STAR-future commited on
Commit
649fefb
·
verified ·
1 Parent(s): ce57c19

add chips/yosys (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. chips/yosys/frontends/blif/blifparse.h +32 -0
  2. chips/yosys/frontends/json/CMakeLists.txt +3 -0
  3. chips/yosys/frontends/json/jsonparse.cc +675 -0
  4. chips/yosys/frontends/liberty/CMakeLists.txt +5 -0
  5. chips/yosys/frontends/liberty/liberty.cc +796 -0
  6. chips/yosys/frontends/rpc/CMakeLists.txt +8 -0
  7. chips/yosys/frontends/rpc/rpc_frontend.cc +597 -0
  8. chips/yosys/frontends/rtlil/.gitignore +4 -0
  9. chips/yosys/frontends/rtlil/CMakeLists.txt +3 -0
  10. chips/yosys/frontends/rtlil/rtlil_frontend.cc +1139 -0
  11. chips/yosys/frontends/slang/CMakeLists.txt +47 -0
  12. chips/yosys/frontends/verific/CMakeLists.txt +79 -0
  13. chips/yosys/frontends/verific/README +36 -0
  14. chips/yosys/frontends/verific/example.sby +16 -0
  15. chips/yosys/frontends/verific/example.sv +18 -0
  16. chips/yosys/frontends/verific/read.cc +235 -0
  17. chips/yosys/frontends/verific/verific.cc +653 -0
  18. chips/yosys/frontends/verific/verific.h +75 -0
  19. chips/yosys/frontends/verific/verific_clocking.cc +321 -0
  20. chips/yosys/frontends/verific/verific_clocking.h +70 -0
  21. chips/yosys/frontends/verific/verific_command.cc +986 -0
  22. chips/yosys/frontends/verific/verific_command.h +75 -0
  23. chips/yosys/frontends/verific/verific_extnets.cc +175 -0
  24. chips/yosys/frontends/verific/verific_importer.cc +2260 -0
  25. chips/yosys/frontends/verific/verific_importer.h +75 -0
  26. chips/yosys/frontends/verific/verific_pass.cc +391 -0
  27. chips/yosys/frontends/verific/verificsva.cc +1949 -0
  28. chips/yosys/frontends/verilog/.gitignore +4 -0
  29. chips/yosys/frontends/verilog/CMakeLists.txt +43 -0
  30. chips/yosys/frontends/verilog/const2ast.cc +271 -0
  31. chips/yosys/frontends/verilog/preproc.cc +1006 -0
  32. chips/yosys/frontends/verilog/preproc.h +84 -0
  33. chips/yosys/frontends/verilog/verilog_error.cc +43 -0
  34. chips/yosys/frontends/verilog/verilog_error.h +31 -0
  35. chips/yosys/frontends/verilog/verilog_frontend.cc +805 -0
  36. chips/yosys/frontends/verilog/verilog_frontend.h +65 -0
  37. chips/yosys/frontends/verilog/verilog_lexer.h +48 -0
  38. chips/yosys/frontends/verilog/verilog_lexer.l +714 -0
  39. chips/yosys/frontends/verilog/verilog_location.h +101 -0
  40. chips/yosys/frontends/verilog/verilog_parser.y +0 -0
  41. chips/yosys/guidelines/GettingStarted +207 -0
  42. chips/yosys/kernel/CMakeLists.txt +203 -0
  43. chips/yosys/kernel/bitpattern.cc +201 -0
  44. chips/yosys/kernel/bitpattern.h +125 -0
  45. chips/yosys/kernel/calc.cc +714 -0
  46. chips/yosys/kernel/cellaigs.cc +531 -0
  47. chips/yosys/kernel/cellaigs.h +52 -0
  48. chips/yosys/kernel/celledges.cc +599 -0
  49. chips/yosys/kernel/celledges.h +63 -0
  50. chips/yosys/kernel/cellhelp.py +99 -0
chips/yosys/frontends/blif/blifparse.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef ABC_BLIFPARSE
21
+ #define ABC_BLIFPARSE
22
+
23
+ #include "kernel/yosys.h"
24
+
25
+ YOSYS_NAMESPACE_BEGIN
26
+
27
+ extern void parse_blif(RTLIL::Design *design, std::istream &f, IdString dff_name, int autoidx_base,
28
+ bool run_clean = false, bool sop_mode = false, bool wideports = false);
29
+
30
+ YOSYS_NAMESPACE_END
31
+
32
+ #endif
chips/yosys/frontends/json/CMakeLists.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ yosys_frontend(json
2
+ jsonparse.cc
3
+ )
chips/yosys/frontends/json/jsonparse.cc ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+
22
+ YOSYS_NAMESPACE_BEGIN
23
+
24
+ struct JsonNode
25
+ {
26
+ char type; // S=String, N=Number, A=Array, D=Dict
27
+ string data_string;
28
+ int64_t data_number;
29
+ vector<JsonNode*> data_array;
30
+ dict<string, JsonNode*> data_dict;
31
+ vector<string> data_dict_keys;
32
+
33
+ JsonNode(std::istream &f)
34
+ {
35
+ type = 0;
36
+ data_number = 0;
37
+
38
+ while (1)
39
+ {
40
+ int ch = f.get();
41
+
42
+ if (ch == EOF)
43
+ log_error("Unexpected EOF in JSON file.\n");
44
+
45
+ if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
46
+ continue;
47
+
48
+ if (ch == '"')
49
+ {
50
+ type = 'S';
51
+
52
+ while (1)
53
+ {
54
+ ch = f.get();
55
+
56
+ if (ch == EOF)
57
+ log_error("Unexpected EOF in JSON string.\n");
58
+
59
+ if (ch == '"')
60
+ break;
61
+
62
+ if (ch == '\\') {
63
+ ch = f.get();
64
+
65
+ switch (ch) {
66
+ case EOF: log_error("Unexpected EOF in JSON string.\n"); break;
67
+ case '"':
68
+ case '/':
69
+ case '\\': break;
70
+ case 'b': ch = '\b'; break;
71
+ case 'f': ch = '\f'; break;
72
+ case 'n': ch = '\n'; break;
73
+ case 'r': ch = '\r'; break;
74
+ case 't': ch = '\t'; break;
75
+ case 'u':
76
+ int val = 0;
77
+ for (int i = 0; i < 4; i++) {
78
+ ch = f.get();
79
+ val <<= 4;
80
+ if (ch >= '0' && '9' >= ch) {
81
+ val += ch - '0';
82
+ } else if (ch >= 'A' && 'F' >= ch) {
83
+ val += 10 + ch - 'A';
84
+ } else if (ch >= 'a' && 'f' >= ch) {
85
+ val += 10 + ch - 'a';
86
+ } else
87
+ log_error("Unexpected non-digit character in \\uXXXX sequence: %c.\n", ch);
88
+ }
89
+ if (val < 128)
90
+ ch = val;
91
+ else
92
+ log_error("Unsupported \\uXXXX sequence in JSON string: %04X.\n", val);
93
+ break;
94
+ }
95
+ }
96
+
97
+ data_string += ch;
98
+ }
99
+
100
+ break;
101
+ }
102
+
103
+ if (('0' <= ch && ch <= '9') || ch == '-')
104
+ {
105
+ bool negative = false;
106
+ type = 'N';
107
+ if (ch == '-') {
108
+ data_number = 0;
109
+ negative = true;
110
+ } else {
111
+ data_number = ch - '0';
112
+ }
113
+
114
+ data_string += ch;
115
+
116
+ while (1)
117
+ {
118
+ ch = f.get();
119
+
120
+ if (ch == EOF)
121
+ break;
122
+
123
+ if (ch == '.')
124
+ goto parse_real;
125
+
126
+ if (ch < '0' || '9' < ch) {
127
+ f.unget();
128
+ break;
129
+ }
130
+
131
+ data_number = data_number*10 + (ch - '0');
132
+ data_string += ch;
133
+ }
134
+
135
+ data_number = negative ? -data_number : data_number;
136
+ data_string = "";
137
+ break;
138
+
139
+ parse_real:
140
+ type = 'S';
141
+ data_number = 0;
142
+ data_string += ch;
143
+
144
+ while (1)
145
+ {
146
+ ch = f.get();
147
+
148
+ if (ch == EOF)
149
+ break;
150
+
151
+ if (ch < '0' || '9' < ch) {
152
+ f.unget();
153
+ break;
154
+ }
155
+
156
+ data_string += ch;
157
+ }
158
+
159
+ break;
160
+ }
161
+
162
+ if (ch == '[')
163
+ {
164
+ type = 'A';
165
+
166
+ while (1)
167
+ {
168
+ ch = f.get();
169
+
170
+ if (ch == EOF)
171
+ log_error("Unexpected EOF in JSON file.\n");
172
+
173
+ if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == ',')
174
+ continue;
175
+
176
+ if (ch == ']')
177
+ break;
178
+
179
+ f.unget();
180
+ data_array.push_back(new JsonNode(f));
181
+ }
182
+
183
+ break;
184
+ }
185
+
186
+ if (ch == '{')
187
+ {
188
+ type = 'D';
189
+
190
+ while (1)
191
+ {
192
+ ch = f.get();
193
+
194
+ if (ch == EOF)
195
+ log_error("Unexpected EOF in JSON file.\n");
196
+
197
+ if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == ',')
198
+ continue;
199
+
200
+ if (ch == '}')
201
+ break;
202
+
203
+ f.unget();
204
+ JsonNode key(f);
205
+
206
+ while (1)
207
+ {
208
+ ch = f.get();
209
+
210
+ if (ch == EOF)
211
+ log_error("Unexpected EOF in JSON file.\n");
212
+
213
+ if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == ':')
214
+ continue;
215
+
216
+ f.unget();
217
+ break;
218
+ }
219
+
220
+ JsonNode *value = new JsonNode(f);
221
+
222
+ if (key.type != 'S')
223
+ log_error("Unexpected non-string key in JSON dict.\n");
224
+
225
+ data_dict[key.data_string] = value;
226
+ data_dict_keys.push_back(key.data_string);
227
+ }
228
+
229
+ break;
230
+ }
231
+
232
+ log_error("Unexpected character in JSON file: '%c'\n", ch);
233
+ }
234
+ }
235
+
236
+ ~JsonNode()
237
+ {
238
+ for (auto it : data_array)
239
+ delete it;
240
+ for (auto &it : data_dict)
241
+ delete it.second;
242
+ }
243
+ };
244
+
245
+ Const json_parse_attr_param_value(JsonNode *node)
246
+ {
247
+ Const value;
248
+
249
+ if (node->type == 'S') {
250
+ string &s = node->data_string;
251
+ size_t cursor = s.find_first_not_of("01xz");
252
+ if (cursor == string::npos) {
253
+ value = Const::from_string(s);
254
+ } else if (s.find_first_not_of(' ', cursor) == string::npos) {
255
+ value = Const(s.substr(0, GetSize(s)-1));
256
+ } else {
257
+ value = Const(s);
258
+ }
259
+ } else
260
+ if (node->type == 'N') {
261
+ value = Const(node->data_number);
262
+ if (node->data_number < 0)
263
+ value.flags |= RTLIL::CONST_FLAG_SIGNED;
264
+ } else
265
+ if (node->type == 'A') {
266
+ log_error("JSON attribute or parameter value is an array.\n");
267
+ } else
268
+ if (node->type == 'D') {
269
+ log_error("JSON attribute or parameter value is a dict.\n");
270
+ } else {
271
+ log_abort();
272
+ }
273
+
274
+ return value;
275
+ }
276
+
277
+ void json_parse_attr_param(RTLIL::Design *design, dict<IdString, Const> &results, JsonNode *node)
278
+ {
279
+ if (node->type != 'D')
280
+ log_error("JSON attributes or parameters node is not a dictionary.\n");
281
+
282
+ for (auto it : node->data_dict)
283
+ {
284
+ IdString key = design->twines().add(RTLIL::escape_id(it.first.c_str()));
285
+ Const value = json_parse_attr_param_value(it.second);
286
+ results[key] = value;
287
+ }
288
+ }
289
+
290
+ void json_import(Design *design, string &modname, JsonNode *node)
291
+ {
292
+ log("Importing module %s from JSON tree.\n", modname);
293
+
294
+ Module *module = new RTLIL::Module(design);
295
+ module->name = design->twines().add(RTLIL::escape_id(modname));
296
+
297
+ if (design->module(module->name))
298
+ log_error("Re-definition of module %s.\n", module);
299
+
300
+ design->add(module);
301
+
302
+ if (node->data_dict.count("attributes"))
303
+ json_parse_attr_param(design, module->attributes, node->data_dict.at("attributes"));
304
+
305
+ if (node->data_dict.count("parameter_default_values"))
306
+ json_parse_attr_param(design, module->parameter_default_values, node->data_dict.at("parameter_default_values"));
307
+
308
+ dict<int, SigBit> signal_bits;
309
+
310
+ if (node->data_dict.count("ports"))
311
+ {
312
+ JsonNode *ports_node = node->data_dict.at("ports");
313
+
314
+ if (ports_node->type != 'D')
315
+ log_error("JSON ports node is not a dictionary.\n");
316
+
317
+ for (int port_id = 1; port_id <= GetSize(ports_node->data_dict_keys); port_id++)
318
+ {
319
+ IdString port_ref = design->twines().add(RTLIL::escape_id(ports_node->data_dict_keys[port_id-1]));
320
+ JsonNode *port_node = ports_node->data_dict.at(ports_node->data_dict_keys[port_id-1]);
321
+
322
+ if (port_node->type != 'D')
323
+ log_error("JSON port node '%s' is not a dictionary.\n", PooledName(design, port_ref).unescape());
324
+
325
+ if (port_node->data_dict.count("direction") == 0)
326
+ log_error("JSON port node '%s' has no direction attribute.\n", PooledName(design, port_ref).unescape());
327
+
328
+ if (port_node->data_dict.count("bits") == 0)
329
+ log_error("JSON port node '%s' has no bits attribute.\n", PooledName(design, port_ref).unescape());
330
+
331
+ JsonNode *port_direction_node = port_node->data_dict.at("direction");
332
+ JsonNode *port_bits_node = port_node->data_dict.at("bits");
333
+
334
+ if (port_direction_node->type != 'S')
335
+ log_error("JSON port node '%s' has non-string direction attribute.\n", PooledName(design, port_ref).unescape());
336
+
337
+ if (port_bits_node->type != 'A')
338
+ log_error("JSON port node '%s' has non-array bits attribute.\n", PooledName(design, port_ref).unescape());
339
+
340
+ Wire *port_wire = module->wire(port_ref);
341
+
342
+ if (port_wire == nullptr)
343
+ port_wire = module->addWire(port_ref, GetSize(port_bits_node->data_array));
344
+
345
+ if (port_node->data_dict.count("upto") != 0) {
346
+ JsonNode *val = port_node->data_dict.at("upto");
347
+ if (val->type == 'N')
348
+ port_wire->upto = val->data_number != 0;
349
+ }
350
+
351
+ if (port_node->data_dict.count("signed") != 0) {
352
+ JsonNode *val = port_node->data_dict.at("signed");
353
+ if (val->type == 'N')
354
+ port_wire->is_signed = val->data_number != 0;
355
+ }
356
+
357
+ if (port_node->data_dict.count("offset") != 0) {
358
+ JsonNode *val = port_node->data_dict.at("offset");
359
+ if (val->type == 'N')
360
+ port_wire->start_offset = val->data_number;
361
+ }
362
+
363
+ if (port_direction_node->data_string == "input") {
364
+ port_wire->port_input = true;
365
+ } else
366
+ if (port_direction_node->data_string == "output") {
367
+ port_wire->port_output = true;
368
+ } else
369
+ if (port_direction_node->data_string == "inout") {
370
+ port_wire->port_input = true;
371
+ port_wire->port_output = true;
372
+ } else
373
+ log_error("JSON port node '%s' has invalid '%s' direction attribute.\n", PooledName(design, port_ref).unescape(), port_direction_node->data_string);
374
+
375
+ port_wire->port_id = port_id;
376
+
377
+ for (int i = 0; i < GetSize(port_bits_node->data_array); i++)
378
+ {
379
+ JsonNode *bitval_node = port_bits_node->data_array.at(i);
380
+ SigBit sigbit(port_wire, i);
381
+
382
+ if (bitval_node->type == 'S') {
383
+ if (bitval_node->data_string == "0")
384
+ module->connect(sigbit, State::S0);
385
+ else if (bitval_node->data_string == "1")
386
+ module->connect(sigbit, State::S1);
387
+ else if (bitval_node->data_string == "x")
388
+ module->connect(sigbit, State::Sx);
389
+ else if (bitval_node->data_string == "z")
390
+ module->connect(sigbit, State::Sz);
391
+ else
392
+ log_error("JSON port node '%s' has invalid '%s' bit string value on bit %d.\n",
393
+ PooledName(design, port_ref).unescape(), bitval_node->data_string, i);
394
+ } else
395
+ if (bitval_node->type == 'N') {
396
+ int bitidx = bitval_node->data_number;
397
+ if (signal_bits.count(bitidx)) {
398
+ if (port_wire->port_output) {
399
+ module->connect(sigbit, signal_bits.at(bitidx));
400
+ } else {
401
+ module->connect(signal_bits.at(bitidx), sigbit);
402
+ signal_bits[bitidx] = sigbit;
403
+ }
404
+ } else {
405
+ signal_bits[bitidx] = sigbit;
406
+ }
407
+ } else
408
+ log_error("JSON port node '%s' has invalid bit value on bit %d.\n", PooledName(design, port_ref).unescape(), i);
409
+ }
410
+ }
411
+
412
+ module->fixup_ports();
413
+ }
414
+
415
+ if (node->data_dict.count("netnames"))
416
+ {
417
+ JsonNode *netnames_node = node->data_dict.at("netnames");
418
+
419
+ if (netnames_node->type != 'D')
420
+ log_error("JSON netnames node is not a dictionary.\n");
421
+
422
+ for (auto &net : netnames_node->data_dict)
423
+ {
424
+ IdString net_ref = design->twines().add(RTLIL::escape_id(net.first));
425
+ JsonNode *net_node = net.second;
426
+
427
+ if (net_node->type != 'D')
428
+ log_error("JSON netname node '%s' is not a dictionary.\n", PooledName(design, net_ref).unescape());
429
+
430
+ if (net_node->data_dict.count("bits") == 0)
431
+ log_error("JSON netname node '%s' has no bits attribute.\n", PooledName(design, net_ref).unescape());
432
+
433
+ JsonNode *bits_node = net_node->data_dict.at("bits");
434
+
435
+ if (bits_node->type != 'A')
436
+ log_error("JSON netname node '%s' has non-array bits attribute.\n", PooledName(design, net_ref).unescape());
437
+
438
+ Wire *wire = module->wire(net_ref);
439
+
440
+ if (wire == nullptr)
441
+ wire = module->addWire(net_ref, GetSize(bits_node->data_array));
442
+
443
+ if (net_node->data_dict.count("upto") != 0) {
444
+ JsonNode *val = net_node->data_dict.at("upto");
445
+ if (val->type == 'N')
446
+ wire->upto = val->data_number != 0;
447
+ }
448
+
449
+ if (net_node->data_dict.count("offset") != 0) {
450
+ JsonNode *val = net_node->data_dict.at("offset");
451
+ if (val->type == 'N')
452
+ wire->start_offset = val->data_number;
453
+ }
454
+
455
+ if (net_node->data_dict.count("signed") != 0) {
456
+ JsonNode *val = net_node->data_dict.at("signed");
457
+ if (val->type == 'N')
458
+ wire->is_signed = val->data_number != 0;
459
+ }
460
+
461
+ for (int i = 0; i < GetSize(bits_node->data_array); i++)
462
+ {
463
+ JsonNode *bitval_node = bits_node->data_array.at(i);
464
+ SigBit sigbit(wire, i);
465
+
466
+ if (bitval_node->type == 'S') {
467
+ if (bitval_node->data_string == "0")
468
+ module->connect(sigbit, State::S0);
469
+ else if (bitval_node->data_string == "1")
470
+ module->connect(sigbit, State::S1);
471
+ else if (bitval_node->data_string == "x")
472
+ module->connect(sigbit, State::Sx);
473
+ else if (bitval_node->data_string == "z")
474
+ module->connect(sigbit, State::Sz);
475
+ else
476
+ log_error("JSON netname node '%s' has invalid '%s' bit string value on bit %d.\n",
477
+ PooledName(design, net_ref).unescape(), bitval_node->data_string, i);
478
+ } else
479
+ if (bitval_node->type == 'N') {
480
+ int bitidx = bitval_node->data_number;
481
+ if (signal_bits.count(bitidx)) {
482
+ if (sigbit != signal_bits.at(bitidx))
483
+ module->connect(sigbit, signal_bits.at(bitidx));
484
+ } else {
485
+ signal_bits[bitidx] = sigbit;
486
+ }
487
+ } else
488
+ log_error("JSON netname node '%s' has invalid bit value on bit %d.\n", PooledName(design, net_ref).unescape(), i);
489
+ }
490
+
491
+ if (net_node->data_dict.count("attributes"))
492
+ json_parse_attr_param(design, wire->attributes, net_node->data_dict.at("attributes"));
493
+ }
494
+ }
495
+
496
+ if (node->data_dict.count("cells"))
497
+ {
498
+ JsonNode *cells_node = node->data_dict.at("cells");
499
+
500
+ if (cells_node->type != 'D')
501
+ log_error("JSON cells node is not a dictionary.\n");
502
+
503
+ for (auto &cell_node_it : cells_node->data_dict)
504
+ {
505
+ IdString cell_ref = design->twines().add(RTLIL::escape_id(cell_node_it.first));
506
+ JsonNode *cell_node = cell_node_it.second;
507
+
508
+ if (cell_node->type != 'D')
509
+ log_error("JSON cells node '%s' is not a dictionary.\n", PooledName(design, cell_ref).unescape());
510
+
511
+ if (cell_node->data_dict.count("type") == 0)
512
+ log_error("JSON cells node '%s' has no type attribute.\n", PooledName(design, cell_ref).unescape());
513
+
514
+ JsonNode *type_node = cell_node->data_dict.at("type");
515
+
516
+ if (type_node->type != 'S')
517
+ log_error("JSON cells node '%s' has a non-string type.\n", PooledName(design, cell_ref).unescape());
518
+
519
+ IdString cell_type = design->twines().add(RTLIL::escape_id(type_node->data_string));
520
+
521
+ Cell *cell = module->addCell(cell_ref, cell_type);
522
+
523
+ if (cell_node->data_dict.count("connections") == 0)
524
+ log_error("JSON cells node '%s' has no connections attribute.\n", PooledName(design, cell_ref).unescape());
525
+
526
+ JsonNode *connections_node = cell_node->data_dict.at("connections");
527
+
528
+ if (connections_node->type != 'D')
529
+ log_error("JSON cells node '%s' has non-dictionary connections attribute.\n", PooledName(design, cell_ref).unescape());
530
+
531
+ for (auto &conn_it : connections_node->data_dict)
532
+ {
533
+ IdString conn_ref = design->twines().add(RTLIL::escape_id(conn_it.first));
534
+ JsonNode *conn_node = conn_it.second;
535
+
536
+ if (conn_node->type != 'A')
537
+ log_error("JSON cells node '%s' connection '%s' is not an array.\n", PooledName(design, cell_ref).unescape(), PooledName(design, conn_ref).unescape());
538
+
539
+ SigSpec sig;
540
+
541
+ for (int i = 0; i < GetSize(conn_node->data_array); i++)
542
+ {
543
+ JsonNode *bitval_node = conn_node->data_array.at(i);
544
+
545
+ if (bitval_node->type == 'S') {
546
+ if (bitval_node->data_string == "0")
547
+ sig.append(State::S0);
548
+ else if (bitval_node->data_string == "1")
549
+ sig.append(State::S1);
550
+ else if (bitval_node->data_string == "x")
551
+ sig.append(State::Sx);
552
+ else if (bitval_node->data_string == "z")
553
+ sig.append(State::Sz);
554
+ else
555
+ log_error("JSON cells node '%s' connection '%s' has invalid '%s' bit string value on bit %d.\n",
556
+ PooledName(design, cell_ref).unescape(), PooledName(design, conn_ref).unescape(), bitval_node->data_string, i);
557
+ } else
558
+ if (bitval_node->type == 'N') {
559
+ int bitidx = bitval_node->data_number;
560
+ if (signal_bits.count(bitidx) == 0)
561
+ signal_bits[bitidx] = module->addWire(NEW_ID);
562
+ sig.append(signal_bits.at(bitidx));
563
+ } else
564
+ log_error("JSON cells node '%s' connection '%s' has invalid bit value on bit %d.\n",
565
+ PooledName(design, cell_ref).unescape(), PooledName(design, conn_ref).unescape(), i);
566
+
567
+ }
568
+
569
+ cell->setPort(conn_ref, sig);
570
+ }
571
+
572
+ if (cell_node->data_dict.count("attributes"))
573
+ json_parse_attr_param(design, cell->attributes, cell_node->data_dict.at("attributes"));
574
+
575
+ if (cell_node->data_dict.count("parameters"))
576
+ json_parse_attr_param(design, cell->parameters, cell_node->data_dict.at("parameters"));
577
+ }
578
+ }
579
+
580
+ if (node->data_dict.count("memories"))
581
+ {
582
+ JsonNode *memories_node = node->data_dict.at("memories");
583
+
584
+ if (memories_node->type != 'D')
585
+ log_error("JSON memories node is not a dictionary.\n");
586
+
587
+ for (auto &memory_node_it : memories_node->data_dict)
588
+ {
589
+ JsonNode *memory_node = memory_node_it.second;
590
+
591
+ RTLIL::Memory *mem = new RTLIL::Memory(module);
592
+ mem->name = design->twines().add(RTLIL::escape_id(memory_node_it.first));
593
+
594
+ if (memory_node->type != 'D')
595
+ log_error("JSON memory node '%s' is not a dictionary.\n", mem);
596
+
597
+ if (memory_node->data_dict.count("width") == 0)
598
+ log_error("JSON memory node '%s' has no width attribute.\n", mem);
599
+ JsonNode *width_node = memory_node->data_dict.at("width");
600
+ if (width_node->type != 'N')
601
+ log_error("JSON memory node '%s' has a non-number width.\n", mem);
602
+ mem->width = width_node->data_number;
603
+
604
+ if (memory_node->data_dict.count("size") == 0)
605
+ log_error("JSON memory node '%s' has no size attribute.\n", mem);
606
+ JsonNode *size_node = memory_node->data_dict.at("size");
607
+ if (size_node->type != 'N')
608
+ log_error("JSON memory node '%s' has a non-number size.\n", mem);
609
+ mem->size = size_node->data_number;
610
+
611
+ mem->start_offset = 0;
612
+ if (memory_node->data_dict.count("start_offset") != 0) {
613
+ JsonNode *val = memory_node->data_dict.at("start_offset");
614
+ if (val->type == 'N')
615
+ mem->start_offset = val->data_number;
616
+ }
617
+
618
+ if (memory_node->data_dict.count("attributes"))
619
+ json_parse_attr_param(design, mem->attributes, memory_node->data_dict.at("attributes"));
620
+
621
+ module->memories[mem->name] = mem;
622
+ }
623
+ }
624
+
625
+ // remove duplicates from connections array
626
+ pool<RTLIL::SigSig> unique_connections(module->connections_.begin(), module->connections_.end());
627
+ module->connections_ = std::vector<RTLIL::SigSig>(unique_connections.begin(), unique_connections.end());
628
+ }
629
+
630
+ struct JsonFrontend : public Frontend {
631
+ JsonFrontend() : Frontend("json", "read JSON file") { }
632
+ void help() override
633
+ {
634
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
635
+ log("\n");
636
+ log(" read_json [filename]\n");
637
+ log("\n");
638
+ log("Load modules from a JSON file into the current design See \"help write_json\"\n");
639
+ log("for a description of the file format.\n");
640
+ log("\n");
641
+ }
642
+ void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
643
+ {
644
+ log_header(design, "Executing JSON frontend.\n");
645
+
646
+ size_t argidx;
647
+ for (argidx = 1; argidx < args.size(); argidx++) {
648
+ // std::string arg = args[argidx];
649
+ // if (arg == "-sop") {
650
+ // sop_mode = true;
651
+ // continue;
652
+ // }
653
+ break;
654
+ }
655
+ extra_args(f, filename, args, argidx);
656
+
657
+ JsonNode root(*f);
658
+
659
+ if (root.type != 'D')
660
+ log_error("JSON root node is not a dictionary.\n");
661
+
662
+ if (root.data_dict.count("modules") != 0)
663
+ {
664
+ JsonNode *modules = root.data_dict.at("modules");
665
+
666
+ if (modules->type != 'D')
667
+ log_error("JSON modules node is not a dictionary.\n");
668
+
669
+ for (auto &it : modules->data_dict)
670
+ json_import(design, it.first, it.second);
671
+ }
672
+ }
673
+ } JsonFrontend;
674
+
675
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/liberty/CMakeLists.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ yosys_frontend(liberty
2
+ liberty.cc
3
+ REQUIRES
4
+ libparse
5
+ )
chips/yosys/frontends/liberty/liberty.cc ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "passes/techmap/libparse.h"
21
+ #include "kernel/register.h"
22
+ #include "kernel/log.h"
23
+ #include <array>
24
+
25
+ YOSYS_NAMESPACE_BEGIN
26
+
27
+ struct token_t {
28
+ char type;
29
+ RTLIL::SigSpec sig;
30
+ token_t (char t) : type(t) { }
31
+ token_t (char t, RTLIL::SigSpec s) : type(t), sig(s) { }
32
+ };
33
+
34
+ static RTLIL::SigSpec parse_func_identifier(RTLIL::Module *module, const char *&expr)
35
+ {
36
+ log_assert(*expr != 0);
37
+
38
+ int id_len = 0;
39
+ while (('a' <= expr[id_len] && expr[id_len] <= 'z') || ('A' <= expr[id_len] && expr[id_len] <= 'Z') ||
40
+ ('0' <= expr[id_len] && expr[id_len] <= '9') || expr[id_len] == '.' ||
41
+ expr[id_len] == '_' || expr[id_len] == '[' || expr[id_len] == ']') id_len++;
42
+
43
+ if (id_len == 0)
44
+ log_error("Expected identifier at `%s' in %s.\n", expr, module);
45
+
46
+ if (id_len == 1 && (*expr == '0' || *expr == '1'))
47
+ return *(expr++) == '0' ? RTLIL::State::S0 : RTLIL::State::S1;
48
+
49
+ std::string id = RTLIL::escape_id(std::string(expr, id_len));
50
+ IdString wire_ref = module->twines().find(id);
51
+ RTLIL::Wire *w = module->wire(wire_ref);
52
+ if (!w)
53
+ log_error("Can't resolve wire name %s in %s.\n", RTLIL::unescape_id(id), module);
54
+
55
+ expr += id_len;
56
+ return w;
57
+ }
58
+
59
+ static bool parse_func_reduce(RTLIL::Module *module, std::vector<token_t> &stack, token_t next_token)
60
+ {
61
+ int top = int(stack.size())-1;
62
+
63
+ if (0 <= top-1 && stack[top].type == 0 && stack[top-1].type == '!') {
64
+ token_t t = token_t(0, module->NotGate(NEW_ID, stack[top].sig));
65
+ stack.pop_back();
66
+ stack.pop_back();
67
+ stack.push_back(t);
68
+ return true;
69
+ }
70
+
71
+ if (0 <= top-1 && stack[top].type == '\'' && stack[top-1].type == 0) {
72
+ token_t t = token_t(0, module->NotGate(NEW_ID, stack[top-1].sig));
73
+ stack.pop_back();
74
+ stack.pop_back();
75
+ stack.push_back(t);
76
+ return true;
77
+ }
78
+
79
+ if (0 <= top && stack[top].type == 0) {
80
+ if (next_token.type == '\'')
81
+ return false;
82
+ stack[top].type = 1;
83
+ return true;
84
+ }
85
+
86
+ if (0 <= top-2 && stack[top-2].type == 1 && stack[top-1].type == '^' && stack[top].type == 1) {
87
+ token_t t = token_t(1, module->XorGate(NEW_ID, stack[top-2].sig, stack[top].sig));
88
+ stack.pop_back();
89
+ stack.pop_back();
90
+ stack.pop_back();
91
+ stack.push_back(t);
92
+ return true;
93
+ }
94
+
95
+ if (0 <= top && stack[top].type == 1) {
96
+ if (next_token.type == '^')
97
+ return false;
98
+ stack[top].type = 2;
99
+ return true;
100
+ }
101
+
102
+ if (0 <= top-1 && stack[top-1].type == 2 && stack[top].type == 2) {
103
+ token_t t = token_t(2, module->AndGate(NEW_ID, stack[top-1].sig, stack[top].sig));
104
+ stack.pop_back();
105
+ stack.pop_back();
106
+ stack.push_back(t);
107
+ return true;
108
+ }
109
+
110
+ if (0 <= top-2 && stack[top-2].type == 2 && (stack[top-1].type == '*' || stack[top-1].type == '&') && stack[top].type == 2) {
111
+ token_t t = token_t(2, module->AndGate(NEW_ID, stack[top-2].sig, stack[top].sig));
112
+ stack.pop_back();
113
+ stack.pop_back();
114
+ stack.pop_back();
115
+ stack.push_back(t);
116
+ return true;
117
+ }
118
+
119
+ if (0 <= top && stack[top].type == 2) {
120
+ if (next_token.type == '*' || next_token.type == '&' || next_token.type == 0 || next_token.type == '(' || next_token.type == '!')
121
+ return false;
122
+ stack[top].type = 3;
123
+ return true;
124
+ }
125
+
126
+ if (0 <= top-2 && stack[top-2].type == 3 && (stack[top-1].type == '+' || stack[top-1].type == '|') && stack[top].type == 3) {
127
+ token_t t = token_t(3, module->OrGate(NEW_ID, stack[top-2].sig, stack[top].sig));
128
+ stack.pop_back();
129
+ stack.pop_back();
130
+ stack.pop_back();
131
+ stack.push_back(t);
132
+ return true;
133
+ }
134
+
135
+ if (0 <= top-2 && stack[top-2].type == '(' && stack[top-1].type == 3 && stack[top].type == ')') {
136
+ token_t t = token_t(0, stack[top-1].sig);
137
+ stack.pop_back();
138
+ stack.pop_back();
139
+ stack.pop_back();
140
+ stack.push_back(t);
141
+ return true;
142
+ }
143
+
144
+ return false;
145
+ }
146
+
147
+ static RTLIL::SigSpec parse_func_expr(RTLIL::Module *module, const char *expr)
148
+ {
149
+ const char *orig_expr = expr;
150
+ std::vector<token_t> stack;
151
+
152
+ while (*expr)
153
+ {
154
+ if (*expr == ' ' || *expr == '\t' || *expr == '\r' || *expr == '\n' || *expr == '"') {
155
+ expr++;
156
+ continue;
157
+ }
158
+
159
+ token_t next_token(0);
160
+ if (*expr == '(' || *expr == ')' || *expr == '\'' || *expr == '!' || *expr == '^' || *expr == '*' || *expr == '+' || *expr == '|' || *expr == '&')
161
+ next_token = token_t(*(expr++));
162
+ else
163
+ next_token = token_t(0, parse_func_identifier(module, expr));
164
+
165
+ while (parse_func_reduce(module, stack, next_token)) {}
166
+ stack.push_back(next_token);
167
+ }
168
+
169
+ while (parse_func_reduce(module, stack, token_t('.'))) {}
170
+
171
+ #if 0
172
+ for (size_t i = 0; i < stack.size(); i++)
173
+ if (stack[i].type < 16)
174
+ log("%3d: %d %s\n", int(i), stack[i].type, log_signal(stack[i].sig));
175
+ else
176
+ log("%3d: %c\n", int(i), stack[i].type);
177
+ #endif
178
+
179
+ if (stack.size() != 1 || stack.back().type != 3)
180
+ log_error("Parser error in function expr `%s'in %s.\n", orig_expr, module);
181
+
182
+ return stack.back().sig;
183
+ }
184
+
185
+ static RTLIL::SigSpec create_tristate(RTLIL::Module *module, RTLIL::SigSpec func, const char *three_state_expr)
186
+ {
187
+ RTLIL::SigSpec three_state = parse_func_expr(module, three_state_expr);
188
+
189
+ auto cell = module->addTribuf(NEW_ID, func, module->NotGate(NEW_ID, three_state), module->addWire(NEW_ID));
190
+ return cell->getPort(ID::Y);
191
+ }
192
+
193
+ static void create_latch_ff_wires(RTLIL::Module *module, const LibertyAst *node)
194
+ {
195
+ module->addWire(RTLIL::escape_id(node->args.at(0)));
196
+ module->addWire(RTLIL::escape_id(node->args.at(1)));
197
+ }
198
+
199
+ static std::pair<RTLIL::SigSpec, RTLIL::SigSpec> find_latch_ff_wires(RTLIL::Module *module, const LibertyAst *node)
200
+ {
201
+ IdString iq_ref = module->twines().find(RTLIL::escape_id(node->args.at(0)));
202
+ IdString iqn_ref = module->twines().find(RTLIL::escape_id(node->args.at(1)));
203
+ auto* iq_wire = module->wire(iq_ref);
204
+ auto* iqn_wire = module->wire(iqn_ref);
205
+ log_assert(iq_wire && iqn_wire);
206
+ return std::make_pair(iq_wire, iqn_wire);
207
+ }
208
+
209
+ static void create_ff(RTLIL::Module *module, const LibertyAst *node)
210
+ {
211
+ auto [iq_sig, iqn_sig] = find_latch_ff_wires(module, node);
212
+ RTLIL::SigSpec clk_sig, data_sig, clear_sig, preset_sig;
213
+ const std::string name = module->name.unescape();
214
+
215
+ std::optional<char> clear_preset_var1;
216
+ std::optional<char> clear_preset_var2;
217
+ for (auto child : node->children) {
218
+ if (child->id == "clocked_on")
219
+ clk_sig = parse_func_expr(module, child->value.c_str());
220
+ if (child->id == "next_state")
221
+ data_sig = parse_func_expr(module, child->value.c_str());
222
+ if (child->id == "clear")
223
+ clear_sig = parse_func_expr(module, child->value.c_str());
224
+ if (child->id == "preset")
225
+ preset_sig = parse_func_expr(module, child->value.c_str());
226
+
227
+ for (auto& [id, var] : {pair{"clear_preset_var1", &clear_preset_var1}, {"clear_preset_var2", &clear_preset_var2}})
228
+ if (child->id == id) {
229
+ if (child->value.size() != 1)
230
+ log_error("Unexpected length of clear_preset_var* value %s in FF cell %s\n", child->value, name);
231
+ *var = child->value[0];
232
+ }
233
+
234
+ }
235
+
236
+ if (clk_sig.size() == 0 || data_sig.size() == 0)
237
+ log_error("FF cell %s has no next_state and/or clocked_on attribute.\n", name);
238
+
239
+ for (auto& [out_sig, cp_var, neg] : {tuple{iq_sig, clear_preset_var1, false}, {iqn_sig, clear_preset_var2, true}}) {
240
+ SigSpec q_sig = out_sig;
241
+ if (neg) {
242
+ q_sig = module->addWire(NEW_ID, out_sig.as_wire());
243
+ module->addNotGate(NEW_ID, q_sig, out_sig);
244
+ }
245
+
246
+ RTLIL::Cell* cell = module->addCell(NEW_ID, IdString::Null);
247
+ cell->setPort(ID::D, data_sig);
248
+ cell->setPort(ID::Q, q_sig);
249
+ cell->setPort(ID::C, clk_sig);
250
+
251
+ if (clear_sig.size() == 0 && preset_sig.size() == 0) {
252
+ cell->type = ID::$_DFF_P_;
253
+ }
254
+
255
+ if (clear_sig.size() == 1 && preset_sig.size() == 0) {
256
+ cell->type = ID::$_DFF_PP0_;
257
+ cell->setPort(ID::R, clear_sig);
258
+ }
259
+
260
+ if (clear_sig.size() == 0 && preset_sig.size() == 1) {
261
+ cell->type = ID::$_DFF_PP1_;
262
+ cell->setPort(ID::R, preset_sig);
263
+ }
264
+
265
+ if (clear_sig.size() == 1 && preset_sig.size() == 1) {
266
+ cell->type = ID::$_DFFSR_PPP_;
267
+
268
+ SigBit s_sig = preset_sig;
269
+ SigBit r_sig = clear_sig;
270
+ if (cp_var && *cp_var != 'X') {
271
+ // Either set or reset dominates
272
+ bool set_dominates;
273
+ if (*cp_var == 'L') {
274
+ set_dominates = neg;
275
+ } else if (*cp_var == 'H') {
276
+ set_dominates = !neg;
277
+ } else {
278
+ log_error("FF cell %s has unsupported clear&preset behavior \'%c\'.\n", name, *cp_var);
279
+ }
280
+ log_debug("cell %s variable %d cp_var %c set dominates? %d\n", name, (int)neg + 1, *cp_var, set_dominates);
281
+ // S&R priority is well-defined now
282
+ if (set_dominates) {
283
+ r_sig = module->AndnotGate(NEW_ID, r_sig, s_sig);
284
+ } else {
285
+ s_sig = module->AndnotGate(NEW_ID, s_sig, r_sig);
286
+ }
287
+ } else {
288
+ log_debug("cell %s variable %d undef c&p behavior\n", name, (int)neg + 1);
289
+ }
290
+
291
+ cell->setPort(ID::S, s_sig);
292
+ cell->setPort(ID::R, r_sig);
293
+ }
294
+
295
+ log_assert(!cell->type.empty());
296
+ }
297
+ }
298
+
299
+ static bool create_latch(RTLIL::Module *module, const LibertyAst *node, bool flag_ignore_miss_data_latch)
300
+ {
301
+ auto [iq_sig, iqn_sig] = find_latch_ff_wires(module, node);
302
+ RTLIL::SigSpec enable_sig, data_sig, clear_sig, preset_sig;
303
+ const std::string name = module->name.unescape();
304
+
305
+ std::optional<char> clear_preset_var1;
306
+ std::optional<char> clear_preset_var2;
307
+ for (auto child : node->children) {
308
+ if (child->id == "enable")
309
+ enable_sig = parse_func_expr(module, child->value.c_str());
310
+ if (child->id == "data_in")
311
+ data_sig = parse_func_expr(module, child->value.c_str());
312
+ if (child->id == "clear")
313
+ clear_sig = parse_func_expr(module, child->value.c_str());
314
+ if (child->id == "preset")
315
+ preset_sig = parse_func_expr(module, child->value.c_str());
316
+
317
+ for (auto& [id, var] : {pair{"clear_preset_var1", &clear_preset_var1}, {"clear_preset_var2", &clear_preset_var2}}) {
318
+ if (child->id == id) {
319
+ if (child->value.size() != 1)
320
+ log_error("Unexpected length of clear_preset_var* value %s in latch cell %s\n", child->value, name);
321
+ *var = child->value[0];
322
+ }
323
+ }
324
+ }
325
+
326
+ if (enable_sig.size() == 0 || data_sig.size() == 0) {
327
+ if (!flag_ignore_miss_data_latch)
328
+ log_error("Latch cell %s has no data_in and/or enable attribute.\n", name);
329
+ else
330
+ log("Ignored latch cell %s with no data_in and/or enable attribute.\n", name);
331
+
332
+ return false;
333
+ }
334
+
335
+ for (auto& [out_sig, cp_var, neg] : {tuple{iq_sig, clear_preset_var1, false}, {iqn_sig, clear_preset_var2, true}}) {
336
+ SigSpec q_sig = out_sig;
337
+ if (neg) {
338
+ q_sig = module->addWire(NEW_ID, out_sig.as_wire());
339
+ module->addNotGate(NEW_ID, q_sig, out_sig);
340
+ }
341
+
342
+ RTLIL::Cell* cell = module->addCell(NEW_ID, "");
343
+ cell->setPort(ID::D, data_sig);
344
+ cell->setPort(ID::Q, q_sig);
345
+ cell->setPort(ID::E, enable_sig);
346
+
347
+ if (clear_sig.size() == 0 && preset_sig.size() == 0) {
348
+ cell->type = ID::$_DLATCH_P_;
349
+ }
350
+
351
+ if (clear_sig.size() == 1 && preset_sig.size() == 0) {
352
+ cell->type = ID::$_DLATCH_PP0_;
353
+ cell->setPort(ID::R, clear_sig);
354
+ }
355
+
356
+ if (clear_sig.size() == 0 && preset_sig.size() == 1) {
357
+ cell->type = ID::$_DLATCH_PP1_;
358
+ cell->setPort(ID::R, preset_sig);
359
+ }
360
+
361
+ if (clear_sig.size() == 1 && preset_sig.size() == 1) {
362
+ cell->type = ID::$_DLATCHSR_PPP_;
363
+
364
+ SigBit s_sig = preset_sig;
365
+ SigBit r_sig = clear_sig;
366
+ if (cp_var && *cp_var != 'X') {
367
+ // Either set or reset dominates
368
+ bool set_dominates;
369
+ if (*cp_var == 'L') {
370
+ set_dominates = neg;
371
+ } else if (*cp_var == 'H') {
372
+ set_dominates = !neg;
373
+ } else {
374
+ log_error("Latch cell %s has unsupported clear&preset behavior \'%c\'.\n", name, *cp_var);
375
+ }
376
+ log_debug("cell %s variable %d cp_var %c set dominates? %d\n", name, (int)neg + 1, *cp_var, set_dominates);
377
+ // S&R priority is well-defined now
378
+ if (set_dominates) {
379
+ r_sig = module->AndnotGate(NEW_ID, r_sig, s_sig);
380
+ } else {
381
+ s_sig = module->AndnotGate(NEW_ID, s_sig, r_sig);
382
+ }
383
+ } else {
384
+ log_debug("cell %s variable %d undef c&p behavior\n", name, (int)neg + 1);
385
+ }
386
+
387
+ cell->setPort(ID::S, s_sig);
388
+ cell->setPort(ID::R, r_sig);
389
+ }
390
+
391
+ log_assert(!cell->type.empty());
392
+ }
393
+
394
+ return true;
395
+ }
396
+
397
+ void parse_type_map(std::map<std::string, std::tuple<int, int, bool>> &type_map, const LibertyAst *ast)
398
+ {
399
+ for (auto type_node : ast->children)
400
+ {
401
+ if (type_node->id != "type" || type_node->args.size() != 1)
402
+ continue;
403
+
404
+ std::string type_name = type_node->args.at(0);
405
+ int bit_width = -1, bit_from = -1, bit_to = -1;
406
+ bool upto = false;
407
+
408
+ for (auto child : type_node->children)
409
+ {
410
+ if (child->id == "base_type" && child->value != "array")
411
+ goto next_type;
412
+
413
+ if (child->id == "data_type" && child->value != "bit")
414
+ goto next_type;
415
+
416
+ if (child->id == "bit_width")
417
+ bit_width = atoi(child->value.c_str());
418
+
419
+ if (child->id == "bit_from")
420
+ bit_from = atoi(child->value.c_str());
421
+
422
+ if (child->id == "bit_to")
423
+ bit_to = atoi(child->value.c_str());
424
+
425
+ if (child->id == "downto" && (child->value == "0" || child->value == "false" || child->value == "FALSE"))
426
+ upto = true;
427
+ }
428
+
429
+ if (bit_width != (std::max(bit_from, bit_to) - std::min(bit_from, bit_to) + 1))
430
+ log_error("Incompatible array type '%s': bit_width=%d, bit_from=%d, bit_to=%d.\n",
431
+ type_name, bit_width, bit_from, bit_to);
432
+
433
+ type_map[type_name] = std::tuple<int, int, bool>(bit_width, std::min(bit_from, bit_to), upto);
434
+ next_type:;
435
+ }
436
+ }
437
+
438
+ struct LibertyFrontend : public Frontend {
439
+ LibertyFrontend() : Frontend("liberty", "read cells from liberty file") { }
440
+ void help() override
441
+ {
442
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
443
+ log("\n");
444
+ log(" read_liberty [filename]\n");
445
+ log("\n");
446
+ log("Read cells from liberty file as modules into current design.\n");
447
+ log("\n");
448
+ log(" -lib\n");
449
+ log(" only create empty blackbox modules\n");
450
+ log("\n");
451
+ log(" -wb\n");
452
+ log(" mark imported cells as whiteboxes\n");
453
+ log("\n");
454
+ log(" -nooverwrite\n");
455
+ log(" ignore re-definitions of modules. (the default behavior is to\n");
456
+ log(" create an error message if the existing module is not a blackbox\n");
457
+ log(" module, and overwrite the existing module if it is a blackbox module.)\n");
458
+ log("\n");
459
+ log(" -overwrite\n");
460
+ log(" overwrite existing modules with the same name\n");
461
+ log("\n");
462
+ log(" -ignore_miss_func\n");
463
+ log(" ignore cells with missing function specification of outputs\n");
464
+ log("\n");
465
+ log(" -ignore_miss_dir\n");
466
+ log(" ignore cells with a missing or invalid direction\n");
467
+ log(" specification on a pin\n");
468
+ log("\n");
469
+ log(" -ignore_miss_data_latch\n");
470
+ log(" ignore latches with missing data and/or enable pins\n");
471
+ log("\n");
472
+ log(" -ignore_buses\n");
473
+ log(" ignore cells with bus interfaces (wide ports)\n");
474
+ log("\n");
475
+ log(" -setattr <attribute_name>\n");
476
+ log(" set the specified attribute (to the value 1) on all loaded modules\n");
477
+ log("\n");
478
+ log(" -unit_delay\n");
479
+ log(" import combinational timing arcs under the unit delay model\n");
480
+ log("\n");
481
+ }
482
+ void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
483
+ {
484
+ bool flag_lib = false;
485
+ bool flag_wb = false;
486
+ bool flag_nooverwrite = false;
487
+ bool flag_overwrite = false;
488
+ bool flag_ignore_miss_func = false;
489
+ bool flag_ignore_miss_dir = false;
490
+ bool flag_ignore_miss_data_latch = false;
491
+ bool flag_ignore_buses = false;
492
+ bool flag_unit_delay = false;
493
+ std::vector<std::string> attributes;
494
+
495
+ size_t argidx;
496
+ for (argidx = 1; argidx < args.size(); argidx++) {
497
+ std::string arg = args[argidx];
498
+ if (arg == "-lib") {
499
+ flag_lib = true;
500
+ continue;
501
+ }
502
+ if (arg == "-wb") {
503
+ flag_wb = true;
504
+ continue;
505
+ }
506
+ if (arg == "-ignore_redef" || arg == "-nooverwrite") {
507
+ flag_nooverwrite = true;
508
+ flag_overwrite = false;
509
+ continue;
510
+ }
511
+ if (arg == "-overwrite") {
512
+ flag_nooverwrite = false;
513
+ flag_overwrite = true;
514
+ continue;
515
+ }
516
+ if (arg == "-ignore_miss_func") {
517
+ flag_ignore_miss_func = true;
518
+ continue;
519
+ }
520
+ if (arg == "-ignore_miss_dir") {
521
+ flag_ignore_miss_dir = true;
522
+ continue;
523
+ }
524
+ if (arg == "-ignore_miss_data_latch") {
525
+ flag_ignore_miss_data_latch = true;
526
+ continue;
527
+ }
528
+ if (arg == "-ignore_buses") {
529
+ flag_ignore_buses = true;
530
+ continue;
531
+ }
532
+ if (arg == "-setattr" && argidx+1 < args.size()) {
533
+ attributes.push_back(RTLIL::escape_id(args[++argidx]));
534
+ continue;
535
+ }
536
+ if (arg == "-unit_delay") {
537
+ flag_unit_delay = true;
538
+ continue;
539
+ }
540
+ break;
541
+ }
542
+ extra_args(f, filename, args, argidx);
543
+
544
+ if (flag_wb && flag_lib)
545
+ log_error("-wb and -lib cannot be specified together!\n");
546
+
547
+ log_header(design, "Executing Liberty frontend: %s\n", filename);
548
+
549
+ LibertyParser parser(*f, filename, liberty_synth_filter);
550
+ int cell_count = 0;
551
+
552
+ std::map<std::string, std::tuple<int, int, bool>> global_type_map;
553
+ parse_type_map(global_type_map, parser.ast);
554
+
555
+ for (auto cell : parser.ast->children)
556
+ {
557
+ if (cell->id != "cell" || cell->args.size() != 1)
558
+ continue;
559
+
560
+ // log("Processing cell type %s.\n", RTLIL::unescape_id(cell_name));
561
+
562
+ std::map<std::string, std::tuple<int, int, bool>> type_map = global_type_map;
563
+ parse_type_map(type_map, cell);
564
+
565
+ RTLIL::Module *module = new RTLIL::Module(design);
566
+ std::string cell_name = RTLIL::escape_id(cell->args.at(0));
567
+ IdString cell_name_ref = design->twines().add(cell_name);
568
+ module->name = cell_name_ref;
569
+
570
+ if (flag_lib)
571
+ module->set_bool_attribute(ID::blackbox);
572
+
573
+ if (flag_wb)
574
+ module->set_bool_attribute(ID::whitebox);
575
+
576
+ const LibertyAst *area = cell->find("area");
577
+ if (area)
578
+ module->attributes[ID::area] = area->value;
579
+
580
+ for (auto &attr : attributes)
581
+ module->attributes[design->twines().add(attr)] = 1;
582
+
583
+ bool simple_comb_cell = true, has_inputs = false, has_outputs = false;
584
+
585
+ for (auto node : cell->children)
586
+ {
587
+ if (node->id == "pin" && node->args.size() == 1) {
588
+ const LibertyAst *dir = node->find("direction");
589
+ if (!dir || (dir->value != "input" && dir->value != "output" && dir->value != "inout" && dir->value != "internal"))
590
+ {
591
+ if (!flag_ignore_miss_dir)
592
+ {
593
+ log_error("Missing or invalid direction for pin %s on cell %s.\n", node->args.at(0), module);
594
+ } else {
595
+ log("Ignoring cell %s with missing or invalid direction for pin %s.\n", module, node->args.at(0));
596
+ delete module;
597
+ goto skip_cell;
598
+ }
599
+ }
600
+ if (!flag_lib || dir->value != "internal")
601
+ module->addWire(RTLIL::escape_id(node->args.at(0)));
602
+ }
603
+
604
+ if (node->id == "bus" && node->args.size() == 1)
605
+ {
606
+ if (flag_ignore_buses) {
607
+ log("Ignoring cell %s with a bus interface %s.\n", module, node->args.at(0));
608
+ delete module;
609
+ goto skip_cell;
610
+ }
611
+
612
+ if (!flag_lib)
613
+ log_error("Error in cell %s: bus interfaces are only supported in -lib mode.\n", RTLIL::unescape_id(cell_name));
614
+
615
+ const LibertyAst *dir = node->find("direction");
616
+
617
+ if (dir == nullptr) {
618
+ const LibertyAst *pin = node->find("pin");
619
+ if (pin != nullptr)
620
+ dir = pin->find("direction");
621
+ }
622
+
623
+ if (!dir || (dir->value != "input" && dir->value != "output" && dir->value != "inout" && dir->value != "internal"))
624
+ log_error("Missing or invalid direction for bus %s on cell %s.\n", node->args.at(0), module);
625
+
626
+ simple_comb_cell = false;
627
+
628
+ if (dir->value == "internal")
629
+ continue;
630
+
631
+ const LibertyAst *bus_type_node = node->find("bus_type");
632
+
633
+ if (!bus_type_node || !type_map.count(bus_type_node->value))
634
+ log_error("Unknown or unsupported type for bus interface %s on cell %s.\n",
635
+ node->args.at(0), RTLIL::unescape_id(cell_name));
636
+
637
+ int bus_type_width = std::get<0>(type_map.at(bus_type_node->value));
638
+ int bus_type_offset = std::get<1>(type_map.at(bus_type_node->value));
639
+ bool bus_type_upto = std::get<2>(type_map.at(bus_type_node->value));
640
+
641
+ Wire *wire = module->addWire(RTLIL::escape_id(node->args.at(0)), bus_type_width);
642
+ wire->start_offset = bus_type_offset;
643
+ wire->upto = bus_type_upto;
644
+
645
+ if (dir->value == "input" || dir->value == "inout")
646
+ wire->port_input = true;
647
+
648
+ if (dir->value == "output" || dir->value == "inout")
649
+ wire->port_output = true;
650
+ }
651
+ }
652
+
653
+ if (!flag_lib)
654
+ {
655
+ // some liberty files do not put ff/latch at the beginning of a cell
656
+ // try to find "ff" or "latch" and create FF/latch _before_ processing all other nodes
657
+ // but first, in case of balloon retention cells, we need all ff/latch output wires
658
+ // defined before we add ff/latch cells
659
+ for (auto node : cell->children)
660
+ {
661
+ if ((node->id == "ff" && node->args.size() == 2) || (node->id == "latch" && node->args.size() == 2))
662
+ create_latch_ff_wires(module, node);
663
+ }
664
+ for (auto node : cell->children)
665
+ {
666
+ if (node->id == "ff" && node->args.size() == 2)
667
+ create_ff(module, node);
668
+ if (node->id == "latch" && node->args.size() == 2)
669
+ if (!create_latch(module, node, flag_ignore_miss_data_latch)) {
670
+ delete module;
671
+ goto skip_cell;
672
+ }
673
+ }
674
+ }
675
+
676
+ for (auto node : cell->children)
677
+ {
678
+ if (node->id == "pin" && node->args.size() == 1)
679
+ {
680
+ const LibertyAst *dir = node->find("direction");
681
+
682
+ if (dir->value == "internal" || dir->value == "inout")
683
+ simple_comb_cell = false;
684
+
685
+ if (flag_lib && dir->value == "internal")
686
+ continue;
687
+
688
+ IdString wire_ref = module->twines().find(RTLIL::escape_id(node->args.at(0)));
689
+ RTLIL::Wire *wire = module->wire(wire_ref);
690
+ log_assert(wire);
691
+
692
+ const LibertyAst *capacitance = node->find("capacitance");
693
+ if (capacitance)
694
+ wire->attributes[ID::capacitance] = capacitance->value;
695
+
696
+ if (dir && dir->value == "inout") {
697
+ wire->port_input = true;
698
+ wire->port_output = true;
699
+ }
700
+
701
+ if (dir && dir->value == "input") {
702
+ has_inputs = true;
703
+ wire->port_input = true;
704
+ continue;
705
+ }
706
+
707
+ if (dir && dir->value == "output") {
708
+ has_outputs = true;
709
+ wire->port_output = true;
710
+ }
711
+
712
+ if (flag_lib)
713
+ continue;
714
+
715
+ const LibertyAst *func = node->find("function");
716
+ if (func == NULL)
717
+ {
718
+ if (dir->value != "inout") { // allow inout with missing function, can be used for power pins
719
+ if (!flag_ignore_miss_func)
720
+ {
721
+ log_error("Missing function on output %s of cell %s.\n", wire, module);
722
+ } else {
723
+ log("Ignoring cell %s with missing function on output %s.\n", module, wire);
724
+ delete module;
725
+ goto skip_cell;
726
+ }
727
+ }
728
+ simple_comb_cell = false;
729
+ } else {
730
+ RTLIL::SigSpec out_sig = parse_func_expr(module, func->value.c_str());
731
+ const LibertyAst *three_state = node->find("three_state");
732
+ if (three_state) {
733
+ out_sig = create_tristate(module, out_sig, three_state->value.c_str());
734
+ simple_comb_cell = false;
735
+ }
736
+ module->connect(RTLIL::SigSig(wire, out_sig));
737
+ }
738
+ }
739
+
740
+ if (node->id == "ff" || node->id == "ff_bank" ||
741
+ node->id == "latch" || node->id == "latch_bank" ||
742
+ node->id == "statetable")
743
+ simple_comb_cell = false;
744
+ }
745
+
746
+ if (simple_comb_cell && has_inputs && has_outputs && flag_unit_delay) {
747
+ module->set_bool_attribute(ID::abc9_box);
748
+
749
+ for (auto wi : module->wires())
750
+ if (wi->port_input) {
751
+ for (auto wo : module->wires())
752
+ if (wo->port_output) {
753
+ RTLIL::Cell *spec = module->addCell(NEW_ID, ID($specify2));
754
+ spec->setParam(ID::SRC_WIDTH, wi->width);
755
+ spec->setParam(ID::DST_WIDTH, wo->width);
756
+ spec->setParam(ID::T_FALL_MAX, 1000);
757
+ spec->setParam(ID::T_FALL_TYP, 1000);
758
+ spec->setParam(ID::T_FALL_MIN, 1000);
759
+ spec->setParam(ID::T_RISE_MAX, 1000);
760
+ spec->setParam(ID::T_RISE_TYP, 1000);
761
+ spec->setParam(ID::T_RISE_MIN, 1000);
762
+ spec->setParam(ID::SRC_DST_POL, false);
763
+ spec->setParam(ID::SRC_DST_PEN, false);
764
+ spec->setParam(ID::FULL, true);
765
+ spec->setPort(ID::EN, Const(1, 1));
766
+ spec->setPort(ID::SRC, wi);
767
+ spec->setPort(ID::DST, wo);
768
+ }
769
+ }
770
+ }
771
+
772
+ if (design->has(cell_name_ref)) {
773
+ Module *existing_mod = design->module(cell_name_ref);
774
+ if (!flag_nooverwrite && !flag_overwrite && !existing_mod->get_bool_attribute(ID::blackbox)) {
775
+ log_error("Re-definition of cell/module %s!\n", RTLIL::unescape_id(cell_name));
776
+ } else if (flag_nooverwrite) {
777
+ log("Ignoring re-definition of module %s.\n", RTLIL::unescape_id(cell_name));
778
+ delete module;
779
+ goto skip_cell;
780
+ } else {
781
+ log("Replacing existing%s module %s.\n", existing_mod->get_bool_attribute(ID::blackbox) ? " blackbox" : "", RTLIL::unescape_id(cell_name));
782
+ design->remove(existing_mod);
783
+ }
784
+ }
785
+
786
+ module->fixup_ports();
787
+ design->add(module);
788
+ cell_count++;
789
+ skip_cell:;
790
+ }
791
+
792
+ log("Imported %d cell types from liberty file.\n", cell_count);
793
+ }
794
+ } LibertyFrontend;
795
+
796
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/rpc/CMakeLists.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ yosys_frontend(rpc
2
+ rpc_frontend.cc
3
+ REQUIRES
4
+ json11
5
+ sha1
6
+ ENABLE_IF
7
+ YOSYS_ENABLE_SPAWN
8
+ )
chips/yosys/frontends/rpc/rpc_frontend.cc ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2019 whitequark <whitequark@whitequark.org>
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
+ // The reason the -path mode of connect_rpc uses byte-oriented and not message-oriented sockets, even though
21
+ // it is a message-oriented interface, is that the system can place various limits on the message size, which
22
+ // are not always transparent or easy to change. Given that generated HDL code get be extremely large, it is
23
+ // unwise to rely on those limits being large enough, and using byte-oriented sockets is guaranteed to work.
24
+
25
+ #ifndef _WIN32
26
+ #include <unistd.h>
27
+ #include <spawn.h>
28
+ #include <sys/wait.h>
29
+ #include <sys/socket.h>
30
+ #include <sys/un.h>
31
+ extern char **environ;
32
+ #endif
33
+
34
+ #include "libs/json11/json11.hpp"
35
+ #include "libs/sha1/sha1.h"
36
+ #include "kernel/yosys.h"
37
+
38
+ YOSYS_NAMESPACE_BEGIN
39
+
40
+ #if defined(_WIN32)
41
+ static std::wstring str2wstr(const std::string &in) {
42
+ if(in == "") return L"";
43
+ std::wstring out;
44
+ out.resize(MultiByteToWideChar(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpMultiByteStr=*/&in[0], /*cbMultiByte=*/(int)in.length(), /*lpWideCharStr=*/NULL, /*cchWideChar=*/0));
45
+ int written = MultiByteToWideChar(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpMultiByteStr=*/&in[0], /*cbMultiByte=*/(int)in.length(), /*lpWideCharStr=*/&out[0], /*cchWideChar=*/(int)out.length());
46
+ log_assert(written == (int)out.length());
47
+ return out;
48
+ }
49
+
50
+ static std::string wstr2str(const std::wstring &in) {
51
+ if(in == L"") return "";
52
+ std::string out;
53
+ out.resize(WideCharToMultiByte(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpWideCharStr=*/&in[0], /*cchWideChar=*/(int)in.length(), /*lpMultiByteStr=*/NULL, /*cbMultiByte=*/0, /*lpDefaultChar=*/NULL, /*lpUsedDefaultChar=*/NULL));
54
+ int written = WideCharToMultiByte(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpWideCharStr=*/&in[0], /*cchWideChar=*/(int)in.length(), /*lpMultiByteStr=*/&out[0], /*cbMultiByte=*/(int)out.length(), /*lpDefaultChar=*/NULL, /*lpUsedDefaultChar=*/NULL);
55
+ log_assert(written == (int)out.length());
56
+ return out;
57
+ }
58
+
59
+ static std::string get_last_error_str() {
60
+ DWORD last_error = GetLastError();
61
+ LPWSTR out_w;
62
+ DWORD size_w = FormatMessageW(/*dwFlags=*/FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_IGNORE_INSERTS, /*lpSource=*/NULL, /*dwMessageId=*/last_error, /*dwLanguageId=*/0, /*lpBuffer=*/(LPWSTR)&out_w, /*nSize=*/0, /*Arguments=*/NULL);
63
+ if (size_w == 0)
64
+ return std::to_string(last_error);
65
+ std::string out = wstr2str(std::wstring(out_w, size_w));
66
+ LocalFree(out_w);
67
+ return out;
68
+ }
69
+ #endif
70
+
71
+ using json11::Json;
72
+
73
+ struct RpcServer {
74
+ std::string name;
75
+
76
+ RpcServer(const std::string &name) : name(name) { }
77
+ virtual ~RpcServer() { }
78
+
79
+ virtual void write(const std::string &data) = 0;
80
+ virtual std::string read() = 0;
81
+
82
+ Json call(const Json &json_request) {
83
+ std::string request;
84
+ json_request.dump(request);
85
+ request += '\n';
86
+ log_debug("RPC frontend request: %s", request);
87
+ write(request);
88
+
89
+ std::string response = read();
90
+ log_debug("RPC frontend response: %s", response);
91
+ std::string error;
92
+ Json json_response = Json::parse(response, error);
93
+ if (json_response.is_null())
94
+ log_cmd_error("parsing JSON failed: %s\n", error);
95
+ if (json_response["error"].is_string())
96
+ log_cmd_error("RPC frontend returned an error: %s\n", json_response["error"].string_value());
97
+ return json_response;
98
+ }
99
+
100
+ std::vector<std::string> get_module_names() {
101
+ Json response = call(Json::object {
102
+ { "method", "modules" },
103
+ });
104
+ bool is_valid = true;
105
+ std::vector<std::string> modules;
106
+ if (response["modules"].is_array()) {
107
+ for (auto &json_module : response["modules"].array_items()) {
108
+ if (json_module.is_string())
109
+ modules.push_back(json_module.string_value());
110
+ else is_valid = false;
111
+ }
112
+ } else is_valid = false;
113
+ if (!is_valid)
114
+ log_cmd_error("RPC frontend returned malformed response: %s\n", response.dump());
115
+ return modules;
116
+ }
117
+
118
+ std::pair<std::string, std::string> derive_module(const RTLIL::Design *design, const std::string &module, const dict<IdString, RTLIL::Const> &parameters) {
119
+ Json::object json_parameters;
120
+ for (auto &param : parameters) {
121
+ std::string type, value;
122
+ if (param.second.flags & RTLIL::CONST_FLAG_REAL) {
123
+ type = "real";
124
+ value = param.second.decode_string();
125
+ } else if (param.second.flags & RTLIL::CONST_FLAG_STRING) {
126
+ type = "string";
127
+ value = param.second.decode_string();
128
+ } else if ((param.second.flags & ~RTLIL::CONST_FLAG_SIGNED) == RTLIL::CONST_FLAG_NONE) {
129
+ type = (param.second.flags & RTLIL::CONST_FLAG_SIGNED) ? "signed" : "unsigned";
130
+ value = param.second.as_string();
131
+ } else
132
+ log_cmd_error("Unserializable constant flags 0x%x\n", param.second.flags);
133
+ json_parameters[design->twines().str(param.first)] = Json::object {
134
+ { "type", type },
135
+ { "value", value },
136
+ };
137
+ }
138
+ Json response = call(Json::object {
139
+ { "method", "derive" },
140
+ { "module", module },
141
+ { "parameters", json_parameters },
142
+ });
143
+ bool is_valid = true;
144
+ std::string frontend, source;
145
+ if (response["frontend"].is_string())
146
+ frontend = response["frontend"].string_value();
147
+ else is_valid = false;
148
+ if (response["source"].is_string())
149
+ source = response["source"].string_value();
150
+ else is_valid = false;
151
+ if (!is_valid)
152
+ log_cmd_error("RPC frontend returned malformed response: %s\n", response.dump());
153
+ return std::make_pair(frontend, source);
154
+ }
155
+ };
156
+
157
+ struct RpcModule : RTLIL::Module {
158
+ using RTLIL::Module::Module;
159
+
160
+ std::shared_ptr<RpcServer> server;
161
+
162
+ RTLIL::IdString derive(RTLIL::Design *design, const dict<RTLIL::IdString, RTLIL::Const> &parameters, bool /*mayfail*/) override {
163
+ std::string stripped_name = name.str();
164
+ if (stripped_name.compare(0, 9, "$abstract") == 0)
165
+ stripped_name = stripped_name.substr(9);
166
+ log_assert(stripped_name[0] == '\\');
167
+
168
+ log_header(design, "Executing RPC frontend `%s' for module `%s'.\n", server->name, stripped_name);
169
+
170
+ std::string parameter_info;
171
+ for (auto &param : parameters) {
172
+ log("Parameter %s = %s\n", PooledName(design, param.first).unescape(), log_signal(RTLIL::SigSpec(param.second)));
173
+ parameter_info += stringf("%s=%s", PooledName(design, param.first).unescape(), log_signal(RTLIL::SigSpec(param.second)));
174
+ }
175
+
176
+ std::string derived_name;
177
+ if (parameters.empty())
178
+ derived_name = stripped_name;
179
+ else if (parameter_info.size() > 60)
180
+ derived_name = "$paramod$" + sha1(parameter_info) + stripped_name;
181
+ else
182
+ derived_name = "$paramod" + stripped_name + parameter_info;
183
+
184
+ IdString derived_ref = design->twines().find(derived_name);
185
+ if (design->has(derived_ref)) {
186
+ log("Found cached RTLIL representation for module `%s'.\n", derived_name);
187
+ } else {
188
+ std::string command, input;
189
+ std::tie(command, input) = server->derive_module(design, stripped_name.substr(1), parameters);
190
+
191
+ std::istringstream input_stream(input);
192
+ RTLIL::Design derived_design;
193
+ Frontend::frontend_call(&derived_design, &input_stream, "<rpc>" + derived_name.substr(8), command);
194
+ derived_design.check();
195
+
196
+ dict<std::string, std::string> name_mangling;
197
+ bool found_derived_top = false;
198
+ for (auto module : derived_design.modules()) {
199
+ std::string original_name = module->name.str();
200
+ if (original_name == stripped_name) {
201
+ found_derived_top = true;
202
+ name_mangling[original_name] = derived_name;
203
+ } else {
204
+ name_mangling[original_name] = derived_name + module->name.str();
205
+ }
206
+ }
207
+ if (!found_derived_top)
208
+ log_cmd_error("RPC frontend did not return requested module `%s`!\n", stripped_name);
209
+
210
+ for (auto module : derived_design.modules())
211
+ for (auto cell : module->cells())
212
+ if (name_mangling.count(cell->type.str()))
213
+ cell->type = cell->twines().add(name_mangling[cell->type.str()]);
214
+
215
+ for (auto module : derived_design.modules_) {
216
+ std::string mangled_name = name_mangling[derived_design.twines().str(module.first)];
217
+
218
+ log("Importing `%s' as `%s'.\n", PooledName(&derived_design, module.first).unescape(), mangled_name);
219
+
220
+ IdString original_name = module.first;
221
+ RTLIL::Module *t = module.second->clone(design, design->twines().add(mangled_name));
222
+ t->attributes.erase(ID::top);
223
+ if (!t->has_attribute(ID::hdlname))
224
+ t->set_string_attribute(ID::hdlname, derived_design.twines().str(original_name));
225
+ }
226
+ }
227
+
228
+ return design->twines().add(derived_name);
229
+ }
230
+
231
+ RTLIL::Module *clone() const override {
232
+ RpcModule *new_mod = new RpcModule(design);
233
+ new_mod->server = server;
234
+ cloneInto(new_mod);
235
+ return new_mod;
236
+ }
237
+ };
238
+
239
+ #if defined(_WIN32)
240
+
241
+ #if defined(_MSC_VER)
242
+ #include <BaseTsd.h>
243
+ typedef SSIZE_T ssize_t;
244
+ #endif
245
+
246
+ struct HandleRpcServer : RpcServer {
247
+ HANDLE hsend, hrecv;
248
+
249
+ HandleRpcServer(const std::string &name, HANDLE hsend, HANDLE hrecv)
250
+ : RpcServer(name), hsend(hsend), hrecv(hrecv) { }
251
+
252
+ void write(const std::string &data) override {
253
+ log_assert(data.length() >= 1 && data.find('\n') == data.length() - 1);
254
+ ssize_t offset = 0;
255
+ do {
256
+ DWORD data_written;
257
+ if (!WriteFile(hsend, &data[offset], data.length() - offset, &data_written, /*lpOverlapped=*/NULL))
258
+ log_cmd_error("WriteFile failed: %s\n", get_last_error_str());
259
+ offset += data_written;
260
+ } while(offset < (ssize_t)data.length());
261
+ }
262
+
263
+ std::string read() override {
264
+ std::string data;
265
+ ssize_t offset = 0;
266
+ while (data.length() == 0 || data[data.length() - 1] != '\n') {
267
+ data.resize(data.length() + 1024);
268
+ DWORD data_read;
269
+ if (!ReadFile(hrecv, &data[offset], data.length() - offset, &data_read, /*lpOverlapped=*/NULL))
270
+ log_cmd_error("ReadFile failed: %s\n", get_last_error_str());
271
+ offset += data_read;
272
+ data.resize(offset);
273
+ size_t term_pos = data.find('\n', offset);
274
+ if (term_pos != data.length() - 1 && term_pos != std::string::npos)
275
+ log_cmd_error("read failed: more than one response\n");
276
+ }
277
+ return data;
278
+ }
279
+
280
+ ~HandleRpcServer() {
281
+ CloseHandle(hsend);
282
+ if (hrecv != hsend)
283
+ CloseHandle(hrecv);
284
+ }
285
+ };
286
+
287
+ #else
288
+
289
+ struct FdRpcServer : RpcServer {
290
+ int fdsend, fdrecv;
291
+ pid_t pid;
292
+
293
+ FdRpcServer(const std::string &name, int fdsend, int fdrecv, pid_t pid = -1)
294
+ : RpcServer(name), fdsend(fdsend), fdrecv(fdrecv), pid(pid) { }
295
+
296
+ void check_pid() {
297
+ if (pid == -1) return;
298
+ // If we're communicating with a process, check that it's still running, or we may get killed with SIGPIPE.
299
+ pid_t wait_result = ::waitpid(pid, NULL, WNOHANG);
300
+ if (wait_result == -1)
301
+ log_cmd_error("waitpid failed: %s\n", strerror(errno));
302
+ if (wait_result == pid)
303
+ log_cmd_error("RPC frontend terminated unexpectedly\n");
304
+ }
305
+
306
+ void write(const std::string &data) override {
307
+ log_assert(data.length() >= 1 && data.find('\n') == data.length() - 1);
308
+ ssize_t offset = 0;
309
+ do {
310
+ check_pid();
311
+ ssize_t result = ::write(fdsend, &data[offset], data.length() - offset);
312
+ if (result == -1)
313
+ log_cmd_error("write failed: %s\n", strerror(errno));
314
+ offset += result;
315
+ } while(offset < (ssize_t)data.length());
316
+ }
317
+
318
+ std::string read() override {
319
+ std::string data;
320
+ ssize_t offset = 0;
321
+ while (data.length() == 0 || data[data.length() - 1] != '\n') {
322
+ data.resize(data.length() + 1024);
323
+ check_pid();
324
+ ssize_t result = ::read(fdrecv, &data[offset], data.length() - offset);
325
+ if (result == -1)
326
+ log_cmd_error("read failed: %s\n", strerror(errno));
327
+ offset += result;
328
+ data.resize(offset);
329
+ size_t term_pos = data.find('\n', offset);
330
+ if (term_pos != data.length() - 1 && term_pos != std::string::npos)
331
+ log_cmd_error("read failed: more than one response\n");
332
+ }
333
+ return data;
334
+ }
335
+
336
+ ~FdRpcServer() {
337
+ close(fdsend);
338
+ if (fdrecv != fdsend)
339
+ close(fdrecv);
340
+ }
341
+ };
342
+
343
+ #endif
344
+
345
+ // RpcFrontend does not inherit from Frontend since it does not read files.
346
+ struct RpcFrontend : public Pass {
347
+ RpcFrontend() : Pass("connect_rpc", "connect to RPC frontend") { }
348
+ void help() override
349
+ {
350
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
351
+ log("\n");
352
+ log(" connect_rpc -exec <command> [args...]\n");
353
+ log(" connect_rpc -path <path>\n");
354
+ log("\n");
355
+ log("Load modules using an out-of-process frontend.\n");
356
+ log("\n");
357
+ log(" -exec <command> [args...]\n");
358
+ log(" run <command> with arguments [args...]. send requests on stdin, read\n");
359
+ log(" responses from stdout.\n");
360
+ log("\n");
361
+ log(" -path <path>\n");
362
+ log(" connect to Unix domain socket at <path>. (Unix)\n");
363
+ log(" connect to bidirectional byte-type named pipe at <path>. (Windows)\n");
364
+ log("\n");
365
+ log("A simple JSON-based, newline-delimited protocol is used for communicating with\n");
366
+ log("the frontend. Yosys requests data from the frontend by sending exactly 1 line\n");
367
+ log("of JSON. Frontend responds with data or error message by replying with exactly\n");
368
+ log("1 line of JSON as well.\n");
369
+ log("\n");
370
+ log(" -> {\"method\": \"modules\"}\n");
371
+ log(" <- {\"modules\": [\"<module-name>\", ...]}\n");
372
+ log(" <- {\"error\": \"<error-message>\"}\n");
373
+ log(" request for the list of modules that can be derived by this frontend.\n");
374
+ log(" the 'hierarchy' command will call back into this frontend if a cell\n");
375
+ log(" with type <module-name> is instantiated in the design.\n");
376
+ log("\n");
377
+ log(" -> {\"method\": \"derive\", \"module\": \"<module-name\">, \"parameters\": {\n");
378
+ log(" \"<param-name>\": {\"type\": \"[unsigned|signed|string|real]\",\n");
379
+ log(" \"value\": \"<param-value>\"}, ...}}\n");
380
+ log(" <- {\"frontend\": \"[rtlil|verilog|...]\",\"source\": \"<source>\"}}\n");
381
+ log(" <- {\"error\": \"<error-message>\"}\n");
382
+ log(" request for the module <module-name> to be derived for a specific set of\n");
383
+ log(" parameters. <param-name> starts with \\ for named parameters, and with $\n");
384
+ log(" for unnamed parameters, which are numbered starting at 1.<param-value>\n");
385
+ log(" for integer parameters is always specified as a binary string of\n");
386
+ log(" unlimited precision. the <source> returned by the frontend is\n");
387
+ log(" hygienically parsedby a built-in Yosys <frontend>, allowing the RPC\n");
388
+ log(" frontend to return anyconvenient representation of the module. the\n");
389
+ log(" derived module is cached,so the response should be the same whenever the\n");
390
+ log(" same set of parameters is provided.\n");
391
+ }
392
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
393
+ {
394
+ log_header(design, "Connecting to RPC frontend.\n");
395
+
396
+ std::vector<std::string> command;
397
+ std::string path;
398
+ size_t argidx;
399
+ for (argidx = 1; argidx < args.size(); argidx++) {
400
+ std::string arg = args[argidx];
401
+ if (arg == "-exec" && argidx+1 < args.size()) {
402
+ command.insert(command.begin(), args.begin() + argidx + 1, args.end());
403
+ argidx = args.size()-1;
404
+ continue;
405
+ }
406
+ if (arg == "-path" && argidx+1 < args.size()) {
407
+ path = args[++argidx];
408
+ continue;
409
+ }
410
+ break;
411
+ }
412
+ extra_args(args, argidx, design);
413
+
414
+ if ((!command.empty()) + (!path.empty()) != 1)
415
+ log_cmd_error("Exactly one of -exec, -unix must be specified.\n");
416
+
417
+ std::shared_ptr<RpcServer> server;
418
+ if (!command.empty()) {
419
+ std::string command_line;
420
+ bool first = true;
421
+ for (auto &arg : command) {
422
+ if (!first) command_line += ' ';
423
+ command_line += arg;
424
+ first = false;
425
+ }
426
+
427
+ #ifdef _WIN32
428
+ std::wstring command_w = str2wstr(command[0]);
429
+ std::wstring command_path_w;
430
+ std::wstring command_line_w = str2wstr(command_line);
431
+ DWORD command_path_len_w;
432
+ SECURITY_ATTRIBUTES pipe_attr = {};
433
+ HANDLE send_r = NULL, send_w = NULL, recv_r = NULL, recv_w = NULL;
434
+ STARTUPINFOW startup_info = {};
435
+ PROCESS_INFORMATION proc_info = {};
436
+
437
+ command_path_len_w = SearchPathW(/*lpPath=*/NULL, /*lpFileName=*/command_w.c_str(), /*lpExtension=*/L".exe", /*nBufferLength=*/0, /*lpBuffer=*/NULL, /*lpFilePart=*/NULL);
438
+ if (command_path_len_w == 0) {
439
+ log_error("SearchPathW failed: %s\n", get_last_error_str());
440
+ goto cleanup_exec;
441
+ }
442
+ command_path_w.resize(command_path_len_w - 1);
443
+ command_path_len_w = SearchPathW(/*lpPath=*/NULL, /*lpFileName=*/command_w.c_str(), /*lpExtension=*/L".exe", /*nBufferLength=*/command_path_len_w, /*lpBuffer=*/&command_path_w[0], /*lpFilePart=*/NULL);
444
+ log_assert(command_path_len_w == command_path_w.length());
445
+
446
+ pipe_attr.nLength = sizeof(pipe_attr);
447
+ pipe_attr.bInheritHandle = TRUE;
448
+ pipe_attr.lpSecurityDescriptor = NULL;
449
+ if (!CreatePipe(&send_r, &send_w, &pipe_attr, /*nSize=*/0)) {
450
+ log_error("CreatePipe failed: %s\n", get_last_error_str());
451
+ goto cleanup_exec;
452
+ }
453
+ if (!SetHandleInformation(send_w, HANDLE_FLAG_INHERIT, 0)) {
454
+ log_error("SetHandleInformation failed: %s\n", get_last_error_str());
455
+ goto cleanup_exec;
456
+ }
457
+ if (!CreatePipe(&recv_r, &recv_w, &pipe_attr, /*nSize=*/0)) {
458
+ log_error("CreatePipe failed: %s\n", get_last_error_str());
459
+ goto cleanup_exec;
460
+ }
461
+ if (!SetHandleInformation(recv_r, HANDLE_FLAG_INHERIT, 0)) {
462
+ log_error("SetHandleInformation failed: %s\n", get_last_error_str());
463
+ goto cleanup_exec;
464
+ }
465
+
466
+ startup_info.cb = sizeof(startup_info);
467
+ startup_info.hStdInput = send_r;
468
+ startup_info.hStdOutput = recv_w;
469
+ startup_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
470
+ startup_info.dwFlags |= STARTF_USESTDHANDLES;
471
+ if (!CreateProcessW(/*lpApplicationName=*/command_path_w.c_str(), /*lpCommandLine=*/&command_line_w[0], /*lpProcessAttributes=*/NULL, /*lpThreadAttributes=*/NULL, /*bInheritHandles=*/TRUE, /*dwCreationFlags=*/0, /*lpEnvironment=*/NULL, /*lpCurrentDirectory=*/NULL, &startup_info, &proc_info)) {
472
+ log_error("CreateProcessW failed: %s\n", get_last_error_str());
473
+ goto cleanup_exec;
474
+ }
475
+ CloseHandle(proc_info.hProcess);
476
+ CloseHandle(proc_info.hThread);
477
+
478
+ server = std::make_shared<HandleRpcServer>(path, send_w, recv_r);
479
+ send_w = NULL;
480
+ recv_r = NULL;
481
+
482
+ cleanup_exec:
483
+ if (send_r != NULL) CloseHandle(send_r);
484
+ if (send_w != NULL) CloseHandle(send_w);
485
+ if (recv_r != NULL) CloseHandle(recv_r);
486
+ if (recv_w != NULL) CloseHandle(recv_w);
487
+ #else
488
+ std::vector<char *> argv;
489
+ int send[2] = {-1,-1}, recv[2] = {-1,-1};
490
+ posix_spawn_file_actions_t file_actions, *file_actions_p = NULL;
491
+ pid_t pid;
492
+
493
+ for (auto &arg : command)
494
+ argv.push_back(&arg[0]);
495
+ argv.push_back(nullptr);
496
+
497
+ if (pipe(send) != 0) {
498
+ log_error("pipe failed: %s\n", strerror(errno));
499
+ goto cleanup_exec;
500
+ }
501
+ if (pipe(recv) != 0) {
502
+ log_error("pipe failed: %s\n", strerror(errno));
503
+ goto cleanup_exec;
504
+ }
505
+
506
+ if (posix_spawn_file_actions_init(&file_actions) != 0) {
507
+ log_error("posix_spawn_file_actions_init failed: %s\n", strerror(errno));
508
+ goto cleanup_exec;
509
+ }
510
+ file_actions_p = &file_actions;
511
+ if (posix_spawn_file_actions_adddup2(file_actions_p, send[0], STDIN_FILENO) != 0) {
512
+ log_error("posix_spawn_file_actions_adddup2 failed: %s\n", strerror(errno));
513
+ goto cleanup_exec;
514
+ }
515
+ if (posix_spawn_file_actions_addclose(file_actions_p, send[1]) != 0) {
516
+ log_error("posix_spawn_file_actions_addclose failed: %s\n", strerror(errno));
517
+ goto cleanup_exec;
518
+ }
519
+ if (posix_spawn_file_actions_adddup2(file_actions_p, recv[1], STDOUT_FILENO) != 0) {
520
+ log_error("posix_spawn_file_actions_adddup2 failed: %s\n", strerror(errno));
521
+ goto cleanup_exec;
522
+ }
523
+ if (posix_spawn_file_actions_addclose(file_actions_p, recv[0]) != 0) {
524
+ log_error("posix_spawn_file_actions_addclose failed: %s\n", strerror(errno));
525
+ goto cleanup_exec;
526
+ }
527
+
528
+ if (posix_spawnp(&pid, argv[0], file_actions_p, /*attrp=*/NULL, argv.data(), environ) != 0) {
529
+ log_error("posix_spawnp failed: %s\n", strerror(errno));
530
+ goto cleanup_exec;
531
+ }
532
+
533
+ server = std::make_shared<FdRpcServer>(command_line, send[1], recv[0], pid);
534
+ send[1] = -1;
535
+ recv[0] = -1;
536
+
537
+ cleanup_exec:
538
+ if (send[0] != -1) close(send[0]);
539
+ if (send[1] != -1) close(send[1]);
540
+ if (recv[0] != -1) close(recv[0]);
541
+ if (recv[1] != -1) close(recv[1]);
542
+ if (file_actions_p != NULL)
543
+ posix_spawn_file_actions_destroy(file_actions_p);
544
+ #endif
545
+ } else if (!path.empty()) {
546
+ #ifdef _WIN32
547
+ std::wstring path_w = str2wstr(path);
548
+ HANDLE h;
549
+
550
+ h = CreateFileW(path_w.c_str(), GENERIC_READ|GENERIC_WRITE, /*dwShareMode=*/0, /*lpSecurityAttributes=*/NULL, /*dwCreationDisposition=*/OPEN_EXISTING, /*dwFlagsAndAttributes=*/0, /*hTemplateFile=*/NULL);
551
+ if (h == INVALID_HANDLE_VALUE) {
552
+ log_error("CreateFileW failed: %s\n", get_last_error_str());
553
+ goto cleanup_path;
554
+ }
555
+
556
+ server = std::make_shared<HandleRpcServer>(path, h, h);
557
+
558
+ cleanup_path:
559
+ ;
560
+ #else
561
+ struct sockaddr_un addr;
562
+ addr.sun_family = AF_UNIX;
563
+ strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
564
+
565
+ int fd = socket(AF_UNIX, SOCK_STREAM, 0);
566
+ if (fd == -1) {
567
+ log_error("socket failed: %s\n", strerror(errno));
568
+ goto cleanup_path;
569
+ }
570
+
571
+ if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
572
+ log_error("connect failed: %s\n", strerror(errno));
573
+ goto cleanup_path;
574
+ }
575
+
576
+ server = std::make_shared<FdRpcServer>(path, fd, fd);
577
+ fd = -1;
578
+
579
+ cleanup_path:
580
+ if (fd != -1) close(fd);
581
+ #endif
582
+ }
583
+
584
+ if (!server)
585
+ log_cmd_error("Failed to connect to RPC frontend.\n");
586
+
587
+ for (auto &module_name : server->get_module_names()) {
588
+ log("Linking module `%s'.\n", module_name);
589
+ RpcModule *module = new RpcModule(design);
590
+ module->name = design->twines().add("$abstract\\" + module_name);
591
+ module->server = server;
592
+ design->add(module);
593
+ }
594
+ }
595
+ } RpcFrontend;
596
+
597
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/rtlil/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ rtlil_lexer.cc
2
+ rtlil_parser.output
3
+ rtlil_parser.tab.cc
4
+ rtlil_parser.tab.hh
chips/yosys/frontends/rtlil/CMakeLists.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ yosys_frontend(rtlil
2
+ rtlil_frontend.cc
3
+ )
chips/yosys/frontends/rtlil/rtlil_frontend.cc ADDED
@@ -0,0 +1,1139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * A handwritten recursive-descent parser for the RTLIL text representation.
21
+ *
22
+ */
23
+
24
+ #include "kernel/register.h"
25
+ #include "kernel/log.h"
26
+ #include "kernel/rtlil.h"
27
+ #include "kernel/utils.h"
28
+ #include "kernel/twine.h"
29
+ #include <charconv>
30
+ #include <deque>
31
+ #include <optional>
32
+
33
+ YOSYS_NAMESPACE_BEGIN
34
+
35
+ struct RTLILFrontendWorker {
36
+ std::istream *f = nullptr;
37
+ RTLIL::Design *design;
38
+ bool flag_nooverwrite = false;
39
+ bool flag_overwrite = false;
40
+ bool flag_lib = false;
41
+ bool flag_legalize = false;
42
+
43
+ int line_num;
44
+ std::string line_buf;
45
+ // Substring of line_buf. Always newline-terminated, thus never empty.
46
+ std::string_view line;
47
+
48
+ RTLIL::Module *current_module;
49
+ dict<RTLIL::IdString, RTLIL::Const> attrbuf;
50
+ std::vector<std::vector<RTLIL::SwitchRule*>*> switch_stack;
51
+ std::vector<RTLIL::CaseRule*> case_stack;
52
+
53
+ dict<size_t, IdString> twine_remap;
54
+ std::vector<IdString> twine_parser_holds;
55
+
56
+ struct TwineDesc {
57
+ enum Kind { Root, Suffix } kind;
58
+ std::string text;
59
+ size_t parent = 0;
60
+ bool materializing = false;
61
+ };
62
+ dict<size_t, TwineDesc> twine_descs;
63
+
64
+
65
+
66
+ template <typename... Args>
67
+ [[noreturn]]
68
+ void error(FmtString<TypeIdentity<Args>...> fmt, const Args &... args)
69
+ {
70
+ log_error("Parser error in line %d: %s\n", line_num, fmt.format(args...));
71
+ }
72
+
73
+ template <typename... Args>
74
+ void warning(FmtString<TypeIdentity<Args>...> fmt, const Args &... args)
75
+ {
76
+ log_warning("In line %d: %s\n", line_num, fmt.format(args...));
77
+ }
78
+
79
+ // May return an empty line if the stream is not good().
80
+ void advance_to_next_nonempty_line()
81
+ {
82
+ if (!f->good()) {
83
+ line = "\n";
84
+ return;
85
+ }
86
+ while (true) {
87
+ std::getline(*f, line_buf);
88
+ line_num++;
89
+ if (line_buf.empty() || line_buf[line_buf.size() - 1] != '\n')
90
+ line_buf += '\n';
91
+ line = line_buf;
92
+ consume_whitespace_and_comments();
93
+ if (line[0] != '\n' || !f->good())
94
+ break;
95
+ }
96
+ }
97
+
98
+ void consume_whitespace_and_comments()
99
+ {
100
+ while (true) {
101
+ switch (line[0]) {
102
+ case ' ':
103
+ case '\t':
104
+ line = line.substr(1);
105
+ break;
106
+ case '#':
107
+ line = "\n";
108
+ return;
109
+ default:
110
+ return;
111
+ }
112
+ }
113
+ }
114
+
115
+ bool try_parse_keyword(std::string_view keyword)
116
+ {
117
+ int keyword_size = keyword.size();
118
+ if (keyword != line.substr(0, keyword_size))
119
+ return false;
120
+ // This index is safe because `line` is always newline-terminated
121
+ // and `keyword` never contains a newline.
122
+ char ch = line[keyword_size];
123
+ if (ch >= 'a' && ch <= 'z')
124
+ return false;
125
+ line = line.substr(keyword_size);
126
+ consume_whitespace_and_comments();
127
+ return true;
128
+ }
129
+
130
+ std::string error_token()
131
+ {
132
+ std::string result;
133
+ for (char ch : line) {
134
+ if (ch == '\n' || ch == ' ' || ch == '\t')
135
+ break;
136
+ result += ch;
137
+ }
138
+ return result;
139
+ }
140
+
141
+ void expect_keyword(std::string_view keyword)
142
+ {
143
+ if (!try_parse_keyword(keyword))
144
+ error("Expected token `%s', got `%s'.", keyword, error_token());
145
+ }
146
+
147
+ bool try_parse_char(char ch)
148
+ {
149
+ if (line[0] != ch)
150
+ return false;
151
+ line = line.substr(1);
152
+ consume_whitespace_and_comments();
153
+ return true;
154
+ }
155
+
156
+ void expect_char(char ch)
157
+ {
158
+ if (!try_parse_char(ch))
159
+ error("Expected `%c', got `%s'.", ch, error_token());
160
+ }
161
+
162
+ bool try_parse_eol()
163
+ {
164
+ if (line[0] != '\n')
165
+ return false;
166
+ advance_to_next_nonempty_line();
167
+ return true;
168
+ }
169
+
170
+ void expect_eol()
171
+ {
172
+ if (!try_parse_eol())
173
+ error("Expected EOL, got `%s'.", error_token());
174
+ }
175
+
176
+ std::optional<std::string> try_parse_id()
177
+ {
178
+ char ch = line[0];
179
+ if (ch != '\\' && ch != '$')
180
+ return std::nullopt;
181
+ int idx = 1;
182
+ while (true) {
183
+ ch = line[idx];
184
+ if (ch <= ' ' && (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'))
185
+ break;
186
+ ++idx;
187
+ }
188
+ std::string result(line.substr(0, idx));
189
+ line = line.substr(idx);
190
+ consume_whitespace_and_comments();
191
+ return result;
192
+ }
193
+
194
+ std::string parse_id()
195
+ {
196
+ std::optional<std::string> id = try_parse_id();
197
+ if (!id.has_value())
198
+ error("Expected ID, got `%s'.", error_token());
199
+ return std::move(*id);
200
+ }
201
+
202
+ long long parse_integer()
203
+ {
204
+ long long result = parse_integer_alone();
205
+ consume_whitespace_and_comments();
206
+ return result;
207
+ }
208
+
209
+ long long parse_integer_alone()
210
+ {
211
+ int idx = 0;
212
+ if (line[idx] == '-')
213
+ ++idx;
214
+ while (true) {
215
+ char ch = line[idx];
216
+ if (ch < '0' || ch > '9')
217
+ break;
218
+ ++idx;
219
+ }
220
+ long long result;
221
+ if (std::from_chars(line.data(), line.data() + idx, result, 10).ec != std::errc{})
222
+ error("Invalid integer `%s'.", error_token());
223
+ line = line.substr(idx);
224
+ return result;
225
+ }
226
+
227
+ std::string parse_string()
228
+ {
229
+ if (line[0] != '\"')
230
+ error("Expected string, got `%s'.", error_token());
231
+ std::string str;
232
+ int idx = 1;
233
+ while (true) {
234
+ int start_idx = idx;
235
+ char ch;
236
+ while (true) {
237
+ ch = line[idx];
238
+ if (ch == '"' || ch == '\n' || ch == '\\' || ch == 0)
239
+ break;
240
+ ++idx;
241
+ }
242
+ str.append(line.data() + start_idx, line.data() + idx);
243
+ ++idx;
244
+ if (ch == '"')
245
+ break;
246
+ if (ch == 0)
247
+ error("Null byte in string literal: `%s'.", line);
248
+ if (ch == '\n')
249
+ error("Unterminated string literal: `%s'.", line);
250
+ ch = line[idx++];
251
+ if (ch == 'n') {
252
+ ch = '\n';
253
+ } else if (ch == 't') {
254
+ ch = '\t';
255
+ } else if (ch >= '0' && ch <= '7') {
256
+ int v = ch - '0';
257
+ char next_ch = line[idx + 1];
258
+ if (next_ch >= '0' && next_ch <= '7') {
259
+ ++idx;
260
+ v = v*8 + (next_ch - '0');
261
+ next_ch = line[idx + 1];
262
+ if (next_ch >= '0' && next_ch <= '7') {
263
+ ++idx;
264
+ v = v*8 + (next_ch - '0');
265
+ }
266
+ }
267
+ ch = v;
268
+ }
269
+ str += ch;
270
+ }
271
+ line = line.substr(idx);
272
+ consume_whitespace_and_comments();
273
+ return str;
274
+ }
275
+
276
+ RTLIL::Const parse_const()
277
+ {
278
+ if (line[0] == '"')
279
+ return RTLIL::Const(parse_string());
280
+
281
+ bool negative_value = line[0] == '-';
282
+ long long width = parse_integer_alone();
283
+ // Can't test value<0 here because we need to stop parsing after '-0'
284
+ if (negative_value || line[0] != '\'') {
285
+ if (width < INT_MIN || width > INT_MAX)
286
+ error("Integer %lld out of range before `%s'.", width, error_token());
287
+ consume_whitespace_and_comments();
288
+ return RTLIL::Const(width);
289
+ }
290
+
291
+ int idx = 1;
292
+ bool is_signed = line[1] == 's';
293
+ if (is_signed)
294
+ ++idx;
295
+
296
+ std::vector<RTLIL::State> bits;
297
+ if (width >= RTLIL::WIDTH_LIMIT)
298
+ error("Constant width %lld out of range before `%s`.", width, error_token());
299
+ bits.reserve(width);
300
+ int start_idx = idx;
301
+ while (true) {
302
+ RTLIL::State bit;
303
+ switch (line[idx]) {
304
+ case '0': bit = RTLIL::S0; break;
305
+ case '1': bit = RTLIL::S1; break;
306
+ case 'x': bit = RTLIL::Sx; break;
307
+ case 'z': bit = RTLIL::Sz; break;
308
+ case 'm': bit = RTLIL::Sm; break;
309
+ case '-': bit = RTLIL::Sa; break;
310
+ default: goto done;
311
+ }
312
+ bits.push_back(bit);
313
+ ++idx;
314
+ }
315
+ done:
316
+ if (start_idx < idx)
317
+ std::reverse(bits.begin(), bits.end());
318
+
319
+ if (GetSize(bits) > width)
320
+ bits.resize(width);
321
+ else if (GetSize(bits) < width) {
322
+ RTLIL::State extbit = RTLIL::Sx;
323
+ if (!bits.empty()) {
324
+ extbit = bits.back();
325
+ if (extbit == RTLIL::S1)
326
+ extbit = RTLIL::S0;
327
+ }
328
+ bits.resize(width, extbit);
329
+ }
330
+
331
+ RTLIL::Const val(std::move(bits));
332
+ if (is_signed)
333
+ val.flags |= RTLIL::CONST_FLAG_SIGNED;
334
+ line = line.substr(idx);
335
+ consume_whitespace_and_comments();
336
+ return val;
337
+ }
338
+
339
+ RTLIL::Wire *legalize_wire(RTLIL::IdString id)
340
+ {
341
+ int wires_size = current_module->wires_size();
342
+ if (wires_size == 0)
343
+ error("No wires found for legalization");
344
+ int hash = hash_ops<RTLIL::IdString>::hash(id).yield();
345
+ RTLIL::Wire *wire = current_module->wire_at(abs(hash % wires_size));
346
+ log("Legalizing wire `%s' to `%s'.\n", PooledName(current_module->design, id).unescape(), wire);
347
+ return wire;
348
+ }
349
+
350
+ RTLIL::SigSpec parse_sigspec()
351
+ {
352
+ RTLIL::SigSpec sig;
353
+
354
+ if (try_parse_char('{')) {
355
+ std::vector<SigSpec> parts;
356
+ while (!try_parse_char('}'))
357
+ parts.push_back(parse_sigspec());
358
+ for (auto it = parts.rbegin(); it != parts.rend(); ++it)
359
+ sig.append(std::move(*it));
360
+ } else if (std::optional<IdString> handle = try_parse_twine_handle()) {
361
+ IdString ref = *handle;
362
+ RTLIL::Wire *wire = current_module->wire(ref);
363
+ if (wire == nullptr) {
364
+ if (flag_legalize)
365
+ wire = legalize_wire(ref);
366
+ else
367
+ error("Wire %s not found.", design->twines().str(ref).c_str());
368
+ }
369
+ sig = RTLIL::SigSpec(wire);
370
+ } else {
371
+ // We could add a special path for parsing IdStrings that must already exist,
372
+ // as here.
373
+ // We don't need to addref/release in this case.
374
+ std::optional<std::string> id = try_parse_id();
375
+ if (id.has_value()) {
376
+ RTLIL::Wire *wire = current_module->wire(design->twines().find(*id));
377
+ if (wire == nullptr) {
378
+ if (flag_legalize)
379
+ wire = legalize_wire(design->twines().add(*id));
380
+ else
381
+ error("Wire `%s' not found.", *id);
382
+ }
383
+ sig = RTLIL::SigSpec(wire);
384
+ } else {
385
+ sig = RTLIL::SigSpec(parse_const());
386
+ }
387
+ }
388
+
389
+ while (try_parse_char('[')) {
390
+ int left = parse_integer();
391
+ if (left >= sig.size() || left < 0) {
392
+ if (flag_legalize) {
393
+ int legalized;
394
+ if (sig.size() == 0)
395
+ legalized = 0;
396
+ else
397
+ legalized = std::max(0, std::min(left, sig.size() - 1));
398
+ log("Legalizing bit index %d to %d.\n", left, legalized);
399
+ left = legalized;
400
+ } else {
401
+ error("bit index %d out of range", left);
402
+ }
403
+ }
404
+ if (try_parse_char(':')) {
405
+ int right = parse_integer();
406
+ if (right < 0) {
407
+ if (flag_legalize) {
408
+ log("Legalizing bit index %d to %d.\n", right, 0);
409
+ right = 0;
410
+ } else
411
+ error("bit index %d out of range", right);
412
+ }
413
+ if (left < right) {
414
+ if (flag_legalize) {
415
+ log("Legalizing bit index %d to %d.\n", left, right);
416
+ left = right;
417
+ } else
418
+ error("invalid slice [%d:%d]", left, right);
419
+ }
420
+ if (flag_legalize && left >= sig.size())
421
+ log("Legalizing slice %d:%d by igoring it\n", left, right);
422
+ else
423
+ sig = sig.extract(right, left - right + 1);
424
+ } else {
425
+ if (flag_legalize && left >= sig.size())
426
+ log("Legalizing slice %d by igoring it\n", left);
427
+ else
428
+ sig = sig.extract(left);
429
+ }
430
+ expect_char(']');
431
+ }
432
+
433
+ return sig;
434
+ }
435
+
436
+ void parse_module()
437
+ {
438
+ IdString module_name = parse_twine();
439
+ expect_eol();
440
+
441
+ bool delete_current_module = false;
442
+ if (design->has(module_name)) {
443
+ RTLIL::Module *existing_mod = design->module(module_name);
444
+ if (!flag_overwrite && (flag_lib || (attrbuf.count(ID::blackbox) && attrbuf.at(ID::blackbox).as_bool()))) {
445
+ log("Ignoring blackbox re-definition of module %s.\n", design->twines().str(module_name));
446
+ delete_current_module = true;
447
+ } else if (!flag_nooverwrite && !flag_overwrite && !existing_mod->get_bool_attribute(ID::blackbox)) {
448
+ error("RTLIL error: redefinition of module %s.", design->twines().str(module_name).c_str());
449
+ } else if (flag_nooverwrite) {
450
+ log("Ignoring re-definition of module %s.\n", design->twines().str(module_name));
451
+ delete_current_module = true;
452
+ } else {
453
+ log("Replacing existing%s module %s.\n", existing_mod->get_bool_attribute(ID::blackbox) ? " blackbox" : "", design->twines().str(module_name));
454
+ design->remove(existing_mod);
455
+ }
456
+ }
457
+
458
+ current_module = new RTLIL::Module(design);
459
+ current_module->name = std::move(module_name);
460
+ current_module->attributes = std::move(attrbuf);
461
+ if (!delete_current_module)
462
+ design->add(current_module);
463
+
464
+ while (true)
465
+ {
466
+ if (try_parse_keyword("attribute")) {
467
+ parse_attribute();
468
+ continue;
469
+ }
470
+ if (try_parse_keyword("parameter")) {
471
+ parse_parameter();
472
+ continue;
473
+ }
474
+ if (try_parse_keyword("connect")) {
475
+ parse_connect();
476
+ continue;
477
+ }
478
+ if (try_parse_keyword("wire")) {
479
+ parse_wire();
480
+ continue;
481
+ }
482
+ if (try_parse_keyword("cell")) {
483
+ parse_cell();
484
+ continue;
485
+ }
486
+ if (try_parse_keyword("memory")) {
487
+ parse_memory();
488
+ continue;
489
+ }
490
+ if (try_parse_keyword("process")) {
491
+ parse_process();
492
+ continue;
493
+ }
494
+ if (try_parse_keyword("end")) {
495
+ expect_eol();
496
+ break;
497
+ }
498
+ error("Unexpected token in module body: %s", error_token());
499
+ }
500
+
501
+ if (attrbuf.size() != 0)
502
+ error("dangling attribute");
503
+ current_module->fixup_ports();
504
+ if (delete_current_module)
505
+ delete current_module;
506
+ else if (flag_lib)
507
+ current_module->makeblackbox();
508
+ current_module = nullptr;
509
+ }
510
+
511
+ void parse_attribute()
512
+ {
513
+ IdString id = parse_twine();
514
+ RTLIL::Const c = parse_const();
515
+ attrbuf.insert({std::move(id), std::move(c)});
516
+ expect_eol();
517
+ }
518
+
519
+ bool static_ids_match(const std::vector<size_t> &ordered_ids)
520
+ {
521
+ for (size_t id : ordered_ids) {
522
+ if (id >= STATIC_TWINE_END)
523
+ continue;
524
+ const TwineDesc &desc = twine_descs.at(id);
525
+ IdString found;
526
+ if (desc.kind == TwineDesc::Root)
527
+ found = design->twines().find(TwineSpec{TwineSpec::Root{desc.text}});
528
+ else
529
+ found = design->twines().find(TwineSpec{TwineSpec::Suffix{
530
+ IdString(desc.parent), desc.text}});
531
+ if (found == IdString::Null || found.untag().raw() != id)
532
+ return false;
533
+ }
534
+ return true;
535
+ }
536
+
537
+ IdString resolve_file_twine(size_t id, bool is_public = false)
538
+ {
539
+ return materialize_file_twine(id).tag(is_public);
540
+ }
541
+
542
+ IdString materialize_file_twine(size_t id)
543
+ {
544
+ auto rit = twine_remap.find(id);
545
+ if (rit != twine_remap.end())
546
+ return rit->second;
547
+ auto dit = twine_descs.find(id);
548
+ if (dit == twine_descs.end()) {
549
+ if (id < STATIC_TWINE_END)
550
+ return IdString(id);
551
+ error("Unknown twine reference @%zu at line %d", id, line_num);
552
+ }
553
+ TwineDesc &desc = dit->second;
554
+ if (desc.materializing)
555
+ error("Cyclic twine reference @%zu at line %d", id, line_num);
556
+ desc.materializing = true;
557
+ IdString ref;
558
+ switch (desc.kind) {
559
+ case TwineDesc::Root:
560
+ ref = design->twines().add(TwineSpec::Root{desc.text});
561
+ break;
562
+ case TwineDesc::Suffix:
563
+ ref = design->twines().add(TwineSpec::Suffix{
564
+ materialize_file_twine(desc.parent),
565
+ desc.text});
566
+ break;
567
+ }
568
+ desc.materializing = false;
569
+ twine_remap[id] = ref;
570
+ return ref;
571
+ }
572
+
573
+ std::optional<IdString> try_parse_twine_handle()
574
+ {
575
+ bool is_public;
576
+ size_t prefix = IdString::handle_token_prefix(line, is_public);
577
+ if (prefix == 0)
578
+ return std::nullopt;
579
+ line = line.substr(prefix);
580
+ return resolve_file_twine(parse_integer(), is_public);
581
+ }
582
+
583
+ std::optional<IdString> try_parse_twine()
584
+ {
585
+ if (std::optional<IdString> handle = try_parse_twine_handle())
586
+ return handle;
587
+ std::optional<std::string> id = try_parse_id();
588
+ if (!id)
589
+ return std::nullopt;
590
+ return design->twines().add(std::move(*id));
591
+ }
592
+
593
+ IdString parse_twine()
594
+ {
595
+ std::optional<IdString> t = try_parse_twine();
596
+ if (!t)
597
+ error("Expected twine reference or ID, got `%s'.", error_token());
598
+ return *t;
599
+ }
600
+
601
+ void parse_twines()
602
+ {
603
+ expect_eol();
604
+ while (true) {
605
+ if (try_parse_keyword("end"))
606
+ break;
607
+ if (try_parse_keyword("root")) {
608
+ size_t file_id = parse_integer();
609
+ TwineDesc &desc = twine_descs[file_id];
610
+ desc.kind = TwineDesc::Root;
611
+ desc.text = parse_string();
612
+ expect_eol();
613
+ continue;
614
+ }
615
+ if (try_parse_keyword("suffix")) {
616
+ size_t file_id = parse_integer();
617
+ TwineDesc &desc = twine_descs[file_id];
618
+ desc.kind = TwineDesc::Suffix;
619
+ desc.parent = parse_integer();
620
+ desc.text = parse_string();
621
+ expect_eol();
622
+ continue;
623
+ }
624
+ error("Expected `root` or `suffix` inside twines block, got `%s'.",
625
+ error_token());
626
+ }
627
+ std::vector<size_t> ordered_ids;
628
+ ordered_ids.reserve(twine_descs.size());
629
+ for (auto &it : twine_descs)
630
+ ordered_ids.push_back(it.first);
631
+ std::sort(ordered_ids.begin(), ordered_ids.end());
632
+ if (static_ids_match(ordered_ids)) {
633
+ std::vector<size_t> dynamic_ids;
634
+ dynamic_ids.reserve(ordered_ids.size());
635
+ for (size_t id : ordered_ids) {
636
+ if (id < STATIC_TWINE_END)
637
+ twine_descs.erase(id);
638
+ else
639
+ dynamic_ids.push_back(id);
640
+ }
641
+ ordered_ids.swap(dynamic_ids);
642
+ }
643
+ for (size_t id : ordered_ids)
644
+ materialize_file_twine(id);
645
+ twine_descs.clear();
646
+ expect_eol();
647
+ }
648
+
649
+ void parse_metadata()
650
+ {
651
+ expect_eol();
652
+ while (!try_parse_keyword("end")) {
653
+ if (try_parse_keyword("twines"))
654
+ parse_twines();
655
+ else
656
+ error("Unexpected section `%s' in metadata block.", error_token());
657
+ }
658
+ expect_eol();
659
+ }
660
+
661
+ void parse_parameter()
662
+ {
663
+ IdString id = parse_twine();
664
+ current_module->avail_parameters(id);
665
+ if (try_parse_eol())
666
+ return;
667
+ RTLIL::Const c = parse_const();
668
+ current_module->parameter_default_values.insert({std::move(id), std::move(c)});
669
+ expect_eol();
670
+ }
671
+
672
+ void parse_wire()
673
+ {
674
+ RTLIL::Wire *wire;
675
+ int width = 1;
676
+ int start_offset = 0;
677
+ int port_id = 0;
678
+ bool port_input = false;
679
+ bool port_output = false;
680
+ bool upto = false;
681
+ bool is_signed = false;
682
+
683
+ while (true)
684
+ {
685
+ std::optional<IdString> name = try_parse_twine();
686
+ if (name) {
687
+ IdString wire_name = *name;
688
+ if (current_module->wire(wire_name) != nullptr) {
689
+ if (flag_legalize) {
690
+ log("Legalizing redefinition of wire %s.\n", design->twines().str(wire_name));
691
+ pool<RTLIL::Wire*> wires = {current_module->wire(wire_name)};
692
+ current_module->remove(wires);
693
+ } else
694
+ error("RTLIL error: redefinition of wire %s.", design->twines().str(wire_name).c_str());
695
+ }
696
+ wire = current_module->addWire(wire_name);
697
+ break;
698
+ }
699
+ if (try_parse_keyword("width")){
700
+ long long width_val = parse_integer();
701
+ if (width_val < 0 || width_val >= RTLIL::WIDTH_LIMIT)
702
+ error("Wire width %lld out of range before `%s`.", width_val, error_token());
703
+ width = width_val;
704
+ }
705
+ else if (try_parse_keyword("upto"))
706
+ upto = true;
707
+ else if (try_parse_keyword("signed"))
708
+ is_signed = true;
709
+ else if (try_parse_keyword("offset")) {
710
+ long long offset_val = parse_integer();
711
+ if (offset_val < INT_MIN || offset_val > INT_MAX)
712
+ error("Wire offset %lld out of range before `%s`.", offset_val, error_token());
713
+ start_offset = offset_val;
714
+ }
715
+ else if (try_parse_keyword("input")) {
716
+ port_id = parse_integer();
717
+ port_input = true;
718
+ } else if (try_parse_keyword("output")) {
719
+ port_id = parse_integer();
720
+ port_output = true;
721
+ } else if (try_parse_keyword("inout")) {
722
+ port_id = parse_integer();
723
+ port_input = true;
724
+ port_output = true;
725
+ } else if (try_parse_eol())
726
+ error("Missing wire ID");
727
+ else
728
+ error("Unexpected wire option: %s", error_token());
729
+ }
730
+
731
+ wire->attributes = std::move(attrbuf);
732
+ wire->width = width;
733
+ wire->upto = upto;
734
+ wire->start_offset = start_offset;
735
+ wire->is_signed = is_signed;
736
+ wire->port_id = port_id;
737
+ wire->port_input = port_input;
738
+ wire->port_output = port_output;
739
+ expect_eol();
740
+ }
741
+
742
+ void parse_memory()
743
+ {
744
+ RTLIL::Memory *memory = new RTLIL::Memory(current_module);
745
+ memory->attributes = std::move(attrbuf);
746
+
747
+ int width = 1;
748
+ int start_offset = 0;
749
+ int size = 0;
750
+ IdString mem_name;
751
+ while (true)
752
+ {
753
+ std::optional<IdString> name = try_parse_twine();
754
+ if (name.has_value()) {
755
+ mem_name = *name;
756
+ if (current_module->memories.count(mem_name) != 0) {
757
+ if (flag_legalize) {
758
+ log("Legalizing redefinition of memory %s.\n", design->twines().str(mem_name));
759
+ current_module->remove(current_module->memories.at(mem_name));
760
+ } else
761
+ error("RTLIL error: redefinition of memory %s.", design->twines().str(mem_name).c_str());
762
+ }
763
+ memory->name = mem_name;
764
+ break;
765
+ }
766
+ if (try_parse_keyword("width")){
767
+ long long width_val = parse_integer();
768
+ if (width_val < 0 || width_val >= RTLIL::WIDTH_LIMIT)
769
+ error("Memory width %lld out of range before `%s`.", width_val, error_token());
770
+ width = width_val;
771
+ }
772
+ else if (try_parse_keyword("size")) {
773
+ long long size_val = parse_integer();
774
+ if (size_val < INT_MIN || size_val > INT_MAX)
775
+ error("Memory size %lld out of range before `%s`.", size_val, error_token());
776
+ size = size_val;
777
+ }
778
+ else if (try_parse_keyword("offset")) {
779
+ long long offset_val = parse_integer();
780
+ if (offset_val < INT_MIN || offset_val > INT_MAX)
781
+ error("Memory offset %lld out of range before `%s`.", offset_val, error_token());
782
+ start_offset = offset_val;
783
+ }
784
+ else if (try_parse_eol())
785
+ error("Missing memory ID");
786
+ else
787
+ error("Unexpected memory option: %s", error_token());
788
+ }
789
+ memory->width = width;
790
+ memory->start_offset = start_offset;
791
+ memory->size = size;
792
+ memory->module = current_module;
793
+ current_module->memories.insert({mem_name, memory});
794
+ expect_eol();
795
+ }
796
+
797
+ void legalize_width_parameter(RTLIL::Cell *cell, RTLIL::IdString port_name)
798
+ {
799
+ IdString width_param = design->twines().find(design->twines().str(port_name) + "_WIDTH");
800
+ if (width_param == IdString::Null || cell->parameters.count(width_param) == 0)
801
+ return;
802
+ RTLIL::Const &param = cell->parameters.at(width_param);
803
+ if (param.as_int() != 0)
804
+ return;
805
+ cell->parameters[width_param] = RTLIL::Const(cell->getPort(port_name).size());
806
+ }
807
+
808
+ void parse_cell()
809
+ {
810
+ IdString cell_type_ref = parse_twine();
811
+ IdString cell_name_ref = parse_twine();
812
+ expect_eol();
813
+
814
+ if (current_module->cell(cell_name_ref) != nullptr) {
815
+ if (flag_legalize) {
816
+ std::string base = design->twines().str(cell_name_ref);
817
+ std::string new_name_str;
818
+ int suffix = 1;
819
+ do {
820
+ new_name_str = base + "_" + std::to_string(suffix);
821
+ cell_name_ref = design->twines().add(new_name_str);
822
+ ++suffix;
823
+ } while (current_module->cell(cell_name_ref) != nullptr);
824
+ log("Legalizing redefinition of cell %s by renaming to %s.\n", base, new_name_str);
825
+ } else
826
+ error("RTLIL error: redefinition of cell %s.", design->twines().str(cell_name_ref).c_str());
827
+ }
828
+ RTLIL::Cell *cell = current_module->addCell(cell_name_ref, cell_type_ref);
829
+ cell->attributes = std::move(attrbuf);
830
+
831
+ while (true)
832
+ {
833
+ if (try_parse_keyword("parameter")) {
834
+ bool is_signed = false;
835
+ bool is_real = false;
836
+ bool is_unsized = false;
837
+ if (try_parse_keyword("signed")) {
838
+ is_signed = true;
839
+ } else if (try_parse_keyword("real")) {
840
+ is_real = true;
841
+ } else if (try_parse_keyword("unsized")) {
842
+ is_unsized = true;
843
+ }
844
+ IdString param_name = parse_twine();
845
+ RTLIL::Const val = parse_const();
846
+ if (is_signed)
847
+ val.flags |= RTLIL::CONST_FLAG_SIGNED;
848
+ if (is_real)
849
+ val.flags |= RTLIL::CONST_FLAG_REAL;
850
+ if (is_unsized)
851
+ val.flags |= RTLIL::CONST_FLAG_UNSIZED;
852
+ cell->parameters.insert({std::move(param_name), std::move(val)});
853
+ expect_eol();
854
+ } else if (try_parse_keyword("connect")) {
855
+ IdString port_name = parse_twine();
856
+ if (cell->hasPort(port_name)) {
857
+ if (flag_legalize)
858
+ log("Legalizing redefinition of cell port %s.\n", design->twines().str(port_name));
859
+ else
860
+ error("RTLIL error: redefinition of cell port %s.", design->twines().str(port_name).c_str());
861
+ }
862
+ cell->setPort(port_name, parse_sigspec());
863
+ if (flag_legalize)
864
+ legalize_width_parameter(cell, port_name);
865
+ expect_eol();
866
+ } else if (try_parse_keyword("end")) {
867
+ expect_eol();
868
+ break;
869
+ } else {
870
+ error("Unexpected token in cell body: %s", error_token());
871
+ }
872
+ }
873
+ }
874
+
875
+ void parse_connect()
876
+ {
877
+ if (attrbuf.size() != 0)
878
+ error("dangling attribute");
879
+ RTLIL::SigSpec s1 = parse_sigspec();
880
+ RTLIL::SigSpec s2 = parse_sigspec();
881
+ if (flag_legalize) {
882
+ int min_size = std::min(s1.size(), s2.size());
883
+ s1 = s1.extract(0, min_size);
884
+ s2 = s2.extract(0, min_size);
885
+ }
886
+ current_module->connect(std::move(s1), std::move(s2));
887
+ expect_eol();
888
+ }
889
+
890
+ void parse_case_body(RTLIL::CaseRule *current_case)
891
+ {
892
+ while (true)
893
+ {
894
+ if (try_parse_keyword("attribute"))
895
+ parse_attribute();
896
+ else if (try_parse_keyword("switch"))
897
+ parse_switch();
898
+ else if (try_parse_keyword("assign")) {
899
+ if (attrbuf.size() != 0)
900
+ error("dangling attribute");
901
+ // See https://github.com/YosysHQ/yosys/pull/4765 for discussion on this
902
+ // warning
903
+ if (!switch_stack.back()->empty())
904
+ warning("case rule assign statements after switch statements may cause unexpected behaviour. "
905
+ "The assign statement is reordered to come before all switch statements.");
906
+ RTLIL::SigSpec s1 = parse_sigspec();
907
+ RTLIL::SigSpec s2 = parse_sigspec();
908
+ current_case->actions.push_back({std::move(s1), std::move(s2)});
909
+ expect_eol();
910
+ } else
911
+ return;
912
+ }
913
+ }
914
+
915
+ void parse_switch()
916
+ {
917
+ RTLIL::SwitchRule *rule = new RTLIL::SwitchRule;
918
+ rule->signal = parse_sigspec();
919
+ rule->attributes = std::move(attrbuf);
920
+ switch_stack.back()->push_back(rule);
921
+ expect_eol();
922
+
923
+ while (true) {
924
+ if (try_parse_keyword("attribute")) {
925
+ parse_attribute();
926
+ continue;
927
+ }
928
+
929
+ if (try_parse_keyword("end")) {
930
+ expect_eol();
931
+ break;
932
+ }
933
+
934
+ expect_keyword("case");
935
+ RTLIL::CaseRule *case_rule = new RTLIL::CaseRule;
936
+ case_rule->attributes = std::move(attrbuf);
937
+ rule->cases.push_back(case_rule);
938
+ switch_stack.push_back(&case_rule->switches);
939
+ case_stack.push_back(case_rule);
940
+
941
+ if (!try_parse_eol()) {
942
+ while (true) {
943
+ case_rule->compare.push_back(parse_sigspec());
944
+ if (try_parse_eol())
945
+ break;
946
+ expect_char(',');
947
+ }
948
+ }
949
+
950
+ parse_case_body(case_rule);
951
+
952
+ switch_stack.pop_back();
953
+ case_stack.pop_back();
954
+ }
955
+ }
956
+
957
+ void parse_process()
958
+ {
959
+ IdString proc_name = parse_twine();
960
+ expect_eol();
961
+
962
+ if (current_module->processes.count(proc_name) != 0) {
963
+ if (flag_legalize) {
964
+ log("Legalizing redefinition of process %s.\n", design->twines().str(proc_name));
965
+ current_module->remove(current_module->processes.at(proc_name));
966
+ } else
967
+ error("RTLIL error: redefinition of process %s.", design->twines().str(proc_name).c_str());
968
+ }
969
+ RTLIL::Process *proc = current_module->addProcess(std::move(proc_name));
970
+ proc->attributes = std::move(attrbuf);
971
+
972
+ switch_stack.clear();
973
+ switch_stack.push_back(&proc->root_case.switches);
974
+ case_stack.clear();
975
+ case_stack.push_back(&proc->root_case);
976
+
977
+ parse_case_body(&proc->root_case);
978
+
979
+ while (try_parse_keyword("sync"))
980
+ {
981
+ RTLIL::SyncRule *rule = new RTLIL::SyncRule;
982
+
983
+ if (try_parse_keyword("low")) rule->type = RTLIL::ST0;
984
+ else if (try_parse_keyword("high")) rule->type = RTLIL::ST1;
985
+ else if (try_parse_keyword("posedge")) rule->type = RTLIL::STp;
986
+ else if (try_parse_keyword("negedge")) rule->type = RTLIL::STn;
987
+ else if (try_parse_keyword("edge")) rule->type = RTLIL::STe;
988
+ else if (try_parse_keyword("always")) rule->type = RTLIL::STa;
989
+ else if (try_parse_keyword("global")) rule->type = RTLIL::STg;
990
+ else if (try_parse_keyword("init")) rule->type = RTLIL::STi;
991
+ else error("Unexpected sync type: %s", error_token());
992
+
993
+ if (rule->type != RTLIL::STa && rule->type != RTLIL::STg && rule->type != RTLIL::STi)
994
+ rule->signal = parse_sigspec();
995
+ proc->syncs.push_back(rule);
996
+ expect_eol();
997
+
998
+ bool attributes_in_update_list = false;
999
+ while (true)
1000
+ {
1001
+ if (try_parse_keyword("update")) {
1002
+ RTLIL::SigSpec s1 = parse_sigspec();
1003
+ RTLIL::SigSpec s2 = parse_sigspec();
1004
+ rule->actions.push_back({std::move(s1), std::move(s2)});
1005
+ expect_eol();
1006
+ continue;
1007
+ }
1008
+
1009
+ if (try_parse_keyword("attribute")) {
1010
+ attributes_in_update_list = true;
1011
+ parse_attribute();
1012
+ continue;
1013
+ }
1014
+
1015
+ if (!try_parse_keyword("memwr"))
1016
+ break;
1017
+
1018
+ RTLIL::MemWriteAction act;
1019
+ act.attributes = std::move(attrbuf);
1020
+ act.memid = parse_twine();
1021
+ act.address = parse_sigspec();
1022
+ act.data = parse_sigspec();
1023
+ act.enable = parse_sigspec();
1024
+ act.priority_mask = parse_const();
1025
+ rule->mem_write_actions.push_back(std::move(act));
1026
+ expect_eol();
1027
+ }
1028
+ // The old parser allowed dangling attributes before a "sync" to carry through
1029
+ // the "sync", so we will too, for now.
1030
+ if (attributes_in_update_list && attrbuf.size() > 0)
1031
+ error("dangling attribute");
1032
+ }
1033
+
1034
+ expect_keyword("end");
1035
+ expect_eol();
1036
+ }
1037
+
1038
+ RTLILFrontendWorker(RTLIL::Design *design) : design(design) {}
1039
+
1040
+ void parse(std::istream *f)
1041
+ {
1042
+ this->f = f;
1043
+ line_num = 0;
1044
+ advance_to_next_nonempty_line();
1045
+ while (f->good())
1046
+ {
1047
+ if (try_parse_keyword("attribute")) {
1048
+ parse_attribute();
1049
+ continue;
1050
+ }
1051
+ if (try_parse_keyword("module")) {
1052
+ parse_module();
1053
+ continue;
1054
+ }
1055
+ if (try_parse_keyword("autoidx")) {
1056
+ design->twines().ensure_autoidx(parse_integer());
1057
+ expect_eol();
1058
+ continue;
1059
+ }
1060
+ if (try_parse_keyword("metadata")) {
1061
+ parse_metadata();
1062
+ continue;
1063
+ }
1064
+ error("Unexpected token: %s", error_token());
1065
+ }
1066
+ if (attrbuf.size() != 0)
1067
+ error("dangling attribute");
1068
+
1069
+ twine_parser_holds.clear();
1070
+ twine_remap.clear();
1071
+ }
1072
+ };
1073
+
1074
+ struct RTLILFrontend : public Frontend {
1075
+ RTLILFrontend() : Frontend("rtlil", "read modules from RTLIL file") { }
1076
+ void help() override
1077
+ {
1078
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1079
+ log("\n");
1080
+ log(" read_rtlil [filename]\n");
1081
+ log("\n");
1082
+ log("Load modules from an RTLIL file to the current design. (RTLIL is a text\n");
1083
+ log("representation of a design in yosys's internal format.)\n");
1084
+ log("\n");
1085
+ log(" -nooverwrite\n");
1086
+ log(" ignore re-definitions of modules. (the default behavior is to\n");
1087
+ log(" create an error message if the existing module is not a blackbox\n");
1088
+ log(" module, and overwrite the existing module if it is a blackbox module.)\n");
1089
+ log("\n");
1090
+ log(" -overwrite\n");
1091
+ log(" overwrite existing modules with the same name\n");
1092
+ log("\n");
1093
+ log(" -lib\n");
1094
+ log(" only create empty blackbox modules\n");
1095
+ log("\n");
1096
+ log(" -legalize\n");
1097
+ log(" prevent semantic errors (e.g. reference to unknown wire, redefinition of wire/cell)\n");
1098
+ log(" by deterministically rewriting the input into something valid. Useful when using\n");
1099
+ log(" fuzzing to generate random but valid RTLIL.\n");
1100
+ log("\n");
1101
+ }
1102
+ void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
1103
+ {
1104
+ RTLILFrontendWorker worker(design);
1105
+
1106
+ log_header(design, "Executing RTLIL frontend.\n");
1107
+
1108
+ size_t argidx;
1109
+ for (argidx = 1; argidx < args.size(); argidx++) {
1110
+ std::string arg = args[argidx];
1111
+ if (arg == "-nooverwrite") {
1112
+ worker.flag_nooverwrite = true;
1113
+ worker.flag_overwrite = false;
1114
+ continue;
1115
+ }
1116
+ if (arg == "-overwrite") {
1117
+ worker.flag_nooverwrite = false;
1118
+ worker.flag_overwrite = true;
1119
+ continue;
1120
+ }
1121
+ if (arg == "-lib") {
1122
+ worker.flag_lib = true;
1123
+ continue;
1124
+ }
1125
+ if (arg == "-legalize") {
1126
+ worker.flag_legalize = true;
1127
+ continue;
1128
+ }
1129
+ break;
1130
+ }
1131
+ extra_args(f, filename, args, argidx);
1132
+
1133
+ log("Input filename: %s\n", filename);
1134
+
1135
+ worker.parse(f);
1136
+ }
1137
+ } RTLILFrontend;
1138
+
1139
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/slang/CMakeLists.txt ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ include(lib/cmake/GitRevision.cmake)
2
+ git_rev_parse(YOSYS_SLANG_REVISION ${CMAKE_CURRENT_SOURCE_DIR}/lib)
3
+ git_rev_parse(SLANG_REVISION ${PROJECT_SOURCE_DIR}/libs/slang)
4
+ configure_file(${CMAKE_CURRENT_SOURCE_DIR}/lib/src/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h)
5
+
6
+ yosys_frontend(slang
7
+ lib/src/yosys_plugin/abort_helpers.cc
8
+ lib/src/yosys_plugin/backend_builder.cc
9
+ lib/src/yosys_plugin/backend_builder.h
10
+ lib/src/yosys_plugin/blackboxes.cc
11
+ lib/src/yosys_plugin/cases.cc
12
+ lib/src/yosys_plugin/cases.h
13
+ lib/src/yosys_plugin/driver.cc
14
+ lib/src/yosys_plugin/ir.cc
15
+ lib/src/yosys_plugin/ir.h
16
+ lib/src/yosys_plugin/sva.cc
17
+ lib/src/addressing.cc
18
+ lib/src/async_pattern.cc
19
+ lib/src/async_pattern.h
20
+ lib/src/builder.cc
21
+ lib/src/diag.cc
22
+ lib/src/diag.h
23
+ lib/src/initialization.cc
24
+ lib/src/lvalue.cc
25
+ lib/src/memory.h
26
+ lib/src/naming.cc
27
+ lib/src/procedural.cc
28
+ lib/src/slang_frontend.cc
29
+ lib/src/slang_frontend.h
30
+ lib/src/statements.h
31
+ lib/src/variables.cc
32
+ lib/src/variables.h
33
+ ${CMAKE_CURRENT_BINARY_DIR}/version.h
34
+ DEFINITIONS
35
+ YOSYS_MAJOR=${YOSYS_VERSION_MAJOR}
36
+ YOSYS_MINOR=${YOSYS_VERSION_MINOR}
37
+ YOSYS_COMMIT=${YOSYS_VERSION_COMMIT}
38
+ ENABLE_IF
39
+ YOSYS_ENABLE_SLANG
40
+ INCLUDE_DIRS
41
+ ${CMAKE_CURRENT_SOURCE_DIR}/lib/src
42
+ ${CMAKE_CURRENT_SOURCE_DIR}/lib/third_party/hashlib
43
+ ${CMAKE_CURRENT_SOURCE_DIR}/lib/src/yosys_plugin
44
+ ${CMAKE_CURRENT_BINARY_DIR}
45
+ LIBRARIES
46
+ $<${YOSYS_ENABLE_SLANG}:slang::slang>
47
+ )
chips/yosys/frontends/verific/CMakeLists.txt ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if (NOT YOSYS_ENABLE_VERIFIC)
2
+ # Stub interface library.
3
+ add_library(verific INTERFACE)
4
+ set(verific_data_files)
5
+ else()
6
+ if (NOT YOSYS_VERIFIC_COMPONENTS)
7
+ get_verific_components(YOSYS_VERIFIC_COMPONENTS)
8
+ endif()
9
+
10
+ if (NOT YOSYS_VERIFIC_FEATURES)
11
+ foreach (component ${YOSYS_VERIFIC_COMPONENTS})
12
+ if (component MATCHES "^(hier_tree|vhdl|edif|extensions)$")
13
+ list(APPEND YOSYS_VERIFIC_FEATURES ${component})
14
+ elseif (component STREQUAL "verilog")
15
+ list(APPEND YOSYS_VERIFIC_FEATURES systemverilog)
16
+ elseif (component STREQUAL "synlib")
17
+ list(APPEND YOSYS_VERIFIC_FEATURES liberty)
18
+ endif()
19
+ endforeach()
20
+ endif()
21
+
22
+ message(STATUS "Verific library components: ${YOSYS_VERIFIC_COMPONENTS}")
23
+ message(STATUS "Verific frontend features: ${YOSYS_VERIFIC_FEATURES}")
24
+
25
+ get_verific_options(verific_include_dirs verific_libraries ${YOSYS_VERIFIC_COMPONENTS})
26
+ add_library(verific INTERFACE)
27
+ target_include_directories(verific INTERFACE
28
+ ${verific_include_dirs}
29
+ )
30
+ target_link_libraries(verific INTERFACE
31
+ $<LINK_LIBRARY:WHOLE_ARCHIVE,${verific_libraries}>
32
+ PkgConfig::zlib
33
+ )
34
+
35
+ set(verific_data_files)
36
+ if ("vhdl" IN_LIST YOSYS_VERIFIC_FEATURES)
37
+ foreach (vdb_std 1987 1993 2008 2019)
38
+ set(vdb_std_root ${YOSYS_VERIFIC_DIR}/vhdl_packages/vdbs_${vdb_std})
39
+ file(GLOB_RECURSE vdb_files RELATIVE ${vdb_std_root} ${vdb_std_root}/*)
40
+ foreach (vdb_file ${vdb_files})
41
+ list(APPEND verific_data_files
42
+ verific/vhdl_vdbs_${vdb_std}/${vdb_file}
43
+ ${YOSYS_VERIFIC_DIR}/vhdl_packages/vdbs_${vdb_std}/${vdb_file}
44
+ )
45
+ endforeach()
46
+ endforeach()
47
+ endif()
48
+ endif()
49
+
50
+ yosys_frontend(verific
51
+ read.cc
52
+ verific.cc
53
+ verific.h
54
+ verific_pass.cc
55
+ $<${YOSYS_ENABLE_VERIFIC}:verific_clocking.cc>
56
+ $<${YOSYS_ENABLE_VERIFIC}:verific_clocking.h>
57
+ $<${YOSYS_ENABLE_VERIFIC}:verific_command.cc>
58
+ $<${YOSYS_ENABLE_VERIFIC}:verific_command.h>
59
+ $<${YOSYS_ENABLE_VERIFIC}:verific_extnets.cc>
60
+ $<${YOSYS_ENABLE_VERIFIC}:verific_importer.cc>
61
+ $<${YOSYS_ENABLE_VERIFIC}:verific_importer.h>
62
+ $<${YOSYS_ENABLE_VERIFIC}:verificsva.cc>
63
+ DEFINITIONS
64
+ $<$<IN_LIST:hier_tree,${YOSYS_VERIFIC_FEATURES}>:VERIFIC_HIER_TREE_SUPPORT>
65
+ $<$<IN_LIST:systemverilog,${YOSYS_VERIFIC_FEATURES}>:VERIFIC_SYSTEMVERILOG_SUPPORT>
66
+ $<$<IN_LIST:vhdl,${YOSYS_VERIFIC_FEATURES}>:VERIFIC_VHDL_SUPPORT>
67
+ $<$<IN_LIST:edif,${YOSYS_VERIFIC_FEATURES}>:VERIFIC_EDIF_SUPPORT>
68
+ $<$<IN_LIST:liberty,${YOSYS_VERIFIC_FEATURES}>:VERIFIC_LIBERTY_SUPPORT>
69
+ $<$<IN_LIST:extensions,${YOSYS_VERIFIC_FEATURES}>:YOSYSHQ_VERIFIC_EXTENSIONS>
70
+ LIBRARIES
71
+ verific
72
+ REQUIRES
73
+ sha1
74
+ read_verilog
75
+ PROVIDES
76
+ read
77
+ DATA_EXPLICIT
78
+ ${verific_data_files}
79
+ )
chips/yosys/frontends/verific/README ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ This directory contains Verific bindings for Yosys.
3
+
4
+ Use Tabby CAD Suite from YosysHQ if you need Yosys+Verific.
5
+ https://www.yosyshq.com/
6
+
7
+ Contact YosysHQ at contact@yosyshq.com for free evaluation
8
+ binaries of Tabby CAD Suite.
9
+
10
+
11
+ Verific Features that should be enabled in your Verific library
12
+ ===============================================================
13
+
14
+ database/DBCompileFlags.h:
15
+ DB_PRESERVE_INITIAL_VALUE
16
+
17
+
18
+ Testing Verific+Yosys+SBY for formal verification
19
+ ========================================================
20
+
21
+ Install Yosys+Verific, SBY, and Yices2. Install instructions:
22
+ https://yosyshq.readthedocs.io/projects/sby/en/latest/install.html
23
+
24
+ Then run in the following command in this directory:
25
+
26
+ sby -f example.sby
27
+
28
+ This will generate approximately one page of text output. The last lines
29
+ should be something like this:
30
+
31
+ SBY [example] summary: Elapsed clock time [H:MM:SS (secs)]: 0:00:00 (0)
32
+ SBY [example] summary: Elapsed process time [H:MM:SS (secs)]: 0:00:00 (0)
33
+ SBY [example] summary: engine_0 (smtbmc yices) returned PASS for basecase
34
+ SBY [example] summary: engine_0 (smtbmc yices) returned PASS for induction
35
+ SBY [example] summary: successful proof by k-induction.
36
+ SBY [example] DONE (PASS, rc=0)
chips/yosys/frontends/verific/example.sby ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Simple SBY example job utilizing Verific
2
+
3
+ [options]
4
+ mode prove
5
+ depth 10
6
+
7
+ [engines]
8
+ smtbmc yices
9
+
10
+ [script]
11
+ verific -sv example.sv
12
+ verific -import top
13
+ prep -top top
14
+
15
+ [files]
16
+ example.sv
chips/yosys/frontends/verific/example.sv ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module top (
2
+ input clk, rst,
3
+ output reg [3:0] cnt
4
+ );
5
+ initial cnt = 0;
6
+
7
+ always @(posedge clk) begin
8
+ if (rst)
9
+ cnt <= 0;
10
+ else
11
+ cnt <= cnt + 4'd 1;
12
+ end
13
+
14
+ always @(posedge clk) begin
15
+ assume (cnt != 10);
16
+ assert (cnt != 15);
17
+ end
18
+ endmodule
chips/yosys/frontends/verific/read.cc ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+
22
+ #include "frontends/verific/verific.h"
23
+
24
+ USING_YOSYS_NAMESPACE
25
+ PRIVATE_NAMESPACE_BEGIN
26
+
27
+ struct ReadPass : public Pass {
28
+ ReadPass() : Pass("read", "load HDL designs") { }
29
+ void help() override
30
+ {
31
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
32
+ log("\n");
33
+ log(" read {-vlog95|-vlog2k|-sv2005|-sv2009|-sv2012|\n");
34
+ log(" -sv2017|-sv2023|-sv|-formal} <verilog-file>..\n");
35
+ log("\n");
36
+ log("Load the specified Verilog/SystemVerilog files. (Full SystemVerilog support\n");
37
+ log("is only available via Verific.)\n");
38
+ log("\n");
39
+ log("Additional -D<macro>[=<value>] options may be added after the option indicating\n");
40
+ log("the language version (and before file names) to set additional verilog defines.\n");
41
+ log("\n");
42
+ log("\n");
43
+ #ifdef VERIFIC_VHDL_SUPPORT
44
+ log(" read {-vhdl87|-vhdl93|-vhdl2k|-vhdl2008|-vhdl2019|-vhdl} <vhdl-file>..\n");
45
+ log("\n");
46
+ log("Load the specified VHDL files. (Requires Verific.)\n");
47
+ log("\n");
48
+ log("\n");
49
+ #endif
50
+ #ifdef VERIFIC_EDIF_SUPPORT
51
+ log(" read {-edif} <edif-file>..\n");
52
+ log("\n");
53
+ log("Load the specified EDIF files. (Requires Verific.)\n");
54
+ log("\n");
55
+ log("\n");
56
+ #endif
57
+ log(" read {-liberty} <liberty-file>..\n");
58
+ log("\n");
59
+ log("Load the specified Liberty files.\n");
60
+ log("\n");
61
+ log(" -lib\n");
62
+ log(" only create empty blackbox modules\n");
63
+ log("\n");
64
+ log("\n");
65
+ log(" read {-f|-F} <command-file>\n");
66
+ log("\n");
67
+ log("Load and execute the specified command file.\n");
68
+ log("Check verific command for more information about supported commands in file.\n");
69
+ log("\n");
70
+ log("\n");
71
+ log(" read -define <macro>[=<value>]..\n");
72
+ log("\n");
73
+ log("Set global Verilog/SystemVerilog defines.\n");
74
+ log("\n");
75
+ log("\n");
76
+ log(" read -undef <macro>..\n");
77
+ log("\n");
78
+ log("Unset global Verilog/SystemVerilog defines.\n");
79
+ log("\n");
80
+ log("\n");
81
+ log(" read -incdir <directory>\n");
82
+ log("\n");
83
+ log("Add directory to global Verilog/SystemVerilog include directories.\n");
84
+ log("\n");
85
+ log("\n");
86
+ log(" read -verific\n");
87
+ log(" read -noverific\n");
88
+ log("\n");
89
+ log("Subsequent calls to 'read' will either use or not use Verific. Calling 'read'\n");
90
+ log("with -verific will result in an error on Yosys binaries that are built without\n");
91
+ log("Verific support. The default is to use Verific if it is available.\n");
92
+ log("\n");
93
+ }
94
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
95
+ {
96
+ #ifdef YOSYS_ENABLE_VERIFIC
97
+ static bool verific_available = !check_noverific_env();
98
+ #else
99
+ static bool verific_available = false;
100
+ #endif
101
+ static bool use_verific = verific_available;
102
+
103
+ if (args.size() < 2 || args[1][0] != '-')
104
+ cmd_error(args, 1, "Missing mode parameter.\n");
105
+
106
+ if (args[1] == "-verific" || args[1] == "-noverific") {
107
+ if (args.size() != 2)
108
+ cmd_error(args, 1, "Additional arguments to -verific/-noverific.\n");
109
+ if (args[1] == "-verific") {
110
+ if (!verific_available)
111
+ cmd_error(args, 1, "This version of Yosys is built without Verific support.\n");
112
+ use_verific = true;
113
+ } else {
114
+ use_verific = false;
115
+ }
116
+ return;
117
+ }
118
+
119
+ if (args.size() < 3)
120
+ cmd_error(args, 3, "Missing file name parameter.\n");
121
+
122
+ if (args[1] == "-vlog95" || args[1] == "-vlog2k") {
123
+ if (use_verific) {
124
+ args[0] = "verific";
125
+ } else {
126
+ args[0] = "read_verilog";
127
+ args[1] = "-defer";
128
+ }
129
+ Pass::call(design, args);
130
+ return;
131
+ }
132
+
133
+ if (args[1] == "-sv2005" || args[1] == "-sv2009" || args[1] == "-sv2012" ||
134
+ args[1] == "-sv2017" || args[1] == "-sv2023" || args[1] == "-sv" || args[1] == "-formal") {
135
+ if (use_verific) {
136
+ args[0] = "verific";
137
+ } else {
138
+ args[0] = "read_verilog";
139
+ if (args[1] == "-formal")
140
+ args.insert(args.begin()+1, std::string());
141
+ args[1] = "-sv";
142
+ args.insert(args.begin()+1, "-defer");
143
+ }
144
+ Pass::call(design, args);
145
+ return;
146
+ }
147
+
148
+ #ifdef VERIFIC_VHDL_SUPPORT
149
+ if (args[1] == "-vhdl87" || args[1] == "-vhdl93" || args[1] == "-vhdl2k" || args[1] == "-vhdl2008" || args[1] == "-vhdl2019" || args[1] == "-vhdl") {
150
+ if (use_verific) {
151
+ args[0] = "verific";
152
+ Pass::call(design, args);
153
+ } else {
154
+ cmd_error(args, 1, "This version of Yosys is built without Verific support.\n");
155
+ }
156
+ return;
157
+ }
158
+ #endif
159
+ #ifdef VERIFIC_EDIF_SUPPORT
160
+ if (args[1] == "-edif") {
161
+ if (use_verific) {
162
+ args[0] = "verific";
163
+ Pass::call(design, args);
164
+ } else {
165
+ cmd_error(args, 1, "This version of Yosys is built without Verific support.\n");
166
+ }
167
+ return;
168
+ }
169
+ #endif
170
+ if (args[1] == "-liberty") {
171
+ if (use_verific) {
172
+ args[0] = "verific";
173
+ } else {
174
+ args[0] = "read_liberty";
175
+ }
176
+ Pass::call(design, args);
177
+ return;
178
+ }
179
+ if (args[1] == "-f" || args[1] == "-F") {
180
+ if (use_verific) {
181
+ args[0] = "verific";
182
+ } else {
183
+ args[0] = "read_verilog_file_list";
184
+ }
185
+ Pass::call(design, args);
186
+ return;
187
+ }
188
+
189
+ if (args[1] == "-define") {
190
+ if (use_verific) {
191
+ args[0] = "verific";
192
+ args[1] = "-vlog-define";
193
+ Pass::call(design, args);
194
+ }
195
+ args[0] = "verilog_defines";
196
+ args.erase(args.begin()+1, args.begin()+2);
197
+ for (int i = 1; i < GetSize(args); i++)
198
+ args[i] = "-D" + args[i];
199
+ Pass::call(design, args);
200
+ return;
201
+ }
202
+
203
+ if (args[1] == "-undef") {
204
+ if (use_verific) {
205
+ args[0] = "verific";
206
+ args[1] = "-vlog-undef";
207
+ Pass::call(design, args);
208
+ }
209
+ args[0] = "verilog_defines";
210
+ args.erase(args.begin()+1, args.begin()+2);
211
+ for (int i = 1; i < GetSize(args); i++)
212
+ args[i] = "-U" + args[i];
213
+ Pass::call(design, args);
214
+ return;
215
+ }
216
+
217
+ if (args[1] == "-incdir") {
218
+ if (use_verific) {
219
+ args[0] = "verific";
220
+ args[1] = "-vlog-incdir";
221
+ Pass::call(design, args);
222
+ }
223
+ args[0] = "verilog_defaults";
224
+ args[1] = "-add";
225
+ for (int i = 2; i < GetSize(args); i++)
226
+ args[i] = "-I" + args[i];
227
+ Pass::call(design, args);
228
+ return;
229
+ }
230
+
231
+ cmd_error(args, 1, "Missing or unsupported mode parameter.\n");
232
+ }
233
+ } ReadPass;
234
+
235
+ PRIVATE_NAMESPACE_END
chips/yosys/frontends/verific/verific.cc ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+ #include "kernel/log.h"
22
+ #include <stdlib.h>
23
+ #include <string.h>
24
+
25
+ #include "frontends/verific/verific.h"
26
+ #include "frontends/verific/verific_command.h"
27
+
28
+ USING_YOSYS_NAMESPACE
29
+
30
+ #ifdef YOSYS_ENABLE_VERIFIC
31
+
32
+ #ifdef __clang__
33
+ #pragma clang diagnostic push
34
+ #pragma clang diagnostic ignored "-Woverloaded-virtual"
35
+ #endif
36
+
37
+ #include "Array.h"
38
+ #include "RuntimeFlags.h"
39
+ #ifdef VERIFIC_HIER_TREE_SUPPORT
40
+ #include "hier_tree.h"
41
+ #endif
42
+
43
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
44
+ #include "veri_file.h"
45
+ #include "VeriModule.h"
46
+ #include "VeriLibrary.h"
47
+ #include "VeriExpression.h"
48
+ #endif
49
+
50
+ #ifdef VERIFIC_VHDL_SUPPORT
51
+ #include "vhdl_file.h"
52
+ #include "VhdlIdDef.h"
53
+ #include "VhdlUnits.h"
54
+ #endif
55
+
56
+ #ifdef VERIFIC_EDIF_SUPPORT
57
+ #include "edif_file.h"
58
+ #endif
59
+
60
+ #ifdef VERIFIC_LIBERTY_SUPPORT
61
+ #include "synlib_file.h"
62
+ #endif
63
+
64
+ #include "VerificStream.h"
65
+ #include "FileSystem.h"
66
+
67
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
68
+ #include "VerificExtensions.h"
69
+ #endif
70
+
71
+ #ifndef YOSYSHQ_VERIFIC_API_VERSION
72
+ #warning "Only YosysHQ flavored Verific is fully supported. Please contact office@yosyshq.com for commercial support for Yosys+Verific."
73
+ #else
74
+ #if YOSYSHQ_VERIFIC_API_VERSION < 20230901
75
+ # error "Please update your version of YosysHQ flavored Verific."
76
+ #endif
77
+ #endif
78
+
79
+ #if !defined(VERIFIC_VHDL_SUPPORT) && !defined(VERIFIC_SYSTEMVERILOG_SUPPORT)
80
+ #error "At least one of HDL languages must be enabled."
81
+ #endif
82
+
83
+ #ifdef __clang__
84
+ #pragma clang diagnostic pop
85
+ #endif
86
+
87
+ #ifdef VERIFIC_NAMESPACE
88
+ using namespace Verific;
89
+ #endif
90
+
91
+ #endif
92
+
93
+ #ifdef YOSYS_ENABLE_VERIFIC
94
+ YOSYS_NAMESPACE_BEGIN
95
+
96
+ // Verific use internally static data structures to keep current
97
+ // state, we can not mix new design with existing until current
98
+ // design is imported
99
+
100
+ void verific_cleanup();
101
+
102
+ void VerificSession::begin(Design *design)
103
+ {
104
+ std::unique_lock<std::mutex> lock(mutex);
105
+ while (owner != nullptr && owner != design)
106
+ cv.wait(lock);
107
+ owner = design;
108
+ }
109
+
110
+ std::unique_ptr<VerificSession> VerificSession::deferred_end(Design *design)
111
+ {
112
+ std::lock_guard<std::mutex> lock(mutex);
113
+ if (owner != design)
114
+ return nullptr;
115
+ return std::make_unique<VerificSession>();
116
+ }
117
+
118
+ VerificSession::~VerificSession()
119
+ {
120
+ verific_cleanup();
121
+ std::lock_guard<std::mutex> lock(mutex);
122
+ owner = nullptr;
123
+ cv.notify_all();
124
+ }
125
+
126
+ int verific_verbose;
127
+ bool verific_import_pending;
128
+ string verific_error_msg;
129
+ int verific_sva_fsm_limit;
130
+
131
+ const char *get_message_type(msg_type_t msg_type)
132
+ {
133
+ switch (msg_type) {
134
+ case VERIFIC_NONE:
135
+ return "VERIFIC-NONE";
136
+ case VERIFIC_ERROR:
137
+ return "VERIFIC-ERROR";
138
+ case VERIFIC_WARNING:
139
+ return "VERIFIC-WARNING";
140
+ case VERIFIC_IGNORE:
141
+ return "VERIFIC-IGNORE";
142
+ case VERIFIC_INFO:
143
+ return "VERIFIC-INFO";
144
+ case VERIFIC_COMMENT:
145
+ return "VERIFIC-COMMENT";
146
+ case VERIFIC_PROGRAM_ERROR:
147
+ return "VERIFIC-PROGRAM_ERROR";
148
+ default:
149
+ return "VERIFIC-UNKNOWN";
150
+ }
151
+ }
152
+
153
+ void msg_func(msg_type_t msg_type, const char *message_id, linefile_type linefile, const char *msg, va_list args)
154
+ {
155
+ std::string id = message_id ? stringf("[%s] ",message_id) : "";
156
+ string message = stringf("%s%s\n", id, vstringf(msg, args));
157
+ auto src = !linefile ? LogSourceLocation{} : LogSourceLocation{LineFile::GetFileName(linefile),
158
+ #ifdef VERIFIC_LINEFILE_INCLUDES_COLUMNS
159
+ int(linefile->GetLeftLine()), int(linefile->GetLeftCol()), int(linefile->GetRightLine()), int(linefile->GetRightCol())};
160
+ #else
161
+ int(LineFile::GetLineNo(linefile))};
162
+ #endif
163
+
164
+ if (log_verific_callback) {
165
+ log_verific_callback(int(msg_type), message_id, src, message.c_str());
166
+ } else {
167
+ string message_prefix = stringf("%s: ",get_message_type(msg_type));
168
+ if (msg_type == VERIFIC_ERROR || msg_type == VERIFIC_PROGRAM_ERROR) {
169
+ logger().formatted_nonfatal_error(src, message_prefix, "%s%s\n", message);
170
+ } else if (msg_type == VERIFIC_WARNING) {
171
+ logger().formatted_warning(src, message_prefix, "%s%s\n", message);
172
+ } else {
173
+ logger().formatted_string(LogSeverity::Info, src, message_prefix, "%s%s\n", message);
174
+ }
175
+ }
176
+ if (msg_type == VERIFIC_ERROR || msg_type == VERIFIC_PROGRAM_ERROR)
177
+ verific_error_msg = "Design elaboration failed; see full log for details";
178
+ }
179
+
180
+ void set_verific_logging(void (*cb)(int msg_type, const char *message_id, LogSourceLocation src, const char *msg))
181
+ {
182
+ Message::SetConsoleOutput(0);
183
+ Message::RegisterCallBackMsg(msg_func);
184
+ log_verific_callback = cb;
185
+ }
186
+
187
+ string get_full_netlist_name(Netlist *nl)
188
+ {
189
+ if (nl->NumOfRefs() == 1) {
190
+ Instance *inst = (Instance*)nl->GetReferences()->GetLast();
191
+ return get_full_netlist_name(inst->Owner()) + "." + inst->Name();
192
+ }
193
+
194
+ return nl->CellBaseName();
195
+ }
196
+
197
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
198
+ class YosysStreamCallBackHandler : public VerificStreamCallBackHandler
199
+ {
200
+ public:
201
+ YosysStreamCallBackHandler() : VerificStreamCallBackHandler() { }
202
+ virtual ~YosysStreamCallBackHandler() { }
203
+
204
+ virtual verific_stream *GetSysCallStream(const char *file_path)
205
+ {
206
+ if (!file_path) return nullptr;
207
+
208
+ linefile_type src_loc = GetFromLocation();
209
+
210
+ char *this_file_name = nullptr;
211
+ if (src_loc && !FileSystem::IsAbsolutePath(file_path)) {
212
+ const char *src_file_name = LineFile::GetFileName(src_loc);
213
+ char *dir_name = FileSystem::DirectoryPath(src_file_name);
214
+ if (dir_name) {
215
+ this_file_name = Strings::save(dir_name, "/", file_path);
216
+ Strings::free(dir_name);
217
+ file_path = this_file_name;
218
+ }
219
+ }
220
+ verific_stream *strm = new verific_ifstream(file_path);
221
+ Strings::free(this_file_name);
222
+ return strm;
223
+ }
224
+ };
225
+
226
+ YosysStreamCallBackHandler verific_read_cb;
227
+ #endif
228
+
229
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
230
+ static msg_type_t prev_1063;
231
+ #endif
232
+ #ifdef VERIFIC_VHDL_SUPPORT
233
+ static msg_type_t prev_1240 ;
234
+ static msg_type_t prev_1241 ;
235
+ #endif
236
+ void save_blackbox_msg_state()
237
+ {
238
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
239
+ prev_1063 = Message::GetMessageType("VERI-1063") ;
240
+ Message::SetMessageType("VERI-1063", VERIFIC_INFO);
241
+ #endif
242
+ #ifdef VERIFIC_VHDL_SUPPORT
243
+ prev_1240 = Message::GetMessageType("VHDL-1240") ;
244
+ prev_1241 = Message::GetMessageType("VHDL-1241") ;
245
+ Message::SetMessageType("VHDL-1240", VERIFIC_INFO);
246
+ Message::SetMessageType("VHDL-1241", VERIFIC_INFO);
247
+ #endif
248
+ }
249
+
250
+ void restore_blackbox_msg_state()
251
+ {
252
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
253
+ Message::ClearMessageType("VERI-1063") ;
254
+ if (Message::GetMessageType("VERI-1063")!=prev_1063)
255
+ Message::SetMessageType("VERI-1063", prev_1063);
256
+ #endif
257
+ #ifdef VERIFIC_VHDL_SUPPORT
258
+ Message::ClearMessageType("VHDL-1240") ;
259
+ Message::ClearMessageType("VHDL-1241") ;
260
+ if (Message::GetMessageType("VHDL-1240")!=prev_1240)
261
+ Message::SetMessageType("VHDL-1240", prev_1240);
262
+ if (Message::GetMessageType("VHDL-1241")!=prev_1241)
263
+ Message::SetMessageType("VHDL-1241", prev_1241);
264
+ #endif
265
+ }
266
+
267
+ void import_all(const char* work, std::map<std::string,Netlist*> *nl_todo, Map *parameters, bool show_message, std::string ppfile YS_MAYBE_UNUSED)
268
+ {
269
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
270
+ save_blackbox_msg_state();
271
+ VerificExtensions::ElaborateAndRewrite(work, parameters);
272
+ verific_error_msg.clear();
273
+ restore_blackbox_msg_state();
274
+ #endif
275
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
276
+ if (!ppfile.empty())
277
+ veri_file::PrettyPrint(ppfile.c_str(), nullptr, work);
278
+ #endif
279
+
280
+ Array vhdl_libs;
281
+ #ifdef VERIFIC_VHDL_SUPPORT
282
+ VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work, 1);
283
+ if (vhdl_lib) vhdl_libs.InsertLast(vhdl_lib);
284
+ #endif
285
+ Array veri_libs;
286
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
287
+ VeriLibrary *veri_lib = veri_file::GetLibrary(work, 1);
288
+ if (veri_lib) veri_libs.InsertLast(veri_lib);
289
+ #endif
290
+
291
+ #ifdef VERIFIC_HIER_TREE_SUPPORT
292
+ if (show_message)
293
+ log("Running hier_tree::ElaborateAll().\n");
294
+ Array *netlists = hier_tree::ElaborateAll(&veri_libs, &vhdl_libs, parameters);
295
+ Netlist *nl;
296
+ int i;
297
+
298
+ FOREACH_ARRAY_ITEM(netlists, i, nl)
299
+ nl_todo->emplace(nl->CellBaseName(), nl);
300
+ delete netlists;
301
+ #else
302
+ if (parameters->Size())
303
+ log_warning("Please note that parameters are not propagated during import.\n");
304
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
305
+ if (show_message)
306
+ log("Running veri_file::ElaborateAll().\n");
307
+ veri_file::ElaborateAll(work);
308
+ #endif
309
+ #ifdef VERIFIC_VHDL_SUPPORT
310
+ if (show_message)
311
+ log("Running vhdl_file::ElaborateAll().\n");
312
+ vhdl_file::ElaborateAll(work);
313
+ #endif
314
+ MapIter mi ;
315
+ Verific::Cell *c ;
316
+ MapIter it ;
317
+ Library *l ;
318
+ FOREACH_LIBRARY_OF_LIBSET(Libset::Global(),it,l) {
319
+ if (l == Library::Primitives() || l == Library::Operators()) continue;
320
+ FOREACH_CELL_OF_LIBRARY(l,mi,c) {
321
+ MapIter ni ;
322
+ Netlist *nl;
323
+ FOREACH_NETLIST_OF_CELL(c, ni, nl) {
324
+ if (nl)
325
+ nl_todo->emplace(nl->CellBaseName(), nl);
326
+ }
327
+ }
328
+ }
329
+ #endif
330
+ }
331
+
332
+ std::set<std::string> import_tops(const char* work, std::map<std::string,Netlist*> *nl_todo, Map *parameters, bool show_message, std::string ppfile YS_MAYBE_UNUSED, std::vector<std::string> &tops, std::string *top)
333
+ {
334
+ std::set<std::string> top_mod_names;
335
+ Array *netlists = nullptr;
336
+ (void)top;
337
+
338
+ #ifdef VERIFIC_VHDL_SUPPORT
339
+ VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work, 1);
340
+ #endif
341
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
342
+ VeriLibrary* veri_lib = veri_file::GetLibrary(work, 1);
343
+ #endif
344
+
345
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
346
+ for (int static_elaborate = 1; static_elaborate >= 0; static_elaborate--)
347
+ #endif
348
+ {
349
+ Array vhdl_units;
350
+ Array veri_modules;
351
+ for (std::string n : tops)
352
+ {
353
+ const char *name = n.c_str();
354
+ top_mod_names.insert(name);
355
+
356
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
357
+ VeriModule *veri_module = veri_lib ? veri_lib->GetModule(name, 1) : nullptr;
358
+ if (veri_module) {
359
+ if (veri_module->IsConfiguration()) {
360
+ if (show_message)
361
+ log("Adding Verilog configuration '%s' to elaboration queue.\n", name);
362
+ veri_modules.InsertLast(veri_module);
363
+ top_mod_names.erase(name);
364
+ VeriConfiguration *cfg = (VeriConfiguration*)veri_module;
365
+ VeriName *module_name;
366
+ int i;
367
+ FOREACH_ARRAY_ITEM(cfg->GetTopModuleNames(), i, module_name) {
368
+ VeriLibrary *lib = veri_module->GetLibrary() ;
369
+ if (module_name && module_name->IsHierName()) {
370
+ VeriName *prefix = module_name->GetPrefix() ;
371
+ const char *lib_name = (prefix) ? prefix->GetName() : 0 ;
372
+ if (work != lib_name) lib = veri_file::GetLibrary(lib_name, 1) ;
373
+ }
374
+ if (lib && module_name)
375
+ top_mod_names.insert(lib->GetModule(module_name->GetName(), 1)->GetName());
376
+ }
377
+ } else {
378
+ if (show_message)
379
+ log("Adding Verilog module '%s' to elaboration queue.\n", name);
380
+ veri_modules.InsertLast(veri_module);
381
+ }
382
+ continue;
383
+ }
384
+ #endif
385
+ #ifdef VERIFIC_VHDL_SUPPORT
386
+ VhdlDesignUnit *vhdl_unit = vhdl_lib ? vhdl_lib->GetPrimUnit(name) : nullptr;
387
+ if (vhdl_unit) {
388
+ if (show_message)
389
+ log("Adding VHDL unit '%s' to elaboration queue.\n", name);
390
+ vhdl_units.InsertLast(vhdl_unit);
391
+ if (strcmp(name, vhdl_unit->Id()->OrigName()) != 0) {
392
+ top_mod_names.erase(name);
393
+ top_mod_names.insert(vhdl_unit->Id()->OrigName());
394
+ if (top && *top == name)
395
+ *top = vhdl_unit->Id()->OrigName();
396
+ }
397
+ continue;
398
+ }
399
+ #endif
400
+ log_error("Can't find module/unit '%s'.\n", name);
401
+ }
402
+
403
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
404
+ if (static_elaborate) {
405
+ save_blackbox_msg_state();
406
+ VerificExtensions::ElaborateAndRewrite(work, &veri_modules, &vhdl_units, parameters);
407
+ verific_error_msg.clear();
408
+ restore_blackbox_msg_state();
409
+ #endif
410
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
411
+ if (!ppfile.empty())
412
+ veri_file::PrettyPrint(ppfile.c_str(), nullptr, work);
413
+ #endif
414
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
415
+ continue;
416
+ }
417
+ #endif
418
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
419
+ const char *lib_name = nullptr;
420
+ SetIter si;
421
+ FOREACH_SET_ITEM(veri_file::GetAllLOptions(), si, &lib_name) {
422
+ VeriLibrary* veri_lib = veri_file::GetLibrary(lib_name, 0);
423
+ if (veri_lib) {
424
+ // Also elaborate all root modules since they may contain bind statements
425
+ MapIter mi;
426
+ VeriModule *veri_module;
427
+ FOREACH_VERILOG_MODULE_IN_LIBRARY(veri_lib, mi, veri_module) {
428
+ if (!veri_module->IsRootModule()) continue;
429
+ veri_modules.InsertLast(veri_module);
430
+ }
431
+ }
432
+ }
433
+ #endif
434
+ #ifdef VERIFIC_HIER_TREE_SUPPORT
435
+ if (show_message)
436
+ log("Running hier_tree::Elaborate().\n");
437
+ netlists = hier_tree::Elaborate(&veri_modules, &vhdl_units, parameters);
438
+ #else
439
+ #if defined(VERIFIC_SYSTEMVERILOG_SUPPORT) && !defined(VERIFIC_VHDL_SUPPORT)
440
+ if (show_message)
441
+ log("Running veri_file::ElaborateMultipleTop().\n");
442
+ // SystemVerilog support only
443
+ netlists = veri_file::ElaborateMultipleTop(&veri_modules, parameters);
444
+ #elif defined(VERIFIC_VHDL_SUPPORT) && !defined(VERIFIC_SYSTEMVERILOG_SUPPORT)
445
+ if (show_message)
446
+ log("Running vhdl_file::Elaborate().\n");
447
+ // VHDL support only
448
+ netlists = new Array(top_mod_names.size());
449
+ for (auto &name : top_mod_names) {
450
+ vhdl_file::Elaborate(name.c_str(), work, 0, parameters);
451
+ netlists->InsertLast(Netlist::PresentDesign());
452
+ }
453
+ #elif defined(VERIFIC_SYSTEMVERILOG_SUPPORT) && defined(VERIFIC_VHDL_SUPPORT)
454
+ // Both SystemVerilog and VHDL support
455
+ if (veri_modules.Size()>0) {
456
+ if (show_message)
457
+ log("Running veri_file::ElaborateMultipleTop().\n");
458
+ netlists = veri_file::ElaborateMultipleTop(&veri_modules, parameters);
459
+ } else
460
+ netlists = new Array(1);
461
+ if (vhdl_units.Size()>0) {
462
+ if (show_message)
463
+ log("Running vhdl_file::Elaborate().\n");
464
+ for (auto &name : top_mod_names) {
465
+ vhdl_file::Elaborate(name.c_str(), work, 0, parameters);
466
+ netlists->InsertLast(Netlist::PresentDesign());
467
+ }
468
+ }
469
+ #else
470
+ #endif
471
+ #endif
472
+ }
473
+ Netlist *nl;
474
+ int i;
475
+
476
+ FOREACH_ARRAY_ITEM(netlists, i, nl) {
477
+ if (!nl) continue;
478
+ if (!top_mod_names.count(nl->CellBaseName()))
479
+ continue;
480
+ nl->AddAtt(new Att(" \\top", NULL));
481
+ nl_todo->emplace(nl->CellBaseName(), nl);
482
+ }
483
+ delete netlists;
484
+ return top_mod_names;
485
+ }
486
+
487
+ static bool set_verific_global_flags = true;
488
+
489
+ static void set_global_flags()
490
+ {
491
+ if (!set_verific_global_flags)
492
+ return;
493
+
494
+ Message::SetConsoleOutput(0);
495
+ Message::RegisterCallBackMsg(msg_func);
496
+
497
+ RuntimeFlags::SetVar("db_preserve_user_instances", 1);
498
+ RuntimeFlags::SetVar("db_preserve_user_nets", 1);
499
+ RuntimeFlags::SetVar("db_preserve_x", 1);
500
+
501
+ RuntimeFlags::SetVar("db_allow_external_nets", 1);
502
+ RuntimeFlags::SetVar("db_infer_wide_operators", 1);
503
+ RuntimeFlags::SetVar("db_infer_set_reset_registers", 0);
504
+
505
+ // Properly respect order of read and write for rams
506
+ RuntimeFlags::SetVar("db_change_inplace_ram_blocking_write_before_read", 1);
507
+
508
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
509
+ RuntimeFlags::SetVar("veri_extract_dualport_rams", 0);
510
+ RuntimeFlags::SetVar("veri_extract_multiport_rams", 1);
511
+ RuntimeFlags::SetVar("veri_allow_any_ram_in_loop", 1);
512
+ RuntimeFlags::SetVar("veri_replace_const_exprs", 1);
513
+ #endif
514
+ #ifdef VERIFIC_VHDL_SUPPORT
515
+ RuntimeFlags::SetVar("vhdl_extract_dualport_rams", 0);
516
+ RuntimeFlags::SetVar("vhdl_extract_multiport_rams", 1);
517
+ RuntimeFlags::SetVar("vhdl_allow_any_ram_in_loop", 1);
518
+ RuntimeFlags::SetVar("vhdl_replace_const_exprs", 1);
519
+
520
+ RuntimeFlags::SetVar("vhdl_support_variable_slice", 1);
521
+ RuntimeFlags::SetVar("vhdl_ignore_assertion_statements", 0);
522
+
523
+ RuntimeFlags::SetVar("vhdl_preserve_assignments", 1);
524
+ //RuntimeFlags::SetVar("vhdl_preserve_comments", 1);
525
+ RuntimeFlags::SetVar("vhdl_preserve_drivers", 1);
526
+ #endif
527
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
528
+ RuntimeFlags::SetVar("veri_preserve_assignments", 1);
529
+ RuntimeFlags::SetVar("veri_preserve_comments", 1);
530
+ RuntimeFlags::SetVar("veri_preserve_drivers", 1);
531
+
532
+ // Workaround for VIPER #13851
533
+ RuntimeFlags::SetVar("veri_create_name_for_unnamed_gen_block", 1);
534
+
535
+ // WARNING: instantiating unknown module 'XYZ' (VERI-1063)
536
+ Message::SetMessageType("VERI-1063", VERIFIC_ERROR);
537
+
538
+ // Downgrade warnings about things that are normal
539
+ // VERIFIC-WARNING [VERI-1209] foo.sv:98: expression size 7 truncated to fit in target size 6
540
+ Message::SetMessageType("VERI-1209", VERIFIC_INFO);
541
+ // VERIFIC-WARNING [VERI-1142] foo.sv:55: system task 'display' is ignored for synthesis
542
+ Message::SetMessageType("VERI-1142", VERIFIC_INFO);
543
+ // VERIFIC-WARNING [VERI-2418] foo.svh:503: parameter 'all_cfgs_gp' declared inside package 'bp_common_pkg' shall be treated as localparam
544
+ Message::SetMessageType("VERI-2418", VERIFIC_INFO);
545
+
546
+ // https://github.com/YosysHQ/yosys/issues/1055
547
+ RuntimeFlags::SetVar("veri_elaborate_top_level_modules_having_interface_ports", 1) ;
548
+ #endif
549
+ RuntimeFlags::SetVar("verific_produce_verbose_syntax_error_message", 1);
550
+
551
+ #ifndef DB_PRESERVE_INITIAL_VALUE
552
+ # warning Verific was built without DB_PRESERVE_INITIAL_VALUE.
553
+ #endif
554
+
555
+ set_verific_global_flags = false;
556
+ }
557
+
558
+ void verific_setup()
559
+ {
560
+ set_global_flags();
561
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
562
+ veri_file::RegisterCallBackVerificStream(&verific_read_cb);
563
+ #endif
564
+ }
565
+
566
+ void verific_cleanup()
567
+ {
568
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
569
+ VerificExtensions::Reset();
570
+ #endif
571
+ #ifdef VERIFIC_HIER_TREE_SUPPORT
572
+ hier_tree::DeleteHierarchicalTree();
573
+ #endif
574
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
575
+ veri_file::Reset();
576
+ #endif
577
+ #ifdef VERIFIC_VHDL_SUPPORT
578
+ vhdl_file::Reset();
579
+ #endif
580
+ #ifdef VERIFIC_EDIF_SUPPORT
581
+ edif_file::Reset();
582
+ #endif
583
+ #ifdef VERIFIC_LIBERTY_SUPPORT
584
+ synlib_file::Reset();
585
+ #endif
586
+ Libset::Reset();
587
+ Message::Reset();
588
+ RuntimeFlags::DeleteAllFlags();
589
+ set_verific_global_flags = true;
590
+ LineFile::DeleteAllLineFiles();
591
+ VerificCommand::reset_settings();
592
+ verific_import_pending = false;
593
+ }
594
+
595
+ std::string verific_import(Design *design, const std::map<std::string,std::string> &parameters, std::string top)
596
+ {
597
+ verific_sva_fsm_limit = 16;
598
+
599
+ std::map<std::string,Netlist*> nl_todo, nl_done;
600
+
601
+ Map verific_params(STRING_HASH);
602
+ for (const auto &i : parameters)
603
+ verific_params.Insert(i.first.c_str(), i.second.c_str());
604
+
605
+ std::set<std::string> top_mod_names;
606
+ if (top.empty()) {
607
+ import_all("work", &nl_todo, &verific_params, false, "");
608
+ } else {
609
+ std::vector<std::string> tops;
610
+ tops.push_back(top);
611
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
612
+ veri_file::RemoveAllLOptions();
613
+ veri_file::AddLOption("work");
614
+ #endif
615
+ top_mod_names = import_tops("work", &nl_todo, &verific_params, false, "", tops, &top) ;
616
+ }
617
+
618
+ if (!verific_error_msg.empty())
619
+ log_error("%s\n", verific_error_msg);
620
+
621
+ for (auto nl : nl_todo)
622
+ nl.second->ChangePortBusStructures(1 /* hierarchical */);
623
+
624
+ verific_extnets(nl_todo);
625
+
626
+ while (!nl_todo.empty()) {
627
+ auto it = nl_todo.begin();
628
+ Netlist *nl = it->second;
629
+ if (nl_done.count(it->first) == 0) {
630
+ VerificImporter importer(false, false, false, false, false, false, false, false);
631
+ nl_done[it->first] = it->second;
632
+ importer.import_netlist(design, nl, nl_todo, top_mod_names.count(nl->CellBaseName()));
633
+ }
634
+ nl_todo.erase(it);
635
+ }
636
+
637
+ if (!verific_error_msg.empty())
638
+ log_error("%s\n", verific_error_msg);
639
+ return top;
640
+ }
641
+
642
+ bool check_noverific_env()
643
+ {
644
+ const char *e = getenv("YOSYS_NOVERIFIC");
645
+ if (e == nullptr)
646
+ return false;
647
+ if (atoi(e) == 0)
648
+ return false;
649
+ return true;
650
+ }
651
+
652
+ YOSYS_NAMESPACE_END
653
+ #endif /* YOSYS_ENABLE_VERIFIC */
chips/yosys/frontends/verific/verific.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef VERIFIC_H
21
+ #define VERIFIC_H
22
+
23
+ #ifdef YOSYS_ENABLE_VERIFIC
24
+
25
+ #include <condition_variable>
26
+ #include <mutex>
27
+
28
+ #include "DataBase.h"
29
+
30
+ #include "frontends/verific/verific_clocking.h"
31
+ #include "frontends/verific/verific_importer.h"
32
+
33
+ YOSYS_NAMESPACE_BEGIN
34
+
35
+ extern int verific_verbose;
36
+
37
+ bool check_noverific_env();
38
+ void verific_setup();
39
+
40
+ struct VerificSession {
41
+ ~VerificSession();
42
+ static void begin(Design *design);
43
+ static std::unique_ptr<VerificSession> deferred_end(Design *design);
44
+ private:
45
+ static inline std::mutex mutex;
46
+ static inline std::condition_variable cv;
47
+ static inline Design *owner = nullptr;
48
+ };
49
+
50
+ extern bool verific_import_pending;
51
+ extern std::string verific_import(Design *design, const std::map<std::string,std::string> &parameters, std::string top = std::string());
52
+
53
+ extern pool<int> verific_sva_prims;
54
+
55
+ void verific_import_sva_assert(VerificImporter *importer, Verific::Instance *inst);
56
+ void verific_import_sva_assume(VerificImporter *importer, Verific::Instance *inst);
57
+ void verific_import_sva_cover(VerificImporter *importer, Verific::Instance *inst);
58
+ void verific_import_sva_trigger(VerificImporter *importer, Verific::Instance *inst);
59
+ bool verific_is_sva_net(VerificImporter *importer, Verific::Net *net);
60
+
61
+ extern int verific_sva_fsm_limit;
62
+
63
+ extern std::string verific_error_msg;
64
+
65
+ std::string get_full_netlist_name(Verific::Netlist *nl);
66
+ void save_blackbox_msg_state();
67
+ void restore_blackbox_msg_state();
68
+ void import_all(const char* work, std::map<std::string,Verific::Netlist*> *nl_todo, Verific::Map *parameters, bool show_message, std::string ppfile);
69
+ std::set<std::string> import_tops(const char* work, std::map<std::string,Verific::Netlist*> *nl_todo, Verific::Map *parameters, bool show_message, std::string ppfile, std::vector<std::string> &tops, std::string *top = nullptr);
70
+ void verific_extnets(const std::map<std::string,Verific::Netlist*> &nl_todo);
71
+
72
+ YOSYS_NAMESPACE_END
73
+
74
+ #endif
75
+ #endif
chips/yosys/frontends/verific/verific_clocking.cc ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+
22
+ #include "frontends/verific/verific.h"
23
+
24
+ #ifdef VERIFIC_NAMESPACE
25
+ using namespace Verific;
26
+ #endif
27
+
28
+ YOSYS_NAMESPACE_BEGIN
29
+
30
+ VerificClocking::VerificClocking(VerificImporter *importer, Net *net, bool sva_at_only YS_MAYBE_UNUSED)
31
+ {
32
+ module = importer->module;
33
+
34
+ log_assert(importer != nullptr);
35
+ log_assert(net != nullptr);
36
+
37
+ Instance *inst = net->Driver();
38
+
39
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
40
+ // Detect condition expression in sva_at_only mode
41
+ if (sva_at_only)
42
+ do {
43
+ Instance *inst_mux = net->Driver();
44
+ if (inst_mux == nullptr || inst_mux->Type() != PRIM_MUX)
45
+ break;
46
+
47
+ bool pwr1 = inst_mux->GetInput1()->IsPwr();
48
+ bool pwr2 = inst_mux->GetInput2()->IsPwr();
49
+
50
+ bool gnd1 = inst_mux->GetInput1()->IsGnd();
51
+ bool gnd2 = inst_mux->GetInput2()->IsGnd();
52
+
53
+ if (!pwr1 && !pwr2) {
54
+ pwr1 = gnd1;
55
+ pwr2 = gnd2;
56
+ }
57
+
58
+ if (!pwr1 && !pwr2)
59
+ break;
60
+
61
+ Net *sva_net = pwr1 ? inst_mux->GetInput2() : inst_mux->GetInput1();
62
+ if (!verific_is_sva_net(importer, sva_net))
63
+ break;
64
+
65
+ inst = sva_net->Driver();
66
+ cond_net = inst_mux->GetControl();
67
+ cond_pol = pwr1;
68
+ } while (0);
69
+
70
+ if (inst != nullptr && inst->Type() == PRIM_SVA_AT)
71
+ {
72
+ net = inst->GetInput1();
73
+ body_net = inst->GetInput2();
74
+
75
+ inst = net->Driver();
76
+
77
+ Instance *body_inst = body_net->Driver();
78
+ if (body_inst != nullptr && body_inst->Type() == PRIM_SVA_DISABLE_IFF) {
79
+ disable_net = body_inst->GetInput1();
80
+ disable_sig = importer->net_map_at(disable_net);
81
+ body_net = body_inst->GetInput2();
82
+ }
83
+ }
84
+ else
85
+ {
86
+ if (sva_at_only)
87
+ return;
88
+ }
89
+
90
+ // Use while() instead of if() to work around VIPER #13453
91
+ while (inst != nullptr && inst->Type() == PRIM_SVA_POSEDGE)
92
+ {
93
+ net = inst->GetInput();
94
+ inst = net->Driver();;
95
+ }
96
+ #endif
97
+ if (inst != nullptr && inst->Type() == PRIM_INV)
98
+ {
99
+ net = inst->GetInput();
100
+ inst = net->Driver();;
101
+ posedge = false;
102
+ }
103
+
104
+ // Detect clock-enable circuit
105
+ do {
106
+ if (inst == nullptr || inst->Type() != PRIM_AND)
107
+ break;
108
+
109
+ Net *net_dlatch = inst->GetInput1();
110
+ Instance *inst_dlatch = net_dlatch->Driver();
111
+
112
+ if (inst_dlatch == nullptr || inst_dlatch->Type() != PRIM_DLATCHRS)
113
+ break;
114
+
115
+ if (!inst_dlatch->GetSet()->IsGnd() || !inst_dlatch->GetReset()->IsGnd())
116
+ break;
117
+
118
+ Net *net_enable = inst_dlatch->GetInput();
119
+ Net *net_not_clock = inst_dlatch->GetControl();
120
+
121
+ if (net_enable == nullptr || net_not_clock == nullptr)
122
+ break;
123
+
124
+ Instance *inst_not_clock = net_not_clock->Driver();
125
+
126
+ if (inst_not_clock == nullptr || inst_not_clock->Type() != PRIM_INV)
127
+ break;
128
+
129
+ Net *net_clock1 = inst_not_clock->GetInput();
130
+ Net *net_clock2 = inst->GetInput2();
131
+
132
+ if (net_clock1 == nullptr || net_clock1 != net_clock2)
133
+ break;
134
+
135
+ enable_net = net_enable;
136
+ enable_sig = importer->net_map_at(enable_net);
137
+
138
+ net = net_clock1;
139
+ inst = net->Driver();;
140
+ } while (0);
141
+
142
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
143
+ // Detect condition expression
144
+ do {
145
+ if (body_net == nullptr)
146
+ break;
147
+
148
+ Instance *inst_mux = body_net->Driver();
149
+
150
+ if (inst_mux == nullptr || inst_mux->Type() != PRIM_MUX)
151
+ break;
152
+
153
+ bool pwr1 = inst_mux->GetInput1()->IsPwr();
154
+ bool pwr2 = inst_mux->GetInput2()->IsPwr();
155
+
156
+ bool gnd1 = inst_mux->GetInput1()->IsGnd();
157
+ bool gnd2 = inst_mux->GetInput2()->IsGnd();
158
+
159
+ if (!pwr1 && !pwr2) {
160
+ pwr1 = gnd1;
161
+ pwr2 = gnd2;
162
+ }
163
+
164
+ if (!pwr1 && !pwr2)
165
+ break;
166
+
167
+ Net *sva_net = pwr1 ? inst_mux->GetInput2() : inst_mux->GetInput1();
168
+ if (!verific_is_sva_net(importer, sva_net))
169
+ break;
170
+
171
+ body_net = sva_net;
172
+ cond_net = inst_mux->GetControl();
173
+ cond_pol = pwr1;
174
+ } while (0);
175
+
176
+ // Detect disable condition
177
+ do {
178
+ if (body_net == nullptr)
179
+ break;
180
+
181
+ Instance *inst_disable = body_net->Driver();
182
+ if (inst_disable == nullptr || inst_disable->Type() != PRIM_SVA_DISABLE_IFF)
183
+ break;
184
+
185
+ disable_net = inst_disable->GetInput1();
186
+ disable_sig = importer->net_map_at(disable_net);
187
+ body_net = inst_disable->GetInput2();
188
+ } while (0);
189
+ #endif
190
+
191
+ clock_net = net;
192
+ clock_sig = importer->net_map_at(clock_net);
193
+
194
+ const char *gclk_attr = clock_net->GetAttValue("gclk");
195
+ if (gclk_attr != nullptr && (!strcmp(gclk_attr, "1") || !strcmp(gclk_attr, "'1'")))
196
+ gclk = true;
197
+ }
198
+
199
+ Cell *VerificClocking::addDff(IdString name, SigSpec sig_d, SigSpec sig_q, Const init_value)
200
+ {
201
+ log_assert(GetSize(sig_d) == GetSize(sig_q));
202
+
203
+ auto set_init_attribute = [&](SigSpec &s) {
204
+ if (GetSize(init_value) == 0)
205
+ return;
206
+ log_assert(GetSize(s) == GetSize(init_value));
207
+ if (s.is_wire()) {
208
+ s.as_wire()->attributes[ID::init] = init_value;
209
+ } else {
210
+ Wire *w = module->addWire(NEW_ID, GetSize(s));
211
+ w->attributes[ID::init] = init_value;
212
+ module->connect(s, w);
213
+ s = w;
214
+ }
215
+ };
216
+
217
+ if (enable_sig != State::S1)
218
+ sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig);
219
+
220
+ if (disable_sig != State::S0) {
221
+ log_assert(GetSize(sig_q) == GetSize(init_value));
222
+
223
+ if (gclk) {
224
+ Wire *pre_d = module->addWire(NEW_ID, GetSize(sig_d));
225
+ Wire *post_q_w = module->addWire(NEW_ID, GetSize(sig_q));
226
+
227
+ Const initval(State::Sx, GetSize(sig_q));
228
+ int offset = 0;
229
+ for (auto c : sig_q.chunks()) {
230
+ if (c.wire && c.wire->attributes.count(ID::init)) {
231
+ Const val = c.wire->attributes.at(ID::init);
232
+ for (int i = 0; i < GetSize(c); i++)
233
+ initval.set(offset+i, val[c.offset+i]);
234
+ }
235
+ offset += GetSize(c);
236
+ }
237
+
238
+ if (!initval.is_fully_undef())
239
+ post_q_w->attributes[ID::init] = initval;
240
+
241
+ module->addMux(NEW_ID, sig_d, init_value, disable_sig, pre_d);
242
+ module->addMux(NEW_ID, post_q_w, init_value, disable_sig, sig_q);
243
+
244
+ SigSpec post_q(post_q_w);
245
+ set_init_attribute(post_q);
246
+ return module->addFf(name, pre_d, post_q);
247
+ }
248
+
249
+ set_init_attribute(sig_q);
250
+ return module->addAdff(name, clock_sig, disable_sig, sig_d, sig_q, init_value, posedge);
251
+ }
252
+
253
+ if (gclk) {
254
+ set_init_attribute(sig_q);
255
+ return module->addFf(name, sig_d, sig_q);
256
+ }
257
+
258
+ set_init_attribute(sig_q);
259
+ return module->addDff(name, clock_sig, sig_d, sig_q, posedge);
260
+ }
261
+
262
+ Cell *VerificClocking::addAdff(IdString name, RTLIL::SigSpec sig_arst, SigSpec sig_d, SigSpec sig_q, Const arst_value)
263
+ {
264
+ log_assert(gclk == false);
265
+ log_assert(disable_sig == State::S0);
266
+
267
+ // FIXME: Adffe
268
+ if (enable_sig != State::S1)
269
+ sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig);
270
+
271
+ return module->addAdff(name, clock_sig, sig_arst, sig_d, sig_q, arst_value, posedge);
272
+ }
273
+
274
+ Cell *VerificClocking::addDffsr(IdString name, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr, SigSpec sig_d, SigSpec sig_q)
275
+ {
276
+ log_assert(gclk == false);
277
+ log_assert(disable_sig == State::S0);
278
+
279
+ // FIXME: Dffsre
280
+ if (enable_sig != State::S1)
281
+ sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig);
282
+
283
+ return module->addDffsr(name, clock_sig, sig_set, sig_clr, sig_d, sig_q, posedge);
284
+ }
285
+
286
+ Cell *VerificClocking::addAldff(IdString name, RTLIL::SigSpec sig_aload, RTLIL::SigSpec sig_adata, SigSpec sig_d, SigSpec sig_q)
287
+ {
288
+ log_assert(disable_sig == State::S0);
289
+
290
+ // FIXME: Aldffe
291
+ if (enable_sig != State::S1)
292
+ sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig);
293
+
294
+ if (gclk) {
295
+ Wire *pre_d = module->addWire(NEW_ID, GetSize(sig_d));
296
+ Wire *post_q = module->addWire(NEW_ID, GetSize(sig_q));
297
+
298
+ Const initval(State::Sx, GetSize(sig_q));
299
+ int offset = 0;
300
+ for (auto c : sig_q.chunks()) {
301
+ if (c.wire && c.wire->attributes.count(ID::init)) {
302
+ Const val = c.wire->attributes.at(ID::init);
303
+ for (int i = 0; i < GetSize(c); i++)
304
+ initval.set(offset+i, val[c.offset+i]);
305
+ }
306
+ offset += GetSize(c);
307
+ }
308
+
309
+ if (!initval.is_fully_undef())
310
+ post_q->attributes[ID::init] = initval;
311
+
312
+ module->addMux(NEW_ID, sig_d, sig_adata, sig_aload, pre_d);
313
+ module->addMux(NEW_ID, post_q, sig_adata, sig_aload, sig_q);
314
+
315
+ return module->addFf(name, pre_d, post_q);
316
+ }
317
+
318
+ return module->addAldff(name, clock_sig, sig_aload, sig_d, sig_q, sig_adata, posedge);
319
+ }
320
+
321
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verific/verific_clocking.h ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef VERIFIC_CLOCKING_H
21
+ #define VERIFIC_CLOCKING_H
22
+
23
+ #ifdef YOSYS_ENABLE_VERIFIC
24
+
25
+ #include "kernel/yosys.h"
26
+
27
+ #include "DataBase.h"
28
+
29
+ YOSYS_NAMESPACE_BEGIN
30
+
31
+ struct VerificImporter;
32
+
33
+ struct VerificClocking {
34
+ RTLIL::Module *module = nullptr;
35
+ Verific::Net *clock_net = nullptr;
36
+ Verific::Net *enable_net = nullptr;
37
+ Verific::Net *disable_net = nullptr;
38
+ Verific::Net *body_net = nullptr;
39
+ Verific::Net *cond_net = nullptr;
40
+ SigBit clock_sig = State::Sx;
41
+ SigBit enable_sig = State::S1;
42
+ SigBit disable_sig = State::S0;
43
+ bool posedge = true;
44
+ bool gclk = false;
45
+ bool cond_pol = true;
46
+
47
+ VerificClocking() { }
48
+ VerificClocking(VerificImporter *importer, Verific::Net *net, bool sva_at_only = false);
49
+ RTLIL::Cell *addDff(IdString name, SigSpec sig_d, SigSpec sig_q, Const init_value = Const());
50
+ RTLIL::Cell *addAdff(IdString name, RTLIL::SigSpec sig_arst, SigSpec sig_d, SigSpec sig_q, Const arst_value);
51
+ RTLIL::Cell *addDffsr(IdString name, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr, SigSpec sig_d, SigSpec sig_q);
52
+ RTLIL::Cell *addAldff(IdString name, RTLIL::SigSpec sig_aload, RTLIL::SigSpec sig_adata, SigSpec sig_d, SigSpec sig_q);
53
+ YS_NAME_FWD_POOL(addDff, module->twines()) YS_NAME_FWD_POOL(addAdff, module->twines())
54
+ YS_NAME_FWD_POOL(addDffsr, module->twines()) YS_NAME_FWD_POOL(addAldff, module->twines())
55
+
56
+ bool property_matches_sequence(const VerificClocking &seq) const {
57
+ if (clock_net != seq.clock_net)
58
+ return false;
59
+ if (enable_net != seq.enable_net)
60
+ return false;
61
+ if (posedge != seq.posedge)
62
+ return false;
63
+ return true;
64
+ }
65
+ };
66
+
67
+ YOSYS_NAMESPACE_END
68
+
69
+ #endif
70
+ #endif
chips/yosys/frontends/verific/verific_command.cc ADDED
@@ -0,0 +1,986 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+ #include "kernel/log.h"
22
+ #include <filesystem>
23
+
24
+ #include "frontends/verific/verific_command.h"
25
+
26
+ #ifdef __clang__
27
+ #pragma clang diagnostic push
28
+ #pragma clang diagnostic ignored "-Woverloaded-virtual"
29
+ #endif
30
+
31
+ #include "Array.h"
32
+ #include "RuntimeFlags.h"
33
+
34
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
35
+ #include "veri_file.h"
36
+ #include "VeriModule.h"
37
+ #include "VeriWrite.h"
38
+ #include "VeriLibrary.h"
39
+ #endif
40
+
41
+ #ifdef VERIFIC_VHDL_SUPPORT
42
+ #include "vhdl_file.h"
43
+ #include "VhdlUnits.h"
44
+ #endif
45
+
46
+ #ifdef VERIFIC_EDIF_SUPPORT
47
+ #include "edif_file.h"
48
+ #endif
49
+
50
+ #ifdef VERIFIC_LIBERTY_SUPPORT
51
+ #include "synlib_file.h"
52
+ #include "SynlibGroup.h"
53
+ #endif
54
+
55
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
56
+ #include "VerificExtensions.h"
57
+ #endif
58
+
59
+ #ifdef __clang__
60
+ #pragma clang diagnostic pop
61
+ #endif
62
+
63
+ #ifdef VERIFIC_NAMESPACE
64
+ using namespace Verific;
65
+ #endif
66
+
67
+ YOSYS_NAMESPACE_BEGIN
68
+
69
+ static bool already_imported = false;
70
+
71
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
72
+ static std::vector<std::string> verific_incdirs, verific_libdirs, verific_libexts;
73
+ #endif
74
+
75
+ void VerificCommand::reset_settings()
76
+ {
77
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
78
+ verific_incdirs.clear();
79
+ verific_libdirs.clear();
80
+ verific_libexts.clear();
81
+ #endif
82
+ }
83
+
84
+ VerificCommand::VerificCommand(Pass &pass, std::vector<std::string> &args, RTLIL::Design *design) : pass(pass), args(args), design(design)
85
+ {
86
+ for (; argidx < GetSize(args); argidx++)
87
+ {
88
+ if (args[argidx] == "-work" && argidx+1 < GetSize(args)) {
89
+ work = args[++argidx];
90
+ is_work_set = true;
91
+ continue;
92
+ }
93
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
94
+ if (args[argidx] == "-L" && argidx+1 < GetSize(args)) {
95
+ search_libraries.push_back(args[++argidx]);
96
+ continue;
97
+ }
98
+ #endif
99
+ break;
100
+ }
101
+
102
+ if (argidx < GetSize(args))
103
+ mode = args[argidx];
104
+ }
105
+
106
+ VerificCommand::~VerificCommand()
107
+ {
108
+ if (tmp_files.empty())
109
+ return;
110
+ log("Removing temp files.\n");
111
+ for (auto &fn : tmp_files)
112
+ remove(fn.c_str());
113
+ }
114
+
115
+ void VerificCommand::apply_library_options()
116
+ {
117
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
118
+ veri_file::RemoveAllLOptions();
119
+ if (std::find(search_libraries.begin(), search_libraries.end(), work) == search_libraries.end())
120
+ veri_file::AddLOption(work.c_str());
121
+ for (auto &library : search_libraries)
122
+ veri_file::AddLOption(library.c_str());
123
+ #endif
124
+ }
125
+
126
+ bool VerificCommand::change_setting()
127
+ {
128
+ if (mode == "-set-error" || mode == "-set-warning" || mode == "-set-info" || mode == "-set-ignore")
129
+ set_msg_type();
130
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
131
+ else if (mode == "-vlog-incdir")
132
+ append_remaining_args(verific_incdirs);
133
+ else if (mode == "-vlog-libdir")
134
+ append_remaining_args(verific_libdirs);
135
+ else if (mode == "-vlog-libext")
136
+ append_remaining_args(verific_libexts);
137
+ else if (mode == "-vlog-define")
138
+ define_macros();
139
+ else if (mode == "-vlog-undef")
140
+ undefine_macros();
141
+ #endif
142
+ else
143
+ return false;
144
+ return true;
145
+ }
146
+
147
+ void VerificCommand::run()
148
+ {
149
+ if (change_setting())
150
+ return;
151
+
152
+ apply_library_options();
153
+
154
+ if (mode == "-import")
155
+ import_design();
156
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
157
+ else if (mode == "-target")
158
+ read_target();
159
+ else if (mode == "-f" || mode == "-F")
160
+ read_f_file();
161
+ else if (const VerilogStandard *verilog = find_verilog_standard(mode))
162
+ read_verilog(*verilog);
163
+ #endif
164
+ #ifdef VERIFIC_VHDL_SUPPORT
165
+ else if (const VhdlStandard *vhdl = find_vhdl_standard(mode))
166
+ read_vhdl(*vhdl);
167
+ #endif
168
+ #ifdef VERIFIC_EDIF_SUPPORT
169
+ else if (mode == "-edif")
170
+ read_edif();
171
+ #endif
172
+ #ifdef VERIFIC_LIBERTY_SUPPORT
173
+ else if (mode == "-liberty")
174
+ read_liberty();
175
+ #endif
176
+ else if (mode == "-pp")
177
+ pretty_print();
178
+ else if (mode == "-cfg")
179
+ configure();
180
+ else
181
+ run_extension();
182
+ }
183
+
184
+ std::string VerificCommand::frontend_rewrite()
185
+ {
186
+ std::string filename = args[argidx++];
187
+ //Accommodate heredocs with EOT marker spaced out from "<<", e.g. "<< EOT" vs. "<<EOT"
188
+ if (filename == "<<" && (argidx < GetSize(args))) {
189
+ filename += args[argidx++];
190
+ }
191
+ if (filename.compare(0, 2, "<<") == 0) {
192
+ if (filename.size() <= 2)
193
+ log_error("Missing EOT marker in here document!\n");
194
+ std::string eot_marker = filename.substr(2);
195
+ if (Frontend::current_script_file == nullptr)
196
+ filename = "<stdin>";
197
+ std::string last_here_document;
198
+ while (1) {
199
+ std::string buffer;
200
+ char block[4096];
201
+ while (1) {
202
+ if (fgets(block, 4096, Frontend::current_script_file == nullptr? stdin : Frontend::current_script_file) == nullptr)
203
+ log_error("Unexpected end of file in here document '%s'!\n", filename);
204
+ buffer += block;
205
+ if (buffer.size() > 0 && (buffer[buffer.size() - 1] == '\n' || buffer[buffer.size() - 1] == '\r'))
206
+ break;
207
+ }
208
+ size_t indent = buffer.find_first_not_of(" \t\r\n");
209
+ if (indent != std::string::npos && buffer.compare(indent, eot_marker.size(), eot_marker) == 0)
210
+ break;
211
+ last_here_document += buffer;
212
+ }
213
+ filename = make_temp_file();
214
+ tmp_files.push_back(filename);
215
+ std::ofstream file(filename);
216
+ file << last_here_document;
217
+ } else {
218
+ rewrite_filename(filename);
219
+ }
220
+ return filename;
221
+ }
222
+
223
+
224
+ #ifdef VERIFIC_VHDL_SUPPORT
225
+ static void add_units_to_map(Map &map, std::string work, bool flag_lib)
226
+ {
227
+ MapIter mi ;
228
+ VhdlPrimaryUnit *unit ;
229
+ if (!flag_lib) return;
230
+ VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work.c_str(), 1);
231
+ if (vhdl_lib) {
232
+ FOREACH_VHDL_PRIMARY_UNIT(vhdl_lib, mi, unit) {
233
+ if (!unit) continue;
234
+ map.Insert(unit,unit);
235
+ }
236
+ }
237
+ save_blackbox_msg_state();
238
+ }
239
+
240
+ static void set_units_to_blackbox(Map &map, std::string work, bool flag_lib)
241
+ {
242
+ MapIter mi ;
243
+ VhdlPrimaryUnit *unit ;
244
+ if (!flag_lib) return;
245
+ VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work.c_str(), 1);
246
+ FOREACH_VHDL_PRIMARY_UNIT(vhdl_lib, mi, unit) {
247
+ if (!unit) continue;
248
+ if (!map.GetValue(unit)) {
249
+ unit->SetCompileAsBlackbox();
250
+ }
251
+ }
252
+ restore_blackbox_msg_state();
253
+ }
254
+ #endif
255
+
256
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
257
+ static void add_modules_to_map(Map &map, std::string work, bool flag_lib)
258
+ {
259
+ MapIter mi ;
260
+ VeriModule *veri_module ;
261
+ if (!flag_lib) return;
262
+ VeriLibrary *veri_lib = veri_file::GetLibrary(work.c_str(), 1);
263
+ if (veri_lib) {
264
+ FOREACH_VERILOG_MODULE_IN_LIBRARY(veri_lib, mi, veri_module) {
265
+ if (!veri_module) continue;
266
+ map.Insert(veri_module,veri_module);
267
+ }
268
+ }
269
+ save_blackbox_msg_state();
270
+ }
271
+
272
+ static void set_modules_to_blackbox(Map &map, std::string work, bool flag_lib)
273
+ {
274
+ MapIter mi ;
275
+ VeriModule *veri_module ;
276
+ if (!flag_lib) return;
277
+ VeriLibrary *veri_lib = veri_file::GetLibrary(work.c_str(), 1);
278
+ FOREACH_VERILOG_MODULE_IN_LIBRARY(veri_lib, mi, veri_module) {
279
+ if (!veri_module) continue;
280
+ if (!map.GetValue(veri_module)) {
281
+ veri_module->SetCompileAsBlackbox();
282
+ }
283
+ }
284
+ restore_blackbox_msg_state();
285
+ }
286
+ #endif
287
+
288
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
289
+ struct VerificCommand::VerilogStandard {
290
+ const char *flag;
291
+ unsigned mode;
292
+ };
293
+
294
+ const VerificCommand::VerilogStandard *VerificCommand::find_verilog_standard(const std::string &flag)
295
+ {
296
+ static const VerilogStandard standards[] = {
297
+ {"-vlog95", veri_file::VERILOG_95},
298
+ {"-vlog2k", veri_file::VERILOG_2K},
299
+ {"-sv2005", veri_file::SYSTEM_VERILOG_2005},
300
+ {"-sv2009", veri_file::SYSTEM_VERILOG_2009},
301
+ {"-sv2012", veri_file::SYSTEM_VERILOG_2012},
302
+ {"-sv2017", veri_file::SYSTEM_VERILOG_2017},
303
+ {"-sv2023", veri_file::SYSTEM_VERILOG_2023},
304
+ {"-sv", veri_file::SYSTEM_VERILOG},
305
+ {"-formal", veri_file::SYSTEM_VERILOG},
306
+ };
307
+ for (auto &standard : standards)
308
+ if (flag == standard.flag)
309
+ return &standard;
310
+ return nullptr;
311
+ }
312
+
313
+ static void analyze_verilog_files(Array &file_names, unsigned verilog_mode, const std::string &work, bool flag_lib)
314
+ {
315
+ Map map(POINTER_HASH);
316
+ add_modules_to_map(map, work, flag_lib);
317
+ if (!veri_file::AnalyzeMultipleFiles(&file_names, verilog_mode, work.c_str(), veri_file::MFCU)) {
318
+ verific_error_msg.clear();
319
+ log_cmd_error("Reading Verilog/SystemVerilog sources failed.\n");
320
+ }
321
+ char* fn;
322
+ int i = 0;
323
+
324
+ FOREACH_ARRAY_ITEM(&file_names, i, fn) {
325
+ free(fn);
326
+ }
327
+ set_modules_to_blackbox(map, work, flag_lib);
328
+ verific_import_pending = true;
329
+ }
330
+ #endif
331
+
332
+ #ifdef VERIFIC_VHDL_SUPPORT
333
+ struct VerificCommand::VhdlStandard {
334
+ const char *flag;
335
+ unsigned mode;
336
+ const char *name;
337
+ const char *library_dir;
338
+
339
+ void set_library_path() const
340
+ {
341
+ vhdl_file::SetDefaultLibraryPath((proc_share_dirname() + library_dir).c_str());
342
+ }
343
+ };
344
+
345
+ const VerificCommand::VhdlStandard *VerificCommand::find_vhdl_standard(const std::string &flag)
346
+ {
347
+ static const VhdlStandard standards[] = {
348
+ {"-vhdl87", vhdl_file::VHDL_87, "VHDL_87", "verific/vhdl_vdbs_1987"},
349
+ {"-vhdl93", vhdl_file::VHDL_93, "VHDL_93", "verific/vhdl_vdbs_1993"},
350
+ {"-vhdl2k", vhdl_file::VHDL_2K, "VHDL_2K", "verific/vhdl_vdbs_1993"},
351
+ {"-vhdl2008", vhdl_file::VHDL_2008, "VHDL_2008", "verific/vhdl_vdbs_2008"},
352
+ {"-vhdl2019", vhdl_file::VHDL_2019, "VHDL_2019", "verific/vhdl_vdbs_2019"},
353
+ {"-vhdl", vhdl_file::VHDL_2008, "VHDL_2008", "verific/vhdl_vdbs_2008"},
354
+ };
355
+ for (auto &standard : standards)
356
+ if (flag == standard.flag)
357
+ return &standard;
358
+ return nullptr;
359
+ }
360
+ #endif
361
+
362
+ void VerificCommand::set_msg_type()
363
+ {
364
+ msg_type_t new_type;
365
+
366
+ if (mode == "-set-error")
367
+ new_type = VERIFIC_ERROR;
368
+ else if (mode == "-set-warning")
369
+ new_type = VERIFIC_WARNING;
370
+ else if (mode == "-set-info")
371
+ new_type = VERIFIC_INFO;
372
+ else if (mode == "-set-ignore")
373
+ new_type = VERIFIC_IGNORE;
374
+ else
375
+ log_abort();
376
+
377
+ for (argidx++; argidx < GetSize(args); argidx++) {
378
+ if (Strings::compare(args[argidx].c_str(), "errors")) {
379
+ Message::SetMessageType("VERI-1063", new_type);
380
+ Message::SetAllMessageType(VERIFIC_ERROR, new_type);
381
+ } else if (Strings::compare(args[argidx].c_str(), "warnings")) {
382
+ Message::SetAllMessageType(VERIFIC_WARNING, new_type);
383
+ } else if (Strings::compare(args[argidx].c_str(), "infos")) {
384
+ Message::SetMessageType("VERI-1209", new_type);
385
+ Message::SetMessageType("VERI-1142", new_type);
386
+ Message::SetMessageType("VERI-2418", new_type);
387
+ Message::SetAllMessageType(VERIFIC_INFO, new_type);
388
+ } else if (Strings::compare(args[argidx].c_str(), "comments")) {
389
+ Message::SetAllMessageType(VERIFIC_COMMENT, new_type);
390
+ } else {
391
+ Message::SetMessageType(args[argidx].c_str(), new_type);
392
+ }
393
+ }
394
+ }
395
+
396
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
397
+ void VerificCommand::append_remaining_args(std::vector<std::string> &list)
398
+ {
399
+ for (argidx++; argidx < GetSize(args); argidx++)
400
+ list.push_back(args[argidx]);
401
+ }
402
+
403
+ void VerificCommand::define_macros()
404
+ {
405
+ for (argidx++; argidx < GetSize(args); argidx++) {
406
+ string name = args[argidx];
407
+ size_t equal = name.find('=');
408
+ if (equal != std::string::npos) {
409
+ string value = name.substr(equal+1);
410
+ name = name.substr(0, equal);
411
+ veri_file::DefineCmdLineMacro(name.c_str(), value.c_str());
412
+ } else {
413
+ veri_file::DefineCmdLineMacro(name.c_str());
414
+ }
415
+ }
416
+ }
417
+
418
+ void VerificCommand::undefine_macros()
419
+ {
420
+ for (argidx++; argidx < GetSize(args); argidx++) {
421
+ string name = args[argidx];
422
+ veri_file::UndefineMacro(name.c_str());
423
+ }
424
+ }
425
+
426
+ void VerificCommand::read_target()
427
+ {
428
+ argidx++;
429
+ log_experimental("verific -target");
430
+
431
+ if (argidx >= GetSize(args))
432
+ log_cmd_error("Missing target for `-target'.\n");
433
+
434
+ std::string synth_target = args[argidx++];
435
+ std::string synth_family;
436
+
437
+ if (argidx < GetSize(args) && args[argidx] == "-family") {
438
+ argidx++;
439
+ log_experimental("verific -family");
440
+
441
+ if (argidx >= GetSize(args))
442
+ log_cmd_error("Missing family for `-family'.\n");
443
+
444
+ synth_family = args[argidx++];
445
+ } else if (argidx < GetSize(args) && args[argidx][0] == '-') {
446
+ log_cmd_error("Unknown option `%s'.\n", args[argidx]);
447
+ }
448
+ auto target_it = target_register.find(synth_target);
449
+ if (target_it == target_register.end())
450
+ log_cmd_error("Unknown target '%s'.\n", synth_target);
451
+
452
+ auto family_it = target_it->second.families.find(synth_family);
453
+ if (family_it == target_it->second.families.end()) {
454
+ if (synth_family.empty())
455
+ log_cmd_error("Family must be specified for target '%s'.\n", synth_target);
456
+ else
457
+ log_cmd_error("Unknown family '%s' for target '%s'.\n",
458
+ synth_family, synth_target);
459
+ }
460
+
461
+ bool flag_lib = true;
462
+ Array file_names;
463
+ unsigned verilog_mode = veri_file::SYSTEM_VERILOG;
464
+ veri_file::DefineMacro("YOSYS");
465
+ veri_file::DefineMacro("VERIFIC");
466
+
467
+ for (auto &file : family_it->second.files) {
468
+ rewrite_filename(file);
469
+ file_names.Insert(strdup(file.c_str()));
470
+ std::string dir = std::filesystem::path(file).parent_path().string();
471
+ veri_file::AddIncludeDir(dir.c_str());
472
+ }
473
+
474
+ analyze_verilog_files(file_names, verilog_mode, work, flag_lib);
475
+ }
476
+
477
+ void VerificCommand::read_f_file()
478
+ {
479
+ unsigned verilog_mode = veri_file::UNDEFINED;
480
+ #ifdef VERIFIC_VHDL_SUPPORT
481
+ unsigned vhdl_mode = vhdl_file::UNDEFINED;
482
+ #endif
483
+ bool is_formal = false;
484
+ const char* filename = nullptr;
485
+
486
+ Verific::veri_file::f_file_flags flags = (args[argidx] == "-f") ? veri_file::F_FILE_NONE : veri_file::F_FILE_CAPITAL;
487
+
488
+ for (argidx++; argidx < GetSize(args); argidx++) {
489
+ if (const VerilogStandard *verilog = find_verilog_standard(args[argidx])) {
490
+ verilog_mode = verilog->mode;
491
+ if (args[argidx] == "-formal") is_formal = true;
492
+ continue;
493
+ }
494
+ #ifdef VERIFIC_VHDL_SUPPORT
495
+ if (const VhdlStandard *vhdl = find_vhdl_standard(args[argidx])) {
496
+ vhdl_mode = vhdl->mode;
497
+ vhdl->set_library_path();
498
+ continue;
499
+ }
500
+ #endif
501
+ if (args[argidx].compare(0, 1, "-") == 0)
502
+ pass.cmd_error(args, argidx, "unknown option");
503
+
504
+ if (filename)
505
+ log_cmd_error("Only one filename can be specified.\n");
506
+ filename = args[argidx].c_str();
507
+ }
508
+ if (!filename)
509
+ log_cmd_error("Filename must be specified.\n");
510
+
511
+ unsigned analysis_mode = verilog_mode; // keep default as provided by user if not defined in file
512
+ Array *file_names = veri_file::ProcessFFile(filename, flags, analysis_mode);
513
+ if (analysis_mode != verilog_mode)
514
+ log_warning("Provided verilog mode differs from one specified in file.\n");
515
+
516
+ veri_file::DefineMacro("YOSYS");
517
+ veri_file::DefineMacro("VERIFIC");
518
+ veri_file::DefineMacro(is_formal ? "FORMAL" : "SYNTHESIS");
519
+
520
+ #ifdef VERIFIC_VHDL_SUPPORT
521
+ if (vhdl_mode == vhdl_file::UNDEFINED) {
522
+ vhdl_file::SetDefaultLibraryPath((proc_share_dirname() + "verific/vhdl_vdbs_2008").c_str());
523
+ vhdl_mode = vhdl_file::VHDL_2008;
524
+ }
525
+ int i;
526
+ Array *file_names_sv = new Array(POINTER_HASH);
527
+ FOREACH_ARRAY_ITEM(file_names, i, filename) {
528
+ std::string filename_str = filename;
529
+ if ((filename_str.substr(filename_str.find_last_of(".") + 1) == "vhd") ||
530
+ (filename_str.substr(filename_str.find_last_of(".") + 1) == "vhdl")) {
531
+ if (!vhdl_file::Analyze(filename, work.c_str(), vhdl_mode)) {
532
+ verific_error_msg.clear();
533
+ log_cmd_error("Reading VHDL sources failed.\n");
534
+ }
535
+ } else {
536
+ file_names_sv->Insert(strdup(filename));
537
+ }
538
+ }
539
+ if (!veri_file::AnalyzeMultipleFiles(file_names_sv, analysis_mode, work.c_str(), veri_file::MFCU)) {
540
+ verific_error_msg.clear();
541
+ log_cmd_error("Reading Verilog/SystemVerilog sources failed.\n");
542
+ }
543
+ delete file_names_sv;
544
+ #else
545
+ if (!veri_file::AnalyzeMultipleFiles(file_names, analysis_mode, work.c_str(), veri_file::MFCU)) {
546
+ verific_error_msg.clear();
547
+ log_cmd_error("Reading Verilog/SystemVerilog sources failed.\n");
548
+ }
549
+ #endif
550
+
551
+ delete file_names;
552
+ verific_import_pending = true;
553
+ }
554
+
555
+ void VerificCommand::read_verilog(const VerilogStandard &standard)
556
+ {
557
+ Array file_names;
558
+ unsigned verilog_mode = standard.mode;
559
+
560
+ veri_file::DefineMacro("YOSYS");
561
+ veri_file::DefineMacro("VERIFIC");
562
+ veri_file::DefineMacro(args[argidx] == "-formal" ? "FORMAL" : "SYNTHESIS");
563
+
564
+ for (argidx++; argidx < GetSize(args) && GetSize(args[argidx]) >= 2 && args[argidx].compare(0, 2, "-D") == 0; argidx++) {
565
+ std::string name = args[argidx].substr(2);
566
+ if (args[argidx] == "-D") {
567
+ if (++argidx >= GetSize(args))
568
+ break;
569
+ name = args[argidx];
570
+ }
571
+ size_t equal = name.find('=');
572
+ if (equal != std::string::npos) {
573
+ string value = name.substr(equal+1);
574
+ name = name.substr(0, equal);
575
+ veri_file::DefineMacro(name.c_str(), value.c_str());
576
+ } else {
577
+ veri_file::DefineMacro(name.c_str());
578
+ }
579
+ }
580
+
581
+ for (auto &dir : verific_incdirs)
582
+ veri_file::AddIncludeDir(dir.c_str());
583
+ for (auto &dir : verific_libdirs)
584
+ veri_file::AddYDir(dir.c_str());
585
+ for (auto &ext : verific_libexts)
586
+ veri_file::AddLibExt(ext.c_str());
587
+
588
+ bool flag_lib = false;
589
+ while (argidx < GetSize(args)) {
590
+ if (args[argidx] == "-lib") {
591
+ flag_lib = true;
592
+ argidx++;
593
+ continue;
594
+ }
595
+ if (args[argidx].compare(0, 1, "-") == 0) {
596
+ pass.cmd_error(args, argidx, "unknown option");
597
+ return;
598
+ }
599
+ std::string filename = frontend_rewrite();
600
+ file_names.Insert(strdup(filename.c_str()));
601
+ }
602
+ analyze_verilog_files(file_names, verilog_mode, work, flag_lib);
603
+ }
604
+ #endif
605
+
606
+ #ifdef VERIFIC_VHDL_SUPPORT
607
+ void VerificCommand::read_vhdl(const VhdlStandard &standard)
608
+ {
609
+ standard.set_library_path();
610
+ argidx++;
611
+ bool flag_lib = false;
612
+ while (argidx < GetSize(args)) {
613
+ if (args[argidx] == "-lib") {
614
+ flag_lib = true;
615
+ argidx++;
616
+ continue;
617
+ }
618
+ if (args[argidx].compare(0, 1, "-") == 0)
619
+ pass.cmd_error(args, argidx, "unknown option");
620
+ Map map(POINTER_HASH);
621
+ add_units_to_map(map, work, flag_lib);
622
+ std::string filename = frontend_rewrite();
623
+ if (!vhdl_file::Analyze(filename.c_str(), work.c_str(), standard.mode))
624
+ log_cmd_error("Reading `%s' in %s mode failed.\n", filename, standard.name);
625
+ set_units_to_blackbox(map, work, flag_lib);
626
+ }
627
+ verific_import_pending = true;
628
+ }
629
+ #endif
630
+
631
+ #ifdef VERIFIC_EDIF_SUPPORT
632
+ void VerificCommand::read_edif()
633
+ {
634
+ edif_file edif;
635
+ argidx++;
636
+ while (argidx < GetSize(args)) {
637
+ std::string filename = frontend_rewrite();
638
+ if (!edif.Read(filename.c_str()))
639
+ log_cmd_error("Reading `%s' in EDIF mode failed.\n", filename);
640
+ }
641
+ }
642
+ #endif
643
+
644
+ #ifdef VERIFIC_LIBERTY_SUPPORT
645
+ void VerificCommand::read_liberty()
646
+ {
647
+ bool flag_lib = false;
648
+ for (argidx++; argidx < GetSize(args); argidx++) {
649
+ if (args[argidx] == "-lib") {
650
+ flag_lib = true;
651
+ continue;
652
+ }
653
+ if (args[argidx].compare(0, 1, "-") == 0) {
654
+ pass.cmd_error(args, argidx, "unknown option");
655
+ return;
656
+ }
657
+ break;
658
+ }
659
+
660
+ while (argidx < GetSize(args)) {
661
+ std::string filename = frontend_rewrite();
662
+ if (!synlib_file::Read(filename.c_str(), is_work_set ? work.c_str() : nullptr))
663
+ log_cmd_error("Reading `%s' in LIBERTY mode failed.\n", filename);
664
+ SynlibLibrary *lib = synlib_file::GetLastLibraryAnalyzed();
665
+ if (lib && flag_lib) {
666
+ MapIter mi ;
667
+ Verific::Cell *c ;
668
+ FOREACH_CELL_OF_LIBRARY(lib->GetLibrary(),mi,c) {
669
+ MapIter ni ;
670
+ Netlist *nl;
671
+ FOREACH_NETLIST_OF_CELL(c, ni, nl) {
672
+ if (nl)
673
+ nl->MakeBlackBox();
674
+ }
675
+ }
676
+ }
677
+ }
678
+ }
679
+ #endif
680
+
681
+ void VerificCommand::pretty_print()
682
+ {
683
+ const char* filename = nullptr;
684
+ const char* module = nullptr;
685
+ bool mode_vhdl = false;
686
+ for (argidx++; argidx < GetSize(args); argidx++) {
687
+ #ifdef VERIFIC_VHDL_SUPPORT
688
+ if (args[argidx] == "-vhdl") {
689
+ mode_vhdl = true;
690
+ continue;
691
+ }
692
+ #endif
693
+ if (args[argidx] == "-verilog") {
694
+ mode_vhdl = false;
695
+ continue;
696
+ }
697
+
698
+ if (args[argidx].compare(0, 1, "-") == 0) {
699
+ pass.cmd_error(args, argidx, "unknown option");
700
+ return;
701
+ }
702
+
703
+ if (!filename) {
704
+ filename = args[argidx].c_str();
705
+ continue;
706
+ }
707
+ if (module)
708
+ log_cmd_error("Only one module can be specified.\n");
709
+ module = args[argidx].c_str();
710
+ }
711
+
712
+ if (argidx < GetSize(args))
713
+ pass.cmd_error(args, argidx, "unknown option/parameter");
714
+
715
+ if (!filename)
716
+ log_cmd_error("Filename must be specified.\n");
717
+
718
+ if (mode_vhdl) {
719
+ #ifdef VERIFIC_VHDL_SUPPORT
720
+ vhdl_file::PrettyPrint(filename, module, work.c_str());
721
+ #endif
722
+ return;
723
+ }
724
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
725
+ veri_file::PrettyPrint(filename, module, work.c_str());
726
+ #endif
727
+ }
728
+
729
+ void VerificCommand::import_design()
730
+ {
731
+ std::map<std::string,Netlist*> nl_todo, nl_done;
732
+ bool mode_all = false, mode_gates = false, mode_keep = false;
733
+ bool mode_nosva = false, mode_sva_continue = false;
734
+ bool mode_names = false, mode_verific = false;
735
+ bool mode_autocover = false, mode_fullinit = false;
736
+ bool flatten = false, extnets = false, mode_cells = false;
737
+ bool split_complex_ports = true;
738
+ string dumpfile;
739
+ string ppfile;
740
+ Map parameters(STRING_HASH);
741
+
742
+ for (argidx++; argidx < GetSize(args); argidx++) {
743
+ if (args[argidx] == "-all") {
744
+ mode_all = true;
745
+ continue;
746
+ }
747
+ if (args[argidx] == "-gates") {
748
+ mode_gates = true;
749
+ continue;
750
+ }
751
+ if (args[argidx] == "-flatten") {
752
+ flatten = true;
753
+ continue;
754
+ }
755
+ if (args[argidx] == "-no-split-complex-ports") {
756
+ split_complex_ports = false;
757
+ continue;
758
+ }
759
+ if (args[argidx] == "-extnets") {
760
+ extnets = true;
761
+ continue;
762
+ }
763
+ if (args[argidx] == "-k") {
764
+ mode_keep = true;
765
+ continue;
766
+ }
767
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
768
+ if (args[argidx] == "-nosva") {
769
+ mode_nosva = true;
770
+ continue;
771
+ }
772
+ if (args[argidx] == "-sva-continue-on-err") {
773
+ mode_sva_continue = true;
774
+ continue;
775
+ }
776
+ if (args[argidx] == "-L" && argidx+1 < GetSize(args)) {
777
+ verific_sva_fsm_limit = atoi(args[++argidx].c_str());
778
+ continue;
779
+ }
780
+ if (args[argidx] == "-autocover") {
781
+ mode_autocover = true;
782
+ continue;
783
+ }
784
+ #endif
785
+ if (args[argidx] == "-n") {
786
+ mode_names = true;
787
+ continue;
788
+ }
789
+ if (args[argidx] == "-fullinit") {
790
+ mode_fullinit = true;
791
+ continue;
792
+ }
793
+ if (args[argidx] == "-cells") {
794
+ mode_cells = true;
795
+ continue;
796
+ }
797
+ if (args[argidx] == "-chparam" && argidx+2 < GetSize(args)) {
798
+ const std::string &key = args[++argidx];
799
+ const std::string &value = args[++argidx];
800
+ unsigned new_insertion = parameters.Insert(key.c_str(), value.c_str(),
801
+ 1 /* force_overwrite */);
802
+ if (!new_insertion)
803
+ log_warning_noprefix("-chparam %s already specified: overwriting.\n", key);
804
+ continue;
805
+ }
806
+ if (args[argidx] == "-V") {
807
+ mode_verific = true;
808
+ continue;
809
+ }
810
+ if (args[argidx] == "-v") {
811
+ verific_verbose = 1;
812
+ continue;
813
+ }
814
+ if (args[argidx] == "-vv") {
815
+ verific_verbose = 2;
816
+ continue;
817
+ }
818
+ if (args[argidx] == "-d" && argidx+1 < GetSize(args)) {
819
+ dumpfile = args[++argidx];
820
+ continue;
821
+ }
822
+ if (args[argidx] == "-pp" && argidx+1 < GetSize(args)) {
823
+ ppfile = args[++argidx];
824
+ continue;
825
+ }
826
+ break;
827
+ }
828
+
829
+ if (argidx > GetSize(args) && args[argidx].compare(0, 1, "-") == 0)
830
+ pass.cmd_error(args, argidx, "unknown option");
831
+
832
+ if ((unsigned long)verific_sva_fsm_limit >= sizeof(1ull)*8)
833
+ log_cmd_error("-L %d: limit too large; maximum allowed value is %zu.\n", verific_sva_fsm_limit, sizeof(1ull)*8-1);
834
+
835
+ if (already_imported)
836
+ log_warning("Note that all Verific flags were reset to defaults after last -import.\n");
837
+
838
+ std::set<std::string> top_mod_names;
839
+
840
+ if (mode_all)
841
+ {
842
+ import_all(work.c_str(), &nl_todo, &parameters, true, ppfile);
843
+ }
844
+ else
845
+ {
846
+ if (argidx == GetSize(args))
847
+ pass.cmd_error(args, argidx, "No top module specified.\n");
848
+
849
+ std::vector<std::string> tops;
850
+ for (int i = argidx; i < GetSize(args); i++)
851
+ tops.push_back(args[i].c_str());
852
+ top_mod_names = import_tops(work.c_str(), &nl_todo, &parameters, true, ppfile, tops) ;
853
+ }
854
+ if (mode_cells) {
855
+ log("Importing all cells.\n");
856
+ Libset *gls = Libset::Global() ;
857
+ MapIter it ;
858
+ Library *l ;
859
+ FOREACH_LIBRARY_OF_LIBSET(gls,it,l) {
860
+ MapIter mi ;
861
+ Verific::Cell *c ;
862
+ FOREACH_CELL_OF_LIBRARY(l,mi,c) {
863
+ if (!mode_verific && (l == Library::Primitives() || l == Library::Operators())) continue;
864
+ MapIter ni ;
865
+ if (c->NumOfNetlists() == 1) {
866
+ c->GetFirstNetlist()->SetName("");
867
+ }
868
+ Netlist *nl;
869
+ FOREACH_NETLIST_OF_CELL(c, ni, nl) {
870
+ if (nl)
871
+ nl_todo.emplace(nl->CellBaseName(), nl);
872
+ }
873
+ }
874
+ }
875
+ }
876
+
877
+ if (!verific_error_msg.empty())
878
+ return;
879
+
880
+ if (flatten) {
881
+ for (auto nl : nl_todo)
882
+ nl.second->Flatten();
883
+ }
884
+
885
+ if (extnets)
886
+ verific_extnets(nl_todo);
887
+
888
+ if (split_complex_ports) {
889
+ for (auto nl : nl_todo)
890
+ nl.second->ChangePortBusStructures(1 /* hierarchical */);
891
+ }
892
+
893
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
894
+ if (!dumpfile.empty()) {
895
+ VeriWrite veri_writer;
896
+ veri_writer.WriteFile(dumpfile.c_str(), Netlist::PresentDesign());
897
+ }
898
+ #endif
899
+ while (!nl_todo.empty()) {
900
+ auto it = nl_todo.begin();
901
+ Netlist *nl = it->second;
902
+ if (nl_done.count(it->first) == 0) {
903
+ VerificImporter importer(mode_gates, mode_keep, mode_nosva, mode_sva_continue,
904
+ mode_names, mode_verific, mode_autocover, mode_fullinit);
905
+ nl_done[it->first] = it->second;
906
+ importer.import_netlist(design, nl, nl_todo, top_mod_names.count(nl->CellBaseName()));
907
+ }
908
+ nl_todo.erase(it);
909
+ }
910
+
911
+ already_imported = true;
912
+ }
913
+
914
+ void VerificCommand::configure()
915
+ {
916
+ if (argidx+1 == GetSize(args)) {
917
+ MapIter mi;
918
+ const char *k, *s;
919
+ unsigned long v;
920
+ pool<std::string> lines;
921
+ FOREACH_MAP_ITEM(RuntimeFlags::GetVarMap(), mi, &k, &v) {
922
+ lines.insert(stringf("%s %lu", k, v));
923
+ }
924
+ FOREACH_MAP_ITEM(RuntimeFlags::GetStringVarMap(), mi, &k, &s) {
925
+ if (s == nullptr)
926
+ lines.insert(stringf("%s NULL", k));
927
+ else
928
+ lines.insert(stringf("%s \"%s\"", k, s));
929
+ }
930
+ lines.sort();
931
+ for (auto &line : lines)
932
+ log("verific -cfg %s\n", line);
933
+ return;
934
+ }
935
+
936
+ if (argidx+2 == GetSize(args)) {
937
+ const char *k = args[argidx+1].c_str();
938
+ if (RuntimeFlags::HasUnsignedVar(k)) {
939
+ log("verific -cfg %s %lu\n", k, RuntimeFlags::GetVar(k));
940
+ return;
941
+ }
942
+ if (RuntimeFlags::HasStringVar(k)) {
943
+ const char *s = RuntimeFlags::GetStringVar(k);
944
+ if (s == nullptr)
945
+ log("verific -cfg %s NULL\n", k);
946
+ else
947
+ log("verific -cfg %s \"%s\"\n", k, s);
948
+ return;
949
+ }
950
+ log_cmd_error("Can't find Verific Runtime flag '%s'.\n", k);
951
+ }
952
+
953
+ if (argidx+3 == GetSize(args)) {
954
+ const auto &k = args[argidx+1], &v = args[argidx+2];
955
+ if (v == "NULL") {
956
+ RuntimeFlags::SetStringVar(k.c_str(), nullptr);
957
+ return;
958
+ }
959
+ if (v[0] == '"') {
960
+ std::string s = v.substr(1, GetSize(v)-2);
961
+ RuntimeFlags::SetStringVar(k.c_str(), s.c_str());
962
+ return;
963
+ }
964
+ char *endptr;
965
+ unsigned long n = strtol(v.c_str(), &endptr, 0);
966
+ if (*endptr == 0) {
967
+ RuntimeFlags::SetVar(k.c_str(), n);
968
+ return;
969
+ }
970
+ }
971
+
972
+ run_extension();
973
+ }
974
+
975
+ void VerificCommand::run_extension()
976
+ {
977
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
978
+ if (VerificExtensions::Execute(args, argidx, work,
979
+ [this](const std::vector<std::string> &args, size_t argidx, std::string msg)
980
+ { pass.cmd_error(args, argidx, msg); } ))
981
+ return;
982
+ #endif
983
+ pass.cmd_error(args, argidx, "Missing or unsupported mode parameter.\n");
984
+ }
985
+
986
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verific/verific_command.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef VERIFIC_COMMAND_H
21
+ #define VERIFIC_COMMAND_H
22
+
23
+ #ifdef YOSYS_ENABLE_VERIFIC
24
+
25
+ #include "kernel/register.h"
26
+ #include "frontends/verific/verific.h"
27
+
28
+ YOSYS_NAMESPACE_BEGIN
29
+
30
+ struct VerificCommand {
31
+ Pass &pass;
32
+ std::vector<std::string> &args;
33
+ RTLIL::Design *design;
34
+ int argidx = 1;
35
+ std::string mode = {};
36
+ std::string work = "work";
37
+ bool is_work_set = false;
38
+ std::vector<std::string> search_libraries = {};
39
+ std::vector<std::string> tmp_files = {};
40
+
41
+ VerificCommand(Pass &pass, std::vector<std::string> &args, RTLIL::Design *design);
42
+ ~VerificCommand();
43
+ void run();
44
+ static void reset_settings();
45
+
46
+ private:
47
+ struct VerilogStandard;
48
+ struct VhdlStandard;
49
+ static const VerilogStandard *find_verilog_standard(const std::string &flag);
50
+ static const VhdlStandard *find_vhdl_standard(const std::string &flag);
51
+
52
+ std::string frontend_rewrite();
53
+ void append_remaining_args(std::vector<std::string> &list);
54
+ void apply_library_options();
55
+ bool change_setting();
56
+
57
+ void set_msg_type();
58
+ void define_macros();
59
+ void undefine_macros();
60
+ void read_target();
61
+ void read_f_file();
62
+ void read_verilog(const VerilogStandard &standard);
63
+ void read_vhdl(const VhdlStandard &standard);
64
+ void read_edif();
65
+ void read_liberty();
66
+ void pretty_print();
67
+ void import_design();
68
+ void configure();
69
+ void run_extension();
70
+ };
71
+
72
+ YOSYS_NAMESPACE_END
73
+
74
+ #endif
75
+ #endif
chips/yosys/frontends/verific/verific_extnets.cc ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+
22
+ #include "frontends/verific/verific.h"
23
+
24
+ #ifdef VERIFIC_NAMESPACE
25
+ using namespace Verific;
26
+ #endif
27
+
28
+ YOSYS_NAMESPACE_BEGIN
29
+
30
+ struct VerificExtNets
31
+ {
32
+ int portname_cnt = 0;
33
+
34
+ // a map from Net to the same Net one level up in the design hierarchy
35
+ std::map<Net*, Net*> net_level_up_drive_up;
36
+ std::map<Net*, Net*> net_level_up_drive_down;
37
+
38
+ Net *route_up(Net *net, bool drive_up, Net *final_net = nullptr)
39
+ {
40
+ auto &net_level_up = drive_up ? net_level_up_drive_up : net_level_up_drive_down;
41
+
42
+ if (net_level_up.count(net) == 0)
43
+ {
44
+ Netlist *nl = net->Owner();
45
+
46
+ // Simply return if Netlist is not unique
47
+ log_assert(nl->NumOfRefs() == 1);
48
+
49
+ Instance *up_inst = (Instance*)nl->GetReferences()->GetLast();
50
+ Netlist *up_nl = up_inst->Owner();
51
+
52
+ // create new Port
53
+ string name = stringf("___extnets_%d", portname_cnt++);
54
+ Port *new_port = new Port(name.c_str(), drive_up ? DIR_OUT : DIR_IN);
55
+ nl->Add(new_port);
56
+ nl->Buf(net)->Connect(new_port);
57
+
58
+ // create new Net in up Netlist
59
+ Net *new_net = final_net;
60
+ if (new_net == nullptr || new_net->Owner() != up_nl) {
61
+ new_net = new Net(name.c_str());
62
+ up_nl->Add(new_net);
63
+ }
64
+ up_inst->Connect(new_port, new_net);
65
+
66
+ net_level_up[net] = new_net;
67
+ }
68
+
69
+ return net_level_up.at(net);
70
+ }
71
+
72
+ Net *route_up(Net *net, bool drive_up, Netlist *dest, Net *final_net = nullptr)
73
+ {
74
+ while (net->Owner() != dest)
75
+ net = route_up(net, drive_up, final_net);
76
+ if (final_net != nullptr)
77
+ log_assert(net == final_net);
78
+ return net;
79
+ }
80
+
81
+ Netlist *find_common_ancestor(Netlist *A, Netlist *B)
82
+ {
83
+ std::set<Netlist*> ancestors_of_A;
84
+
85
+ Netlist *cursor = A;
86
+ while (1) {
87
+ ancestors_of_A.insert(cursor);
88
+ if (cursor->NumOfRefs() != 1)
89
+ break;
90
+ cursor = ((Instance*)cursor->GetReferences()->GetLast())->Owner();
91
+ }
92
+
93
+ cursor = B;
94
+ while (1) {
95
+ if (ancestors_of_A.count(cursor))
96
+ return cursor;
97
+ if (cursor->NumOfRefs() != 1)
98
+ break;
99
+ cursor = ((Instance*)cursor->GetReferences()->GetLast())->Owner();
100
+ }
101
+
102
+ log_error("No common ancestor found between %s and %s.\n", get_full_netlist_name(A), get_full_netlist_name(B));
103
+ }
104
+
105
+ void run(Netlist *nl)
106
+ {
107
+ MapIter mi, mi2;
108
+ Instance *inst;
109
+ PortRef *pr;
110
+
111
+ vector<tuple<Instance*, Port*, Net*>> todo_connect;
112
+
113
+ FOREACH_INSTANCE_OF_NETLIST(nl, mi, inst)
114
+ run(inst->View());
115
+
116
+ FOREACH_INSTANCE_OF_NETLIST(nl, mi, inst)
117
+ FOREACH_PORTREF_OF_INST(inst, mi2, pr)
118
+ {
119
+ Port *port = pr->GetPort();
120
+ Net *net = pr->GetNet();
121
+
122
+ if (!net->IsExternalTo(nl))
123
+ continue;
124
+
125
+ if (verific_verbose)
126
+ log("Fixing external net reference on port %s.%s.%s:\n", get_full_netlist_name(nl), inst->Name(), port->Name());
127
+
128
+ Netlist *ext_nl = net->Owner();
129
+
130
+ if (verific_verbose)
131
+ log(" external net owner: %s\n", get_full_netlist_name(ext_nl));
132
+
133
+ Netlist *ca_nl = find_common_ancestor(nl, ext_nl);
134
+
135
+ if (verific_verbose)
136
+ log(" common ancestor: %s\n", get_full_netlist_name(ca_nl));
137
+
138
+ Net *ca_net = route_up(net, !port->IsOutput(), ca_nl);
139
+ Net *new_net = ca_net;
140
+
141
+ if (ca_nl != nl)
142
+ {
143
+ if (verific_verbose)
144
+ log(" net in common ancestor: %s\n", ca_net->Name());
145
+
146
+ string name = stringf("___extnets_%d", portname_cnt++);
147
+ new_net = new Net(name.c_str());
148
+ nl->Add(new_net);
149
+
150
+ Net *n = route_up(new_net, port->IsOutput(), ca_nl, ca_net);
151
+ log_assert(n == ca_net);
152
+ }
153
+
154
+ if (verific_verbose)
155
+ log(" new local net: %s\n", new_net->Name());
156
+
157
+ log_assert(!new_net->IsExternalTo(nl));
158
+ todo_connect.push_back(tuple<Instance*, Port*, Net*>(inst, port, new_net));
159
+ }
160
+
161
+ for (auto it : todo_connect) {
162
+ get<0>(it)->Disconnect(get<1>(it));
163
+ get<0>(it)->Connect(get<1>(it), get<2>(it));
164
+ }
165
+ }
166
+ };
167
+
168
+ void verific_extnets(const std::map<std::string,Netlist*> &nl_todo)
169
+ {
170
+ VerificExtNets worker;
171
+ for (auto nl : nl_todo)
172
+ worker.run(nl.second);
173
+ }
174
+
175
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verific/verific_importer.cc ADDED
@@ -0,0 +1,2260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+ #include "kernel/sigtools.h"
22
+ #include "kernel/celltypes.h"
23
+ #include "kernel/log.h"
24
+ #include "kernel/utils.h"
25
+ #include "libs/sha1/sha1.h"
26
+
27
+ #include "frontends/verific/verific.h"
28
+
29
+ #ifdef __clang__
30
+ #pragma clang diagnostic push
31
+ #pragma clang diagnostic ignored "-Woverloaded-virtual"
32
+ #endif
33
+
34
+ #include "Array.h"
35
+
36
+ #ifdef VERIFIC_VHDL_SUPPORT
37
+ #include "NameSpace.h"
38
+ #endif
39
+
40
+ #ifdef __clang__
41
+ #pragma clang diagnostic pop
42
+ #endif
43
+
44
+ #ifdef VERIFIC_NAMESPACE
45
+ using namespace Verific;
46
+ #endif
47
+
48
+ YOSYS_NAMESPACE_BEGIN
49
+
50
+ static std::string format_src_location(DesignObj *obj)
51
+ {
52
+ if (obj == nullptr || !obj->Linefile())
53
+ return std::string();
54
+ #ifdef VERIFIC_LINEFILE_INCLUDES_COLUMNS
55
+ return stringf("%s:%d.%d-%d.%d", LineFile::GetFileName(obj->Linefile()), obj->Linefile()->GetLeftLine(), obj->Linefile()->GetLeftCol(), obj->Linefile()->GetRightLine(), obj->Linefile()->GetRightCol());
56
+ #else
57
+ return stringf("%s:%d", LineFile::GetFileName(obj->Linefile()), LineFile::GetLineNo(obj->Linefile()));
58
+ #endif
59
+ }
60
+
61
+ static std::string announce_src_location(DesignObj *obj)
62
+ {
63
+ std::string loc = format_src_location(obj);
64
+ if (loc.empty())
65
+ return std::string();
66
+ return loc + ": ";
67
+ }
68
+
69
+ VerificImporter::VerificImporter(bool mode_gates, bool mode_keep, bool mode_nosva, bool mode_sva_continue, bool mode_names, bool mode_verific, bool mode_autocover, bool mode_fullinit) :
70
+ mode_gates(mode_gates), mode_keep(mode_keep), mode_nosva(mode_nosva), mode_sva_continue(mode_sva_continue),
71
+ mode_names(mode_names), mode_verific(mode_verific), mode_autocover(mode_autocover),
72
+ mode_fullinit(mode_fullinit)
73
+ {
74
+ }
75
+
76
+ RTLIL::SigBit VerificImporter::net_map_at(Net *net)
77
+ {
78
+ if (net->IsExternalTo(netlist))
79
+ log_error("Found external reference to '%s.%s' in netlist '%s', please use -flatten or -extnets.\n",
80
+ get_full_netlist_name(net->Owner()), net->Name(), get_full_netlist_name(netlist));
81
+
82
+ return net_map.at(net);
83
+ }
84
+
85
+ static bool is_blackbox(Netlist *nl)
86
+ {
87
+ if (nl->IsBlackBox() || nl->IsEmptyBox())
88
+ return true;
89
+
90
+ const char *attr = nl->GetAttValue("blackbox");
91
+ if (attr != nullptr && strcmp(attr, "0"))
92
+ return true;
93
+
94
+ return false;
95
+ }
96
+
97
+ RTLIL::IdString VerificImporter::new_verific_id(Verific::DesignObj *obj)
98
+ {
99
+ std::string s = stringf("$verific$%s", obj->Name());
100
+ if (obj->Linefile())
101
+ s += stringf("$%s:%d", RTLIL::encode_filename(Verific::LineFile::GetFileName(obj->Linefile())), Verific::LineFile::GetLineNo(obj->Linefile()));
102
+ s += stringf("$%d", module->twines().next_autoidx());
103
+ return module->twines().add(std::move(s));
104
+ }
105
+
106
+ static const RTLIL::Const extract_vhdl_boolean(std::string &val)
107
+ {
108
+ if (val == "false")
109
+ return RTLIL::Const::from_string("0");
110
+ if (val == "true")
111
+ return RTLIL::Const::from_string("1");
112
+ log_error("Expecting VHDL boolean value.\n");
113
+ }
114
+
115
+ static const RTLIL::Const extract_vhdl_bit(std::string &val, std::string &typ)
116
+ {
117
+ if (val.size()==3 && val[0]=='\'' && val.back()=='\'')
118
+ return RTLIL::Const::from_string(val.substr(1,val.size()-2));
119
+ log_error("Error parsing VHDL %s.\n", typ);
120
+ }
121
+
122
+ static const RTLIL::Const extract_vhdl_bit_vector(std::string &val, std::string &typ)
123
+ {
124
+ if (val.size()>1 && val[0]=='\"' && val.back()=='\"') {
125
+ RTLIL::Const c = RTLIL::Const::from_string(val.substr(1,val.size()-2));
126
+ if (typ == "signed")
127
+ c.flags |= RTLIL::CONST_FLAG_SIGNED;
128
+ return c;
129
+ }
130
+ log_error("Error parsing VHDL %s.\n", typ);
131
+ }
132
+
133
+ static const RTLIL::Const extract_vhdl_integer(std::string &val)
134
+ {
135
+ char *end;
136
+ return RTLIL::Const((int)std::strtol(val.c_str(), &end, 10));
137
+ }
138
+
139
+ static const RTLIL::Const extract_vhdl_char(std::string &val)
140
+ {
141
+ if (val.size()==3 && val[0]=='\"' && val.back()=='\"')
142
+ return RTLIL::Const((int)val[1]);
143
+ log_error("Error parsing VHDL character.\n");
144
+ }
145
+
146
+ static const RTLIL::Const extract_real_value(std::string &val)
147
+ {
148
+ RTLIL::Const c(val);
149
+ c.flags |= RTLIL::CONST_FLAG_REAL;
150
+ return c;
151
+ }
152
+
153
+ static const RTLIL::Const extract_vhdl_string(std::string &val)
154
+ {
155
+ if (!(val.size()>1 && val[0]=='\"' && val.back()=='\"'))
156
+ log_error("Error parsing VHDL string.\n");
157
+ return RTLIL::Const(val.substr(1,val.size()-2));
158
+ }
159
+
160
+ static const RTLIL::Const extract_vhdl_const(const char *value, bool output_signed)
161
+ {
162
+ RTLIL::Const c;
163
+ char *end;
164
+ int decimal;
165
+ bool is_signed = false;
166
+ std::string val = std::string(value);
167
+
168
+ if (val.size()>1 && val[0]=='\"' && val.back()=='\"') {
169
+ std::string data = val.substr(1,val.size()-2);
170
+ bool isBinary = std::all_of(data.begin(), data.end(), [](char c) {return c=='1' || c=='0'; });
171
+ if (isBinary)
172
+ c = RTLIL::Const::from_string(data);
173
+ else
174
+ c = RTLIL::Const(data);
175
+ } else if (val.size()==3 && val[0]=='\'' && val.back()=='\'') {
176
+ c = RTLIL::Const::from_string(val.substr(1,val.size()-2));
177
+ } else if ((value[0] == '-' || (value[0] >= '0' && value[0] <= '9')) &&
178
+ ((decimal = std::strtol(value, &end, 10)), !end[0])) {
179
+ is_signed = output_signed;
180
+ c = RTLIL::Const((int)decimal);
181
+ } else if (val == "false") {
182
+ c = RTLIL::Const::from_string("0");
183
+ } else if (val == "true") {
184
+ c = RTLIL::Const::from_string("1");
185
+ } else {
186
+ c = RTLIL::Const(val);
187
+ log_warning("encoding value '%s' as string.\n", value);
188
+ }
189
+ if (is_signed)
190
+ c.flags |= RTLIL::CONST_FLAG_SIGNED;
191
+ return c;
192
+ }
193
+
194
+ static const RTLIL::Const extract_verilog_const(const char *value, bool allow_string, bool output_signed)
195
+ {
196
+ RTLIL::Const c;
197
+ char *end;
198
+ int decimal;
199
+ bool is_signed = false;
200
+ size_t found;
201
+ std::string val = std::string(value);
202
+
203
+ if (allow_string && val.size()>1 && val[0]=='\"' && val.back()=='\"') {
204
+ c = RTLIL::Const(val.substr(1,val.size()-2));
205
+ } else if ((found = val.find("'sb")) != std::string::npos) {
206
+ is_signed = output_signed;
207
+ c = RTLIL::Const::from_string(val.substr(found + 3));
208
+ } else if ((found = val.find("'b")) != std::string::npos) {
209
+ c = RTLIL::Const::from_string(val.substr(found + 2));
210
+ } else if ((value[0] == '-' || (value[0] >= '0' && value[0] <= '9')) &&
211
+ ((decimal = std::strtol(value, &end, 10)), !end[0])) {
212
+ is_signed = output_signed;
213
+ c = RTLIL::Const((int)decimal);
214
+ } else if (allow_string) {
215
+ c = RTLIL::Const(val);
216
+ } else {
217
+ c = RTLIL::Const(val);
218
+ log_warning("encoding value '%s' as string.\n", value);
219
+ }
220
+ if (is_signed)
221
+ c.flags |= RTLIL::CONST_FLAG_SIGNED;
222
+ return c;
223
+ }
224
+
225
+ // When used as attributes or parameter values Verific constants come already processed.
226
+ // - Real string values are already under quotes
227
+ // - Numeric values with specified width are always converted to binary
228
+ // - Rest of user defined values are handled as 32bit integers
229
+ // - There could be some internal values that are strings without quotes
230
+ // so we check if value is all digits or not
231
+ //
232
+ // Note: For signed values, verific uses <len>'sb<bits> and decimal values can
233
+ // also be negative.
234
+ static const RTLIL::Const verific_const(const char* type_name, const char *value, DesignObj *obj, bool allow_string = true, bool output_signed = false)
235
+ {
236
+ std::string val = std::string(value);
237
+ // VHDL
238
+ if (obj->IsFromVhdl()) {
239
+ if (type_name) {
240
+ std::string typ = std::string(type_name);
241
+ transform(typ.begin(), typ.end(), typ.begin(), ::tolower);
242
+ if (typ == "integer" || typ == "natural" || typ=="positive") return extract_vhdl_integer(val);
243
+ else if (typ =="boolean") return extract_vhdl_boolean(val);
244
+ else if (typ == "bit" || typ =="std_logic" || typ == "std_ulogic") return extract_vhdl_bit(val,typ);
245
+ else if (typ == "character") return extract_vhdl_char(val);
246
+ else if (typ == "bit_vector" || typ == "std_logic_vector" || typ == "std_ulogic_vector" ||
247
+ typ == "unsigned" || typ == "signed") return extract_vhdl_bit_vector(val,typ);
248
+ else if (typ == "real") return extract_real_value(val);
249
+ else if (typ == "string") return extract_vhdl_string(val);
250
+ else {
251
+ if (val.size()>1 && val[0]=='\"' && val.back()=='\"')
252
+ return RTLIL::Const(val.substr(1,val.size()-2));
253
+ else if (val.size()==3 && val[0]=='\'' && val.back()=='\'')
254
+ return RTLIL::Const(val.substr(1,val.size()-2));
255
+ else
256
+ return RTLIL::Const(val);
257
+ }
258
+ } else
259
+ return extract_vhdl_const(value, output_signed);
260
+ }
261
+ // SystemVerilog
262
+ if (type_name && strcmp(type_name, "real")==0) {
263
+ return extract_real_value(val);
264
+ } else
265
+ return extract_verilog_const(value, allow_string, output_signed);
266
+ }
267
+
268
+ #ifdef YOSYSHQ_VERIFIC_API_VERSION
269
+ static const std::string verific_unescape(const char *value)
270
+ {
271
+ std::string val = std::string(value);
272
+ if (val.size()>1 && val[0]=='\"' && val.back()=='\"')
273
+ return val.substr(1,val.size()-2);
274
+ return value;
275
+ }
276
+ #endif
277
+
278
+ void VerificImporter::import_attributes(dict<RTLIL::IdString, RTLIL::Const> &attributes, DesignObj *obj, Netlist *nl, int wire_width_hint)
279
+ {
280
+ if (!obj)
281
+ return;
282
+
283
+ MapIter mi;
284
+ Att *attr;
285
+
286
+ if (obj->Linefile())
287
+ attributes[ID::src] = format_src_location(obj);
288
+
289
+ FOREACH_ATTRIBUTE(obj, mi, attr) {
290
+ if (attr->Key()[0] == ' ' || attr->Value() == nullptr)
291
+ continue;
292
+ attributes[module->twines().add(RTLIL::escape_id(attr->Key()))] = verific_const(nullptr, attr->Value(), obj);
293
+ }
294
+
295
+ if (nl) {
296
+ auto type_range = nl->GetTypeRange(obj->Name());
297
+ if (!type_range)
298
+ return;
299
+ if (nl->IsFromVhdl() && type_range->IsTypeScalar()) {
300
+ const long long bottom_bound = type_range->GetScalarRangeLeftBound();
301
+ const long long top_bound = type_range->GetScalarRangeRightBound();
302
+ int bit_width = type_range->LeftRangeBound()+1;
303
+ if (bit_width <= 0) { // VHDL null range
304
+ if (wire_width_hint >= 0)
305
+ bit_width = wire_width_hint;
306
+ else
307
+ bit_width = 64; //fallback, currently largest integer width that verific will allow (in vhdl2019 mode)
308
+ } else {
309
+ if (wire_width_hint >= 0) log_assert(bit_width == wire_width_hint);
310
+ }
311
+ RTLIL::Const bottom_const(bottom_bound, bit_width);
312
+ RTLIL::Const top_const(top_bound, bit_width);
313
+ if (bottom_bound < 0 || top_bound < 0) {
314
+ bottom_const.flags |= RTLIL::CONST_FLAG_SIGNED;
315
+ top_const.flags |= RTLIL::CONST_FLAG_SIGNED;
316
+ }
317
+ attributes.emplace(ID(bottom_bound), bottom_const);
318
+ attributes.emplace(ID(top_bound), top_const);
319
+ }
320
+ if (!type_range->IsTypeEnum())
321
+ return;
322
+ #ifdef VERIFIC_VHDL_SUPPORT
323
+ if (nl->IsFromVhdl() && strcmp(type_range->GetTypeName(), "STD_LOGIC") == 0)
324
+ return;
325
+ #endif
326
+ auto type_name = type_range->GetTypeName();
327
+ if (!type_name)
328
+ return;
329
+ attributes.emplace(ID::wiretype, RTLIL::escape_id(type_name));
330
+
331
+ MapIter mi;
332
+ const char *k, *v;
333
+ FOREACH_MAP_ITEM(type_range->GetEnumIdMap(), mi, &k, &v) {
334
+ if (nl->IsFromVerilog()) {
335
+ auto const value = verific_const(type_name, v, nl, false);
336
+
337
+ attributes.emplace(module->twines().add(stringf("\\enum_value_%s", value.as_string())), RTLIL::escape_id(k));
338
+ }
339
+ #ifdef VERIFIC_VHDL_SUPPORT
340
+ else if (nl->IsFromVhdl()) {
341
+ // Expect "<binary>" or plain <binary>
342
+ auto p = v;
343
+ if (p) {
344
+ if (*p != '"') {
345
+ auto l = strlen(p);
346
+ auto q = (char*)malloc(l+1);
347
+ strncpy(q, p, l);
348
+ q[l] = '\0';
349
+ for(char *ptr = q; *ptr; ++ptr )*ptr = tolower(*ptr);
350
+ attributes.emplace(module->twines().add(stringf("\\enum_value_%s", q)), RTLIL::escape_id(k));
351
+ } else {
352
+ auto *q = p+1;
353
+ for (; *q != '"'; q++)
354
+ if (*q != '0' && *q != '1') {
355
+ p = nullptr;
356
+ break;
357
+ }
358
+ if (p && *(q+1) != '\0')
359
+ p = nullptr;
360
+
361
+ if (p != nullptr)
362
+ {
363
+ auto l = strlen(p);
364
+ auto q = (char*)malloc(l+1-2);
365
+ strncpy(q, p+1, l-2);
366
+ q[l-2] = '\0';
367
+ attributes.emplace(module->twines().add(stringf("\\enum_value_%s", q)), RTLIL::escape_id(k));
368
+ free(q);
369
+ }
370
+ }
371
+ }
372
+ if (p == nullptr)
373
+ log_error("%sExpected TypeRange value '%s' to be of form \"<binary>\" or <binary>.\n", announce_src_location(obj), v);
374
+ }
375
+ #endif
376
+ }
377
+ }
378
+ }
379
+
380
+ RTLIL::SigBit VerificImporter::netToSigBit(Verific::Net *net) {
381
+ if (net && net->IsGnd())
382
+ return RTLIL::State::S0;
383
+ else if (net && net->IsPwr())
384
+ return RTLIL::State::S1;
385
+ else if (net && net->IsX())
386
+ return RTLIL::State::Sx;
387
+ else if (net)
388
+ return net_map_at(net);
389
+ else
390
+ return RTLIL::State::Sz;
391
+ }
392
+
393
+ RTLIL::SigSpec VerificImporter::operatorInput(Instance *inst)
394
+ {
395
+ RTLIL::SigSpec sig;
396
+ for (int i = int(inst->InputSize())-1; i >= 0; i--) {
397
+ Net *net = inst->GetInputBit(i);
398
+ sig.append(netToSigBit(net));
399
+ }
400
+ return sig;
401
+ }
402
+
403
+ RTLIL::SigSpec VerificImporter::operatorInput1(Instance *inst)
404
+ {
405
+ RTLIL::SigSpec sig;
406
+ for (int i = int(inst->Input1Size())-1; i >= 0; i--) {
407
+ Net *net = inst->GetInput1Bit(i);
408
+ sig.append(netToSigBit(net));
409
+ }
410
+ return sig;
411
+ }
412
+
413
+ RTLIL::SigSpec VerificImporter::operatorInput2(Instance *inst)
414
+ {
415
+ RTLIL::SigSpec sig;
416
+ for (int i = int(inst->Input2Size())-1; i >= 0; i--) {
417
+ Net *net = inst->GetInput2Bit(i);
418
+ sig.append(netToSigBit(net));
419
+ }
420
+ return sig;
421
+ }
422
+
423
+ RTLIL::SigSpec VerificImporter::operatorInport(Instance *inst, const char *portname)
424
+ {
425
+ PortBus *portbus = inst->View()->GetPortBus(portname);
426
+ if (portbus) {
427
+ RTLIL::SigSpec sig;
428
+ for (unsigned i = 0; i < portbus->Size(); i++) {
429
+ Net *net = inst->GetNet(portbus->ElementAtIndex(i));
430
+ if (net) {
431
+ if (net->IsConstant()) {
432
+ if (net->IsGnd())
433
+ sig.append(RTLIL::State::S0);
434
+ else if (net->IsPwr())
435
+ sig.append(RTLIL::State::S1);
436
+ else if (net->IsX())
437
+ sig.append(RTLIL::State::Sx);
438
+ else
439
+ sig.append(RTLIL::State::Sz);
440
+ }
441
+ else
442
+ sig.append(net_map_at(net));
443
+ } else
444
+ sig.append(RTLIL::State::Sz);
445
+ }
446
+ return sig;
447
+ } else {
448
+ Port *port = inst->View()->GetPort(portname);
449
+ log_assert(port != NULL);
450
+ Net *net = inst->GetNet(port);
451
+ return net_map_at(net);
452
+ }
453
+ }
454
+
455
+ RTLIL::SigSpec VerificImporter::operatorInportCase(Instance *inst, const char *portname)
456
+ {
457
+ PortBus *portbus = inst->View()->GetPortBus(portname);
458
+ if (portbus) {
459
+ RTLIL::SigSpec sig;
460
+ for (unsigned i = 0; i < portbus->Size(); i++) {
461
+ Net *net = inst->GetNet(portbus->ElementAtIndex(i));
462
+ if (net) {
463
+ if (net->IsConstant()) {
464
+ if (net->IsGnd())
465
+ sig.append(RTLIL::State::S0);
466
+ else if (net->IsPwr())
467
+ sig.append(RTLIL::State::S1);
468
+ else
469
+ sig.append(RTLIL::State::Sa);
470
+ }
471
+ else
472
+ sig.append(net_map_at(net));
473
+ } else
474
+ sig.append(RTLIL::State::Sa);
475
+ }
476
+ return sig;
477
+ } else {
478
+ Port *port = inst->View()->GetPort(portname);
479
+ log_assert(port != NULL);
480
+ Net *net = inst->GetNet(port);
481
+ return net_map_at(net);
482
+ }
483
+ }
484
+
485
+ RTLIL::SigSpec VerificImporter::operatorOutput(Instance *inst, const pool<Net*> *any_all_nets)
486
+ {
487
+ RTLIL::SigSpec sig;
488
+ RTLIL::Wire *dummy_wire = NULL;
489
+ for (int i = int(inst->OutputSize())-1; i >= 0; i--)
490
+ if (inst->GetOutputBit(i) && (!any_all_nets || !any_all_nets->count(inst->GetOutputBit(i)))) {
491
+ sig.append(net_map_at(inst->GetOutputBit(i)));
492
+ dummy_wire = NULL;
493
+ } else {
494
+ if (dummy_wire == NULL)
495
+ dummy_wire = module->addWire(new_verific_id(inst));
496
+ else
497
+ dummy_wire->width++;
498
+ sig.append(RTLIL::SigSpec(dummy_wire, dummy_wire->width - 1));
499
+ }
500
+ return sig;
501
+ }
502
+
503
+ bool VerificImporter::import_netlist_instance_gates(Instance *inst, RTLIL::IdString inst_name)
504
+ {
505
+ if (inst->Type() == PRIM_AND) {
506
+ module->addAndGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
507
+ return true;
508
+ }
509
+
510
+ if (inst->Type() == PRIM_NAND) {
511
+ RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst));
512
+ module->addAndGate(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp);
513
+ module->addNotGate(inst_name, tmp, net_map_at(inst->GetOutput()));
514
+ return true;
515
+ }
516
+
517
+ if (inst->Type() == PRIM_OR) {
518
+ module->addOrGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
519
+ return true;
520
+ }
521
+
522
+ if (inst->Type() == PRIM_NOR) {
523
+ RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst));
524
+ module->addOrGate(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp);
525
+ module->addNotGate(inst_name, tmp, net_map_at(inst->GetOutput()));
526
+ return true;
527
+ }
528
+
529
+ if (inst->Type() == PRIM_XOR) {
530
+ module->addXorGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
531
+ return true;
532
+ }
533
+
534
+ if (inst->Type() == PRIM_XNOR) {
535
+ module->addXnorGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
536
+ return true;
537
+ }
538
+
539
+ if (inst->Type() == PRIM_BUF) {
540
+ auto outnet = inst->GetOutput();
541
+ if (!any_all_nets.count(outnet))
542
+ module->addBufGate(inst_name, net_map_at(inst->GetInput()), net_map_at(outnet));
543
+ return true;
544
+ }
545
+
546
+ if (inst->Type() == PRIM_INV) {
547
+ module->addNotGate(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
548
+ return true;
549
+ }
550
+
551
+ if (inst->Type() == PRIM_MUX) {
552
+ module->addMuxGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput()));
553
+ return true;
554
+ }
555
+
556
+ if ((inst->Type() == PRIM_TRI) || (inst->Type() == PRIM_BUFIF1)) {
557
+ module->addMuxGate(inst_name, RTLIL::State::Sz, net_map_at(inst->GetInput()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput()));
558
+ return true;
559
+ }
560
+
561
+ if (inst->Type() == PRIM_FADD)
562
+ {
563
+ RTLIL::SigSpec a = net_map_at(inst->GetInput1()), b = net_map_at(inst->GetInput2()), c = net_map_at(inst->GetCin());
564
+ RTLIL::SigSpec x = inst->GetCout() ? net_map_at(inst->GetCout()) : module->addWire(new_verific_id(inst));
565
+ RTLIL::SigSpec y = inst->GetOutput() ? net_map_at(inst->GetOutput()) : module->addWire(new_verific_id(inst));
566
+ RTLIL::SigSpec tmp1 = module->addWire(new_verific_id(inst));
567
+ RTLIL::SigSpec tmp2 = module->addWire(new_verific_id(inst));
568
+ RTLIL::SigSpec tmp3 = module->addWire(new_verific_id(inst));
569
+ module->addXorGate(new_verific_id(inst), a, b, tmp1);
570
+ module->addXorGate(inst_name, tmp1, c, y);
571
+ module->addAndGate(new_verific_id(inst), tmp1, c, tmp2);
572
+ module->addAndGate(new_verific_id(inst), a, b, tmp3);
573
+ module->addOrGate(new_verific_id(inst), tmp2, tmp3, x);
574
+ return true;
575
+ }
576
+
577
+ if (inst->Type() == PRIM_DFFRS)
578
+ {
579
+ VerificClocking clocking(this, inst->GetClock());
580
+ log_assert(clocking.disable_sig == State::S0);
581
+ log_assert(clocking.body_net == nullptr);
582
+
583
+ if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd())
584
+ clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
585
+ else if (inst->GetSet()->IsGnd())
586
+ clocking.addAdff(inst_name, net_map_at(inst->GetReset()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), State::S0);
587
+ else if (inst->GetReset()->IsGnd())
588
+ clocking.addAdff(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), State::S1);
589
+ else
590
+ clocking.addDffsr(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetReset()),
591
+ net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
592
+ return true;
593
+ }
594
+
595
+ if (inst->Type() == PRIM_DLATCHRS)
596
+ {
597
+ if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd())
598
+ module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
599
+ else
600
+ module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetSet()), net_map_at(inst->GetReset()),
601
+ net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
602
+ return true;
603
+ }
604
+
605
+ if (inst->Type() == PRIM_DFF)
606
+ {
607
+ VerificClocking clocking(this, inst->GetClock());
608
+ log_assert(clocking.disable_sig == State::S0);
609
+ log_assert(clocking.body_net == nullptr);
610
+
611
+ if (inst->GetAsyncCond()->IsGnd())
612
+ clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
613
+ else
614
+ clocking.addAldff(inst_name, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal()),
615
+ net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
616
+ return true;
617
+ }
618
+
619
+ if (inst->Type() == PRIM_DLATCH)
620
+ {
621
+ if (inst->GetAsyncCond()->IsGnd()) {
622
+ module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
623
+ } else {
624
+ RTLIL::SigSpec sig_set = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal()));
625
+ RTLIL::SigSpec sig_clr = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), module->Not(NEW_ID, net_map_at(inst->GetAsyncVal())));
626
+ module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), sig_set, sig_clr, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
627
+ }
628
+ return true;
629
+ }
630
+
631
+ return false;
632
+ }
633
+
634
+ bool VerificImporter::import_netlist_instance_cells(Instance *inst, RTLIL::IdString inst_name)
635
+ {
636
+ RTLIL::Cell *cell = nullptr;
637
+
638
+ if (inst->Type() == PRIM_AND) {
639
+ cell = module->addAnd(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
640
+ import_attributes(cell->attributes, inst);
641
+ return true;
642
+ }
643
+
644
+ if (inst->Type() == PRIM_NAND) {
645
+ RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst));
646
+ cell = module->addAnd(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp);
647
+ import_attributes(cell->attributes, inst);
648
+ cell = module->addNot(inst_name, tmp, net_map_at(inst->GetOutput()));
649
+ import_attributes(cell->attributes, inst);
650
+ return true;
651
+ }
652
+
653
+ if (inst->Type() == PRIM_OR) {
654
+ cell = module->addOr(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
655
+ import_attributes(cell->attributes, inst);
656
+ return true;
657
+ }
658
+
659
+ if (inst->Type() == PRIM_NOR) {
660
+ RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst));
661
+ cell = module->addOr(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp);
662
+ import_attributes(cell->attributes, inst);
663
+ cell = module->addNot(inst_name, tmp, net_map_at(inst->GetOutput()));
664
+ import_attributes(cell->attributes, inst);
665
+ return true;
666
+ }
667
+
668
+ if (inst->Type() == PRIM_XOR) {
669
+ cell = module->addXor(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
670
+ import_attributes(cell->attributes, inst);
671
+ return true;
672
+ }
673
+
674
+ if (inst->Type() == PRIM_XNOR) {
675
+ cell = module->addXnor(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput()));
676
+ import_attributes(cell->attributes, inst);
677
+ return true;
678
+ }
679
+
680
+ if (inst->Type() == PRIM_INV) {
681
+ cell = module->addNot(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
682
+ import_attributes(cell->attributes, inst);
683
+ return true;
684
+ }
685
+
686
+ if (inst->Type() == PRIM_MUX) {
687
+ cell = module->addMux(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput()));
688
+ import_attributes(cell->attributes, inst);
689
+ return true;
690
+ }
691
+
692
+ if ((inst->Type() == PRIM_TRI) || (inst->Type() == PRIM_BUFIF1)) {
693
+ cell = module->addMux(inst_name, RTLIL::State::Sz, net_map_at(inst->GetInput()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput()));
694
+ import_attributes(cell->attributes, inst);
695
+ return true;
696
+ }
697
+
698
+ if (inst->Type() == PRIM_FADD)
699
+ {
700
+ RTLIL::SigSpec a_plus_b = module->addWire(new_verific_id(inst), 2);
701
+ RTLIL::SigSpec y = inst->GetOutput() ? net_map_at(inst->GetOutput()) : module->addWire(new_verific_id(inst));
702
+ if (inst->GetCout())
703
+ y.append(net_map_at(inst->GetCout()));
704
+ cell = module->addAdd(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), a_plus_b);
705
+ import_attributes(cell->attributes, inst);
706
+ cell = module->addAdd(inst_name, a_plus_b, net_map_at(inst->GetCin()), y);
707
+ import_attributes(cell->attributes, inst);
708
+ return true;
709
+ }
710
+
711
+ if (inst->Type() == PRIM_DFFRS)
712
+ {
713
+ VerificClocking clocking(this, inst->GetClock());
714
+ log_assert(clocking.disable_sig == State::S0);
715
+ log_assert(clocking.body_net == nullptr);
716
+
717
+ if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd())
718
+ cell = clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
719
+ else if (inst->GetSet()->IsGnd())
720
+ cell = clocking.addAdff(inst_name, net_map_at(inst->GetReset()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), RTLIL::State::S0);
721
+ else if (inst->GetReset()->IsGnd())
722
+ cell = clocking.addAdff(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), RTLIL::State::S1);
723
+ else
724
+ cell = clocking.addDffsr(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetReset()),
725
+ net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
726
+ import_attributes(cell->attributes, inst);
727
+ return true;
728
+ }
729
+
730
+ if (inst->Type() == PRIM_DLATCHRS)
731
+ {
732
+ if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd())
733
+ cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
734
+ else
735
+ cell = module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetSet()), net_map_at(inst->GetReset()),
736
+ net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
737
+ import_attributes(cell->attributes, inst);
738
+ return true;
739
+ }
740
+
741
+ if (inst->Type() == PRIM_DFF)
742
+ {
743
+ VerificClocking clocking(this, inst->GetClock());
744
+ log_assert(clocking.disable_sig == State::S0);
745
+ log_assert(clocking.body_net == nullptr);
746
+
747
+ if (inst->GetAsyncCond()->IsGnd())
748
+ cell = clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
749
+ else
750
+ cell = clocking.addAldff(inst_name, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal()),
751
+ net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
752
+ import_attributes(cell->attributes, inst);
753
+ return true;
754
+ }
755
+
756
+ if (inst->Type() == PRIM_DLATCH)
757
+ {
758
+ if (inst->GetAsyncCond()->IsGnd()) {
759
+ cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
760
+ } else {
761
+ RTLIL::SigSpec sig_set = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal()));
762
+ RTLIL::SigSpec sig_clr = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), module->Not(NEW_ID, net_map_at(inst->GetAsyncVal())));
763
+ cell = module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), sig_set, sig_clr, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()));
764
+ }
765
+ import_attributes(cell->attributes, inst);
766
+ return true;
767
+ }
768
+
769
+ #define IN operatorInput(inst)
770
+ #define IN1 operatorInput1(inst)
771
+ #define IN2 operatorInput2(inst)
772
+ #define OUT operatorOutput(inst)
773
+ #define FILTERED_OUT operatorOutput(inst, &any_all_nets)
774
+ #define SIGNED inst->View()->IsSigned()
775
+
776
+ if (inst->Type() == OPER_ADDER) {
777
+ RTLIL::SigSpec out = OUT;
778
+ if (inst->GetCout() != NULL)
779
+ out.append(net_map_at(inst->GetCout()));
780
+ if (inst->GetCin()->IsGnd()) {
781
+ cell = module->addAdd(inst_name, IN1, IN2, out, SIGNED);
782
+ import_attributes(cell->attributes, inst);
783
+ } else {
784
+ RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst), GetSize(out));
785
+ cell = module->addAdd(new_verific_id(inst), IN1, IN2, tmp, SIGNED);
786
+ import_attributes(cell->attributes, inst);
787
+ cell = module->addAdd(inst_name, tmp, net_map_at(inst->GetCin()), out, false);
788
+ import_attributes(cell->attributes, inst);
789
+ }
790
+ return true;
791
+ }
792
+
793
+ if (inst->Type() == OPER_MULTIPLIER) {
794
+ cell = module->addMul(inst_name, IN1, IN2, OUT, SIGNED);
795
+ import_attributes(cell->attributes, inst);
796
+ return true;
797
+ }
798
+
799
+ if (inst->Type() == OPER_DIVIDER) {
800
+ cell = module->addDiv(inst_name, IN1, IN2, OUT, SIGNED);
801
+ import_attributes(cell->attributes, inst);
802
+ return true;
803
+ }
804
+
805
+ if (inst->Type() == OPER_MODULO) {
806
+ cell = module->addMod(inst_name, IN1, IN2, OUT, SIGNED);
807
+ import_attributes(cell->attributes, inst);
808
+ return true;
809
+ }
810
+
811
+ if (inst->Type() == OPER_REMAINDER) {
812
+ cell = module->addMod(inst_name, IN1, IN2, OUT, SIGNED);
813
+ import_attributes(cell->attributes, inst);
814
+ return true;
815
+ }
816
+
817
+ if (inst->Type() == OPER_SHIFT_LEFT) {
818
+ cell = module->addShl(inst_name, IN1, IN2, OUT, false);
819
+ import_attributes(cell->attributes, inst);
820
+ return true;
821
+ }
822
+
823
+ if (inst->Type() == OPER_ENABLED_DECODER) {
824
+ RTLIL::SigSpec vec;
825
+ vec.append(net_map_at(inst->GetControl()));
826
+ for (unsigned i = 1; i < inst->OutputSize(); i++) {
827
+ vec.append(RTLIL::State::S0);
828
+ }
829
+ cell = module->addShl(inst_name, vec, IN, OUT, false);
830
+ import_attributes(cell->attributes, inst);
831
+ return true;
832
+ }
833
+
834
+ if (inst->Type() == OPER_DECODER) {
835
+ RTLIL::SigSpec vec;
836
+ vec.append(RTLIL::State::S1);
837
+ for (unsigned i = 1; i < inst->OutputSize(); i++) {
838
+ vec.append(RTLIL::State::S0);
839
+ }
840
+ cell = module->addShl(inst_name, vec, IN, OUT, false);
841
+ import_attributes(cell->attributes, inst);
842
+ return true;
843
+ }
844
+
845
+ if (inst->Type() == OPER_SHIFT_RIGHT) {
846
+ Net *net_cin = inst->GetCin();
847
+ Net *net_a_msb = inst->GetInput1Bit(0);
848
+ if (net_cin->IsGnd())
849
+ cell = module->addShr(inst_name, IN1, IN2, OUT, false);
850
+ else if (net_cin == net_a_msb)
851
+ cell = module->addSshr(inst_name, IN1, IN2, OUT, true);
852
+ else
853
+ log_error("%sCan't import Verific OPER_SHIFT_RIGHT instance %s: carry_in is neither 0 nor msb of left input\n", announce_src_location(inst), inst->Name());
854
+ import_attributes(cell->attributes, inst);
855
+ return true;
856
+ }
857
+
858
+ if (inst->Type() == OPER_REDUCE_AND) {
859
+ cell = module->addReduceAnd(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED);
860
+ import_attributes(cell->attributes, inst);
861
+ return true;
862
+ }
863
+
864
+ if (inst->Type() == OPER_REDUCE_NAND) {
865
+ Wire *tmp = module->addWire(NEW_ID);
866
+ cell = module->addReduceAnd(inst_name, IN, tmp, SIGNED);
867
+ module->addNot(NEW_ID, tmp, net_map_at(inst->GetOutput()));
868
+ import_attributes(cell->attributes, inst);
869
+ return true;
870
+ }
871
+
872
+ if (inst->Type() == OPER_REDUCE_OR) {
873
+ cell = module->addReduceOr(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED);
874
+ import_attributes(cell->attributes, inst);
875
+ return true;
876
+ }
877
+
878
+ if (inst->Type() == OPER_REDUCE_XOR) {
879
+ cell = module->addReduceXor(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED);
880
+ import_attributes(cell->attributes, inst);
881
+ return true;
882
+ }
883
+
884
+ if (inst->Type() == OPER_REDUCE_XNOR) {
885
+ cell = module->addReduceXnor(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED);
886
+ import_attributes(cell->attributes, inst);
887
+ return true;
888
+ }
889
+
890
+ if (inst->Type() == OPER_REDUCE_NOR) {
891
+ SigSpec t = module->ReduceOr(new_verific_id(inst), IN, SIGNED);
892
+ cell = module->addNot(inst_name, t, net_map_at(inst->GetOutput()));
893
+ import_attributes(cell->attributes, inst);
894
+ return true;
895
+ }
896
+
897
+ if (inst->Type() == OPER_LESSTHAN) {
898
+ Net *net_cin = inst->GetCin();
899
+ if (net_cin->IsGnd())
900
+ cell = module->addLt(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED);
901
+ else if (net_cin->IsPwr())
902
+ cell = module->addLe(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED);
903
+ else
904
+ log_error("%sCan't import Verific OPER_LESSTHAN instance %s: carry_in is neither 0 nor 1\n", announce_src_location(inst), inst->Name());
905
+ import_attributes(cell->attributes, inst);
906
+ return true;
907
+ }
908
+
909
+ if (inst->Type() == OPER_WIDE_AND) {
910
+ cell = module->addAnd(inst_name, IN1, IN2, OUT, SIGNED);
911
+ import_attributes(cell->attributes, inst);
912
+ return true;
913
+ }
914
+
915
+ if (inst->Type() == OPER_WIDE_OR) {
916
+ cell = module->addOr(inst_name, IN1, IN2, OUT, SIGNED);
917
+ import_attributes(cell->attributes, inst);
918
+ return true;
919
+ }
920
+
921
+ if (inst->Type() == OPER_WIDE_XOR) {
922
+ cell = module->addXor(inst_name, IN1, IN2, OUT, SIGNED);
923
+ import_attributes(cell->attributes, inst);
924
+ return true;
925
+ }
926
+
927
+ if (inst->Type() == OPER_WIDE_XNOR) {
928
+ cell = module->addXnor(inst_name, IN1, IN2, OUT, SIGNED);
929
+ import_attributes(cell->attributes, inst);
930
+ return true;
931
+ }
932
+
933
+ if (inst->Type() == OPER_WIDE_BUF) {
934
+ cell = module->addPos(inst_name, IN, FILTERED_OUT, SIGNED);
935
+ import_attributes(cell->attributes, inst);
936
+ return true;
937
+ }
938
+
939
+ if (inst->Type() == OPER_WIDE_INV) {
940
+ cell = module->addNot(inst_name, IN, OUT, SIGNED);
941
+ import_attributes(cell->attributes, inst);
942
+ return true;
943
+ }
944
+
945
+ if (inst->Type() == OPER_MINUS) {
946
+ cell = module->addSub(inst_name, IN1, IN2, OUT, SIGNED);
947
+ import_attributes(cell->attributes, inst);
948
+ return true;
949
+ }
950
+
951
+ if (inst->Type() == OPER_UMINUS) {
952
+ cell = module->addNeg(inst_name, IN, OUT, SIGNED);
953
+ import_attributes(cell->attributes, inst);
954
+ return true;
955
+ }
956
+
957
+ if (inst->Type() == OPER_EQUAL) {
958
+ cell = module->addEq(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED);
959
+ import_attributes(cell->attributes, inst);
960
+ return true;
961
+ }
962
+
963
+ if (inst->Type() == OPER_NEQUAL) {
964
+ cell = module->addNe(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED);
965
+ import_attributes(cell->attributes, inst);
966
+ return true;
967
+ }
968
+
969
+ if (inst->Type() == OPER_WIDE_MUX) {
970
+ cell = module->addMux(inst_name, IN1, IN2, net_map_at(inst->GetControl()), OUT);
971
+ import_attributes(cell->attributes, inst);
972
+ return true;
973
+ }
974
+
975
+ if (inst->Type() == OPER_NTO1MUX) {
976
+ cell = module->addBmux(inst_name, IN2, IN1, net_map_at(inst->GetOutput()));
977
+ import_attributes(cell->attributes, inst);
978
+ return true;
979
+ }
980
+
981
+ if (inst->Type() == OPER_WIDE_NTO1MUX)
982
+ {
983
+ cell = module->addBmux(inst_name, IN2, IN1, OUT);
984
+ import_attributes(cell->attributes, inst);
985
+ return true;
986
+ }
987
+
988
+ if (inst->Type() == OPER_SELECTOR)
989
+ {
990
+ cell = module->addPmux(inst_name, State::S0, IN2, IN1, net_map_at(inst->GetOutput()));
991
+ import_attributes(cell->attributes, inst);
992
+ return true;
993
+ }
994
+
995
+ if (inst->Type() == OPER_WIDE_SELECTOR)
996
+ {
997
+ SigSpec out = OUT;
998
+ cell = module->addPmux(inst_name, SigSpec(State::S0, GetSize(out)), IN2, IN1, out);
999
+ import_attributes(cell->attributes, inst);
1000
+ return true;
1001
+ }
1002
+
1003
+ if (inst->Type() == OPER_WIDE_TRI) {
1004
+ cell = module->addMux(inst_name, RTLIL::SigSpec(RTLIL::State::Sz, inst->OutputSize()), IN, net_map_at(inst->GetControl()), OUT);
1005
+ import_attributes(cell->attributes, inst);
1006
+ return true;
1007
+ }
1008
+
1009
+ if (inst->Type() == OPER_WIDE_DFFRS)
1010
+ {
1011
+ VerificClocking clocking(this, inst->GetClock());
1012
+ log_assert(clocking.disable_sig == State::S0);
1013
+ log_assert(clocking.body_net == nullptr);
1014
+
1015
+ RTLIL::SigSpec sig_set = operatorInport(inst, "set");
1016
+ RTLIL::SigSpec sig_reset = operatorInport(inst, "reset");
1017
+
1018
+ if (sig_set.is_fully_const() && !sig_set.as_bool() && sig_reset.is_fully_const() && !sig_reset.as_bool())
1019
+ cell = clocking.addDff(inst_name, IN, OUT);
1020
+ else
1021
+ cell = clocking.addDffsr(inst_name, sig_set, sig_reset, IN, OUT);
1022
+ import_attributes(cell->attributes, inst);
1023
+
1024
+ return true;
1025
+ }
1026
+
1027
+ if (inst->Type() == OPER_WIDE_DLATCHRS)
1028
+ {
1029
+ RTLIL::SigSpec sig_set = operatorInport(inst, "set");
1030
+ RTLIL::SigSpec sig_reset = operatorInport(inst, "reset");
1031
+
1032
+ if (sig_set.is_fully_const() && !sig_set.as_bool() && sig_reset.is_fully_const() && !sig_reset.as_bool())
1033
+ cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), IN, OUT);
1034
+ else
1035
+ cell = module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), sig_set, sig_reset, IN, OUT);
1036
+ import_attributes(cell->attributes, inst);
1037
+
1038
+ return true;
1039
+ }
1040
+
1041
+ if (inst->Type() == OPER_WIDE_DFF)
1042
+ {
1043
+ VerificClocking clocking(this, inst->GetClock());
1044
+ log_assert(clocking.disable_sig == State::S0);
1045
+ log_assert(clocking.body_net == nullptr);
1046
+
1047
+ RTLIL::SigSpec sig_d = IN;
1048
+ RTLIL::SigSpec sig_q = OUT;
1049
+ RTLIL::SigSpec sig_adata = IN1;
1050
+ RTLIL::SigSpec sig_acond = IN2;
1051
+
1052
+ if (sig_acond.is_fully_const() && !sig_acond.as_bool()) {
1053
+ cell = clocking.addDff(inst_name, sig_d, sig_q);
1054
+ import_attributes(cell->attributes, inst);
1055
+ } else {
1056
+ int offset = 0, width = 0;
1057
+ for (offset = 0; offset < GetSize(sig_acond); offset += width) {
1058
+ for (width = 1; offset+width < GetSize(sig_acond); width++)
1059
+ if (sig_acond[offset] != sig_acond[offset+width]) break;
1060
+ cell = clocking.addAldff(module->uniquify(inst_name), sig_acond[offset], sig_adata.extract(offset, width),
1061
+ sig_d.extract(offset, width), sig_q.extract(offset, width));
1062
+ import_attributes(cell->attributes, inst);
1063
+ }
1064
+ }
1065
+
1066
+ return true;
1067
+ }
1068
+
1069
+ if (inst->Type() == OPER_WIDE_DLATCH)
1070
+ {
1071
+ RTLIL::SigSpec sig_d = IN;
1072
+ RTLIL::SigSpec sig_q = OUT;
1073
+ RTLIL::SigSpec sig_adata = IN1;
1074
+ RTLIL::SigSpec sig_acond = IN2;
1075
+
1076
+ if (sig_acond.is_fully_const() && !sig_acond.as_bool()) {
1077
+ cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), sig_d, sig_q);
1078
+ import_attributes(cell->attributes, inst);
1079
+ } else {
1080
+ int offset = 0, width = 0;
1081
+ for (offset = 0; offset < GetSize(sig_acond); offset += width) {
1082
+ for (width = 1; offset+width < GetSize(sig_acond); width++)
1083
+ if (sig_acond[offset] != sig_acond[offset+width]) break;
1084
+ RTLIL::SigSpec sig_set = module->Mux(NEW_ID, RTLIL::SigSpec(0, width), sig_adata.extract(offset, width), sig_acond[offset]);
1085
+ RTLIL::SigSpec sig_clr = module->Mux(NEW_ID, RTLIL::SigSpec(0, width), module->Not(NEW_ID, sig_adata.extract(offset, width)), sig_acond[offset]);
1086
+ cell = module->addDlatchsr(module->uniquify(inst_name), net_map_at(inst->GetControl()), sig_set, sig_clr,
1087
+ sig_d.extract(offset, width), sig_q.extract(offset, width));
1088
+ import_attributes(cell->attributes, inst);
1089
+ }
1090
+ }
1091
+
1092
+ return true;
1093
+ }
1094
+
1095
+ if (inst->Type() == OPER_WIDE_CASE_SELECT_BOX)
1096
+ {
1097
+ RTLIL::SigSpec sig_out_val = operatorInport(inst, "out_value");
1098
+ RTLIL::SigSpec sig_select = operatorInport(inst, "select");
1099
+ RTLIL::SigSpec sig_select_values = operatorInportCase(inst, "select_values");
1100
+ RTLIL::SigSpec sig_data_values = operatorInport(inst, "data_values");
1101
+ RTLIL::SigSpec sig_data_default = operatorInport(inst, "default_value");
1102
+
1103
+ RTLIL::Process *proc = module->addProcess(new_verific_id(inst));
1104
+ import_attributes(proc->attributes, inst);
1105
+
1106
+ RTLIL::CaseRule *current_case = &proc->root_case;
1107
+ current_case = &proc->root_case;
1108
+
1109
+ RTLIL::SwitchRule *sw = new RTLIL::SwitchRule;
1110
+ sw->signal = sig_select;
1111
+ current_case->switches.push_back(sw);
1112
+
1113
+ unsigned select_width = inst->InputSize();
1114
+ unsigned data_width = inst->OutputSize();
1115
+ unsigned offset_data = 0;
1116
+ unsigned offset_select = 0;
1117
+
1118
+ OperWideCaseSelector* selector = (OperWideCaseSelector*) inst->View();
1119
+
1120
+ for (unsigned i = 0 ; i < selector->GetNumBranches() ; ++i) {
1121
+
1122
+ SigSig action(sig_out_val, sig_data_values.extract(offset_data, data_width));
1123
+ offset_data += data_width;
1124
+
1125
+ for (unsigned j = 0 ; j < selector->GetNumConditions(i) ; ++j) {
1126
+ Array left_bound, right_bound ;
1127
+ selector->GetCondition(i, j, &left_bound, &right_bound);
1128
+
1129
+ SigSpec sel_left = sig_select_values.extract(offset_select, select_width);
1130
+ offset_select += select_width;
1131
+
1132
+ if (right_bound.Size()) {
1133
+ SigSpec sel_right = sig_select_values.extract(offset_select, select_width);
1134
+ offset_select += select_width;
1135
+
1136
+ log_assert(sel_right.is_fully_const() && sel_right.is_fully_def());
1137
+ log_assert(sel_left.is_fully_const() && sel_right.is_fully_def());
1138
+
1139
+ int32_t left = sel_left.as_int();
1140
+ int32_t right = sel_right.as_int();
1141
+ int width = sel_left.size();
1142
+
1143
+ for (int32_t i = right; i<left; i++) {
1144
+ RTLIL::CaseRule *cs = new RTLIL::CaseRule;
1145
+ cs->compare.push_back(RTLIL::Const(i,width));
1146
+ cs->actions.push_back(action);
1147
+ sw->cases.push_back(cs);
1148
+ }
1149
+ }
1150
+
1151
+ RTLIL::CaseRule *cs = new RTLIL::CaseRule;
1152
+ cs->compare.push_back(sel_left);
1153
+ cs->actions.push_back(action);
1154
+ sw->cases.push_back(cs);
1155
+ }
1156
+ }
1157
+ RTLIL::CaseRule *cs_default = new RTLIL::CaseRule;
1158
+ cs_default->actions.push_back(SigSig(sig_out_val, sig_data_default));
1159
+ sw->cases.push_back(cs_default);
1160
+
1161
+ return true;
1162
+ }
1163
+
1164
+ #ifdef YOSYSHQ_VERIFIC_API_VERSION
1165
+ if (inst->Type() == OPER_YOSYSHQ_SET_TAG)
1166
+ {
1167
+ RTLIL::SigSpec sig_expr = operatorInport(inst, "expr");
1168
+ RTLIL::SigSpec sig_set_mask = operatorInport(inst, "set_mask");
1169
+ RTLIL::SigSpec sig_clr_mask = operatorInport(inst, "clr_mask");
1170
+ RTLIL::SigSpec sig_o = operatorOutput(inst);
1171
+ std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : "";
1172
+ module->connect(sig_o, module->SetTag(new_verific_id(inst), tag, sig_expr, sig_set_mask, sig_clr_mask));
1173
+ return true;
1174
+ }
1175
+ if (inst->Type() == OPER_YOSYSHQ_GET_TAG)
1176
+ {
1177
+ std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : "";
1178
+ module->connect(operatorOutput(inst),module->GetTag(new_verific_id(inst), tag, operatorInput(inst)));
1179
+ return true;
1180
+ }
1181
+ if (inst->Type() == OPER_YOSYSHQ_OVERWRITE_TAG)
1182
+ {
1183
+ RTLIL::SigSpec sig_signal = operatorInport(inst, "signal");
1184
+ RTLIL::SigSpec sig_set_mask = operatorInport(inst, "set_mask");
1185
+ RTLIL::SigSpec sig_clr_mask = operatorInport(inst, "clr_mask");
1186
+ std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : "";
1187
+ module->addOverwriteTag(new_verific_id(inst), tag, sig_signal, sig_set_mask, sig_clr_mask);
1188
+ return true;
1189
+ }
1190
+ if (inst->Type() == OPER_YOSYSHQ_ORIGINAL_TAG)
1191
+ {
1192
+ std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : "";
1193
+ module->connect(operatorOutput(inst),module->OriginalTag(new_verific_id(inst), tag, operatorInput(inst)));
1194
+ return true;
1195
+ }
1196
+ if (inst->Type() == OPER_YOSYSHQ_FUTURE_FF)
1197
+ {
1198
+ module->connect(operatorOutput(inst),module->FutureFF(new_verific_id(inst), operatorInput(inst)));
1199
+ return true;
1200
+ }
1201
+ #endif
1202
+
1203
+ #undef IN
1204
+ #undef IN1
1205
+ #undef IN2
1206
+ #undef OUT
1207
+ #undef SIGNED
1208
+
1209
+ return false;
1210
+ }
1211
+
1212
+ void VerificImporter::merge_past_ffs_clock(pool<RTLIL::Cell*> &candidates, SigBit clock, bool clock_pol)
1213
+ {
1214
+ bool keep_running = true;
1215
+ SigMap sigmap;
1216
+
1217
+ while (keep_running)
1218
+ {
1219
+ keep_running = false;
1220
+
1221
+ dict<SigBit, pool<RTLIL::Cell*>> dbits_db;
1222
+ SigSpec dbits;
1223
+
1224
+ for (auto cell : candidates) {
1225
+ SigBit bit = sigmap(cell->getPort(ID::D));
1226
+ dbits_db[bit].insert(cell);
1227
+ dbits.append(bit);
1228
+ }
1229
+
1230
+ dbits.sort_and_unify();
1231
+
1232
+ for (auto chunk : dbits.chunks())
1233
+ {
1234
+ SigSpec sig_d = chunk;
1235
+
1236
+ if (chunk.wire == nullptr || GetSize(sig_d) == 1)
1237
+ continue;
1238
+
1239
+ SigSpec sig_q = module->addWire(NEW_ID, GetSize(sig_d));
1240
+ RTLIL::Cell *new_ff = module->addDff(NEW_ID, clock, sig_d, sig_q, clock_pol);
1241
+
1242
+ if (verific_verbose)
1243
+ log(" merging single-bit past_ffs into new %d-bit ff %s.\n", GetSize(sig_d), new_ff);
1244
+
1245
+ for (int i = 0; i < GetSize(sig_d); i++)
1246
+ for (auto old_ff : dbits_db[sig_d[i]])
1247
+ {
1248
+ if (verific_verbose)
1249
+ log(" replacing old ff %s on bit %d.\n", old_ff, i);
1250
+
1251
+ SigBit old_q = old_ff->getPort(ID::Q);
1252
+ SigBit new_q = sig_q[i];
1253
+
1254
+ sigmap.add(old_q, new_q);
1255
+ module->connect(old_q, new_q);
1256
+ candidates.erase(old_ff);
1257
+ module->remove(old_ff);
1258
+ keep_running = true;
1259
+ }
1260
+ }
1261
+ }
1262
+ }
1263
+
1264
+ void VerificImporter::merge_past_ffs(pool<RTLIL::Cell*> &candidates)
1265
+ {
1266
+ dict<pair<SigBit, int>, pool<RTLIL::Cell*>> database;
1267
+
1268
+ for (auto cell : candidates)
1269
+ {
1270
+ if (cell->type != ID($dff)) continue;
1271
+ SigBit clock = cell->getPort(ID::CLK);
1272
+ bool clock_pol = cell->getParam(ID::CLK_POLARITY).as_bool();
1273
+ database[make_pair(clock, int(clock_pol))].insert(cell);
1274
+ }
1275
+
1276
+ for (auto it : database)
1277
+ merge_past_ffs_clock(it.second, it.first.first, it.first.second);
1278
+ }
1279
+
1280
+ static std::string sha1_if_contain_spaces(std::string str)
1281
+ {
1282
+ if(str.find_first_of(' ') != std::string::npos) {
1283
+ std::size_t open = str.find_first_of('(');
1284
+ std::size_t closed = str.find_last_of(')');
1285
+ if (open != std::string::npos && closed != std::string::npos) {
1286
+ std::string content = str.substr(open + 1, closed - open - 1);
1287
+ return str.substr(0, open + 1) + sha1(content) + str.substr(closed);
1288
+ } else {
1289
+ return sha1(str);
1290
+ }
1291
+ }
1292
+ return str;
1293
+ }
1294
+
1295
+ void VerificImporter::recurse_mem_dimensions(RTLIL::Module *module, RTLIL::Memory *memory, Net *net, const char *&ascii_initdata, int max_bits_in_addr, const RTLIL::SigSpec &prefix, TypeRange *typeRange) {
1296
+ if (typeRange == nullptr)
1297
+ typeRange = net->GetOrigTypeRange();
1298
+
1299
+ auto *nextRange = typeRange->GetNext();
1300
+ auto left = typeRange->LeftRangeBound();
1301
+ auto right = typeRange->RightRangeBound();
1302
+ bool is_up = left < right;
1303
+ for (auto i = left; is_up ? i <= right : i >= right; is_up ? i++ : i--) {
1304
+ // TODO verific can do u64
1305
+ auto max_bits = max_bits_in_addr - prefix.size();
1306
+ auto next_sig = SigSpec(Const(i, typeRange->NumBits()));
1307
+ auto extra_bits = next_sig.size() - max_bits;
1308
+ if (extra_bits > 0) {
1309
+ next_sig = next_sig.extract_end(extra_bits);
1310
+ auto extra_inc = (1 << extra_bits) - 1;
1311
+ i = is_up ? i + extra_inc : i - extra_inc;
1312
+ }
1313
+ next_sig.append(prefix);
1314
+ if (nextRange != nullptr && extra_bits < 0) {
1315
+ recurse_mem_dimensions(module, memory, net, ascii_initdata, max_bits_in_addr, next_sig, nextRange);
1316
+ } else {
1317
+ if (next_sig.size() != max_bits_in_addr) {
1318
+ // TODO verific can do u64
1319
+ log_error("Expected %d bits for addr but got %d!\n", max_bits_in_addr, next_sig.size());
1320
+ }
1321
+ Const initval = Const(State::Sx, memory->width);
1322
+ bool initval_valid = false;
1323
+ if (ascii_initdata) {
1324
+ for (int bit_idx = memory->width-1; bit_idx >= 0; bit_idx--) {
1325
+ if (*ascii_initdata == 0)
1326
+ break;
1327
+ if (*ascii_initdata == '0' || *ascii_initdata == '1') {
1328
+ initval.set(bit_idx, (*ascii_initdata == '0') ? State::S0 : State::S1);
1329
+ initval_valid = true;
1330
+ }
1331
+ ascii_initdata++;
1332
+ }
1333
+ }
1334
+ if (!next_sig.convertible_to_int())
1335
+ log_error("Address %s on RAM for identifier '%s' too wide!\n", log_signal(next_sig), net->Name());
1336
+ auto next_idx = next_sig.as_int();
1337
+ if (initval_valid) {
1338
+ RTLIL::Cell *cell = module->addCell(new_verific_id(net), ID($meminit));
1339
+ cell->parameters[ID::WORDS] = 1;
1340
+ cell->setPort(ID::ADDR, next_idx);
1341
+ cell->setPort(ID::DATA, initval);
1342
+ cell->parameters[ID::MEMID] = RTLIL::Const(memory->name.str());
1343
+ cell->parameters[ID::ABITS] = 32;
1344
+ cell->parameters[ID::WIDTH] = memory->width;
1345
+ cell->parameters[ID::PRIORITY] = RTLIL::Const(module->twines().autoidx()-1);
1346
+ }
1347
+ memory->start_offset = min(memory->start_offset, next_idx);
1348
+ memory->size = max(memory->size, next_idx);
1349
+ }
1350
+ }
1351
+ }
1352
+
1353
+ void VerificImporter::import_netlist(RTLIL::Design *design, Netlist *nl, std::map<std::string,Netlist*> &nl_todo, bool norename)
1354
+ {
1355
+ std::string netlist_name = nl->GetAtt(" \\top") || is_blackbox(nl) ? nl->CellBaseName() : nl->Owner()->Name();
1356
+ std::string module_name = netlist_name;
1357
+
1358
+ if (nl->IsOperator() || nl->IsPrimitive()) {
1359
+ module_name = "$verific$" + module_name;
1360
+ } else {
1361
+ if (!norename && *nl->Name() && !is_blackbox(nl)) {
1362
+ module_name += "(";
1363
+ module_name += nl->Name();
1364
+ module_name += ")";
1365
+ }
1366
+ module_name = "\\" + sha1_if_contain_spaces(module_name);
1367
+ }
1368
+
1369
+ {
1370
+ Array ram_nets ;
1371
+ MapIter mem_mi;
1372
+ Net *mem_net;
1373
+ FOREACH_NET_OF_NETLIST(nl, mem_mi, mem_net)
1374
+ {
1375
+ if (!mem_net->IsRamNet()) continue ;
1376
+
1377
+ if (mem_net->GetAtt("mem2reg"))
1378
+ ram_nets.Insert(mem_net) ;
1379
+ }
1380
+ unsigned i ;
1381
+ FOREACH_ARRAY_ITEM(&ram_nets, i, mem_net) {
1382
+ log("Bit blasting RAM for identifier '%s'\n", mem_net->Name());
1383
+ mem_net->BlastNet();
1384
+ }
1385
+ nl->RemoveDanglingLogic(0);
1386
+ }
1387
+
1388
+ netlist = nl;
1389
+
1390
+ IdString module_id = design->twines().add(module_name);
1391
+ if (design->has(module_id)) {
1392
+ if (!nl->IsOperator() && !is_blackbox(nl))
1393
+ log_cmd_error("Re-definition of module `%s'.\n", netlist_name);
1394
+ return;
1395
+ }
1396
+
1397
+ module = new RTLIL::Module(design);
1398
+ module->name = module_id;
1399
+ design->add(module);
1400
+
1401
+ if (is_blackbox(nl)) {
1402
+ log("Importing blackbox module %s.\n", module);
1403
+ module->set_bool_attribute(ID::blackbox);
1404
+ } else {
1405
+ log("Importing module %s.\n", module);
1406
+ }
1407
+ import_attributes(module->attributes, nl, nl);
1408
+ if (module->name.isPublic())
1409
+ module->set_string_attribute(ID::hdlname, nl->CellBaseName());
1410
+ module->set_string_attribute(ID(library), nl->Owner()->Owner()->Name());
1411
+ #ifdef VERIFIC_VHDL_SUPPORT
1412
+ if (nl->IsFromVhdl()) {
1413
+ NameSpace name_space(0);
1414
+ char *architecture_name = name_space.ReName(nl->Name()) ;
1415
+ module->set_string_attribute(ID(architecture), (architecture_name) ? architecture_name : nl->Name());
1416
+ }
1417
+ #endif
1418
+ const char *param_name ;
1419
+ const char *param_value ;
1420
+ MapIter mi;
1421
+ FOREACH_PARAMETER_OF_NETLIST(nl, mi, param_name, param_value) {
1422
+ IdString param_id = design->twines().add(RTLIL::escape_id(param_name));
1423
+ module->avail_parameters(param_id);
1424
+ const TypeRange *tr = nl->GetTypeRange(param_name) ;
1425
+ const char* type_name = (tr) ? tr->GetTypeName() : nullptr;
1426
+ module->parameter_default_values[param_id] = verific_const(type_name, param_value, nl);
1427
+ }
1428
+
1429
+ SetIter si;
1430
+ MapIter mi2;
1431
+ Port *port;
1432
+ PortBus *portbus;
1433
+ Net *net;
1434
+ NetBus *netbus;
1435
+ Instance *inst;
1436
+ PortRef *pr;
1437
+ Att *attr;
1438
+
1439
+ FOREACH_ATTRIBUTE(nl, mi, attr) {
1440
+ if (!strcmp(attr->Key(), "noblackbox"))
1441
+ module->set_bool_attribute(ID::blackbox, false);
1442
+ }
1443
+
1444
+ FOREACH_PORT_OF_NETLIST(nl, mi, port)
1445
+ {
1446
+ if (port->Bus())
1447
+ continue;
1448
+
1449
+ if (verific_verbose)
1450
+ log(" importing port %s.\n", port->Name());
1451
+
1452
+ RTLIL::Wire *wire = module->addWire(RTLIL::escape_id(port->Name()));
1453
+ import_attributes(wire->attributes, port, nl, 1);
1454
+
1455
+ wire->port_id = nl->IndexOf(port) + 1;
1456
+
1457
+ if (port->GetDir() == DIR_INOUT || port->GetDir() == DIR_IN)
1458
+ wire->port_input = true;
1459
+ if (port->GetDir() == DIR_INOUT || port->GetDir() == DIR_OUT)
1460
+ wire->port_output = true;
1461
+
1462
+ if (port->GetNet()) {
1463
+ net = port->GetNet();
1464
+ if (net_map.count(net) == 0)
1465
+ net_map[net] = wire;
1466
+ else if (wire->port_input)
1467
+ module->connect(net_map_at(net), wire);
1468
+ else
1469
+ module->connect(wire, net_map_at(net));
1470
+ }
1471
+ }
1472
+
1473
+ FOREACH_PORTBUS_OF_NETLIST(nl, mi, portbus)
1474
+ {
1475
+ if (verific_verbose)
1476
+ log(" importing portbus %s.\n", portbus->Name());
1477
+
1478
+ RTLIL::Wire *wire = module->addWire(RTLIL::escape_id(portbus->Name()), portbus->Size());
1479
+ wire->start_offset = min(portbus->LeftIndex(), portbus->RightIndex());
1480
+ wire->upto = portbus->IsUp();
1481
+ import_attributes(wire->attributes, portbus, nl, portbus->Size());
1482
+ if (portbus->Size() == 1)
1483
+ wire->set_bool_attribute(ID::single_bit_vector);
1484
+ SetIter si ;
1485
+ Port *port ;
1486
+ FOREACH_PORT_OF_PORTBUS(portbus, si, port) {
1487
+ wire->port_id = nl->IndexOf(port) + 1;
1488
+ import_attributes(wire->attributes, port->GetNet(), nl, portbus->Size());
1489
+ break;
1490
+ }
1491
+ bool portbus_input = portbus->GetDir() == DIR_INOUT || portbus->GetDir() == DIR_IN;
1492
+ if (portbus_input)
1493
+ wire->port_input = true;
1494
+ if (portbus->GetDir() == DIR_INOUT || portbus->GetDir() == DIR_OUT)
1495
+ wire->port_output = true;
1496
+
1497
+ for (int i = portbus->LeftIndex();; i += portbus->IsUp() ? +1 : -1) {
1498
+ if (portbus->ElementAtIndex(i) && portbus->ElementAtIndex(i)->GetNet()) {
1499
+ bool bit_input = portbus_input;
1500
+ if (portbus->GetDir() == DIR_NONE) {
1501
+ Port *p = portbus->ElementAtIndex(i);
1502
+ bit_input = p->GetDir() == DIR_INOUT || p->GetDir() == DIR_IN;
1503
+ if (bit_input)
1504
+ wire->port_input = true;
1505
+ if (p->GetDir() == DIR_INOUT || p->GetDir() == DIR_OUT)
1506
+ wire->port_output = true;
1507
+ }
1508
+ net = portbus->ElementAtIndex(i)->GetNet();
1509
+ int bitidx = wire->upto ? (wire->width - 1 - (i - wire->start_offset)) : (i - wire->start_offset);
1510
+ RTLIL::SigBit bit(wire, bitidx);
1511
+ if (net_map.count(net) == 0)
1512
+ net_map[net] = bit;
1513
+ else if (bit_input)
1514
+ module->connect(net_map_at(net), bit);
1515
+ else
1516
+ module->connect(bit, net_map_at(net));
1517
+ }
1518
+ if (i == portbus->RightIndex())
1519
+ break;
1520
+ }
1521
+ }
1522
+
1523
+ module->fixup_ports();
1524
+
1525
+ dict<Net*, char> init_nets;
1526
+ pool<Net*> anyconst_nets, anyseq_nets;
1527
+ pool<Net*> allconst_nets, allseq_nets;
1528
+ any_all_nets.clear();
1529
+
1530
+ FOREACH_NET_OF_NETLIST(nl, mi, net)
1531
+ {
1532
+ if (net->IsRamNet())
1533
+ {
1534
+ IdString memory_name = design->twines().add(RTLIL::escape_id(net->Name()));
1535
+ log_assert(module->count_id(memory_name) == 0);
1536
+ RTLIL::Memory *memory = module->addMemory(memory_name);
1537
+ import_attributes(memory->attributes, net, nl);
1538
+
1539
+ int number_of_bits = net->Size();
1540
+ int min_bits_in_word = number_of_bits;
1541
+ int max_bits_in_addr = 0;
1542
+
1543
+ // get the size of each memory access
1544
+ FOREACH_PORTREF_OF_NET(net, si, pr) {
1545
+ auto *inst = pr->GetInst();
1546
+ int bits_in_word;
1547
+ if (inst->Type() == OPER_READ_PORT)
1548
+ bits_in_word = inst->OutputSize();
1549
+ else if (inst->Type() == OPER_WRITE_PORT || inst->Type() == OPER_CLOCKED_WRITE_PORT)
1550
+ bits_in_word = inst->Input2Size();
1551
+ else
1552
+ log_error("%sVerific RamNet %s is connected to unsupported instance type %s (%s).\n", announce_src_location(inst),
1553
+ net->Name(), inst->View()->Owner()->Name(), inst->Name());
1554
+
1555
+ if (bits_in_word < min_bits_in_word) {
1556
+ min_bits_in_word = bits_in_word;
1557
+ max_bits_in_addr = inst->Input1Size();
1558
+ }
1559
+ }
1560
+
1561
+ int number_of_words = number_of_bits / min_bits_in_word;
1562
+
1563
+ memory->width = min_bits_in_word;
1564
+ memory->size = 0;
1565
+ memory->start_offset = INT_MAX;
1566
+
1567
+ const char *ascii_initdata = net->GetWideInitialValue();
1568
+ if (ascii_initdata) {
1569
+ while (*ascii_initdata != 0 && *ascii_initdata != '\'')
1570
+ ascii_initdata++;
1571
+ if (*ascii_initdata == '\'')
1572
+ ascii_initdata++;
1573
+ if (*ascii_initdata != 0) {
1574
+ log_assert(*ascii_initdata == 'b');
1575
+ ascii_initdata++;
1576
+ }
1577
+ }
1578
+
1579
+ // process initdata and fixup min/max address
1580
+ auto prefix = SigSpec();
1581
+ recurse_mem_dimensions(module, memory, net, ascii_initdata, max_bits_in_addr, prefix);
1582
+
1583
+ auto min_idx = memory->start_offset;
1584
+ auto max_idx = memory->size;
1585
+ memory->size = max_idx - min_idx + 1;
1586
+
1587
+ // sanity check we haven't shrunk the memory
1588
+ if (memory->size < number_of_words)
1589
+ log_error("Expected memory of size %d words, but got %d for address range %d to %d (inclusive)\n", number_of_words, memory->size, min_idx, max_idx);
1590
+
1591
+ // warn on oversize memories
1592
+ // TODO consider using a minimum ratio?
1593
+ if (memory->size > number_of_words) {
1594
+ float ratio = memory->size / (float)number_of_words;
1595
+ log_warning("RAM for identifier '%s' may be up to %.0f%% oversize due to addressing\n", net->Name(), (ratio-1)*100);
1596
+ log_debug("Expected memory of size %d words, but got %d for address range %d to %d (inclusive)\n", number_of_words, memory->size, min_idx, max_idx);
1597
+ }
1598
+ continue;
1599
+ }
1600
+
1601
+ if (net->GetInitialValue())
1602
+ init_nets[net] = net->GetInitialValue();
1603
+
1604
+ const char *rand_const_attr = net->GetAttValue(" rand_const");
1605
+ const char *rand_attr = net->GetAttValue(" rand");
1606
+
1607
+ const char *anyconst_attr = net->GetAttValue("anyconst");
1608
+ const char *anyseq_attr = net->GetAttValue("anyseq");
1609
+
1610
+ const char *allconst_attr = net->GetAttValue("allconst");
1611
+ const char *allseq_attr = net->GetAttValue("allseq");
1612
+
1613
+ if (rand_const_attr != nullptr && (!strcmp(rand_const_attr, "1") || !strcmp(rand_const_attr, "'1'"))) {
1614
+ anyconst_nets.insert(net);
1615
+ any_all_nets.insert(net);
1616
+ }
1617
+ else if (rand_attr != nullptr && (!strcmp(rand_attr, "1") || !strcmp(rand_attr, "'1'"))) {
1618
+ anyseq_nets.insert(net);
1619
+ any_all_nets.insert(net);
1620
+ }
1621
+ else if (anyconst_attr != nullptr && (!strcmp(anyconst_attr, "1") || !strcmp(anyconst_attr, "'1'"))) {
1622
+ anyconst_nets.insert(net);
1623
+ any_all_nets.insert(net);
1624
+ }
1625
+ else if (anyseq_attr != nullptr && (!strcmp(anyseq_attr, "1") || !strcmp(anyseq_attr, "'1'"))) {
1626
+ anyseq_nets.insert(net);
1627
+ any_all_nets.insert(net);
1628
+ }
1629
+ else if (allconst_attr != nullptr && (!strcmp(allconst_attr, "1") || !strcmp(allconst_attr, "'1'"))) {
1630
+ allconst_nets.insert(net);
1631
+ any_all_nets.insert(net);
1632
+ }
1633
+ else if (allseq_attr != nullptr && (!strcmp(allseq_attr, "1") || !strcmp(allseq_attr, "'1'"))) {
1634
+ allseq_nets.insert(net);
1635
+ any_all_nets.insert(net);
1636
+ }
1637
+
1638
+ if (net_map.count(net)) {
1639
+ if (verific_verbose)
1640
+ log(" skipping net %s.\n", net->Name());
1641
+ continue;
1642
+ }
1643
+
1644
+ if (net->Bus())
1645
+ continue;
1646
+
1647
+ RTLIL::IdString wire_name = module->uniquify(mode_names || net->IsUserDeclared() ? design->twines().add(RTLIL::escape_id(net->Name())) : new_verific_id(net));
1648
+
1649
+ RTLIL::Wire *wire = module->addWire(wire_name);
1650
+
1651
+ if (verific_verbose)
1652
+ log(" importing net %s as %s.\n", net->Name(), wire);
1653
+ import_attributes(wire->attributes, net, nl, 1);
1654
+
1655
+ net_map[net] = wire;
1656
+ }
1657
+
1658
+ FOREACH_NETBUS_OF_NETLIST(nl, mi, netbus)
1659
+ {
1660
+ bool found_new_net = false;
1661
+ for (int i = netbus->LeftIndex();; i += netbus->IsUp() ? +1 : -1) {
1662
+ net = netbus->ElementAtIndex(i);
1663
+ if (net_map.count(net) == 0)
1664
+ found_new_net = true;
1665
+ if (i == netbus->RightIndex())
1666
+ break;
1667
+ }
1668
+
1669
+ if (found_new_net)
1670
+ {
1671
+ RTLIL::IdString wire_name = module->uniquify(mode_names || netbus->IsUserDeclared() ? design->twines().add(RTLIL::escape_id(netbus->Name())) : new_verific_id(netbus));
1672
+
1673
+ RTLIL::Wire *wire = module->addWire(wire_name, netbus->Size());
1674
+
1675
+ if (verific_verbose)
1676
+ log(" importing netbus %s as %s.\n", netbus->Name(), wire);
1677
+ wire->start_offset = min(netbus->LeftIndex(), netbus->RightIndex());
1678
+ wire->upto = netbus->IsUp();
1679
+ MapIter mibus;
1680
+ FOREACH_NET_OF_NETBUS(netbus, mibus, net) {
1681
+ if (net)
1682
+ import_attributes(wire->attributes, net, nl, netbus->Size());
1683
+ break;
1684
+ }
1685
+ import_attributes(wire->attributes, netbus, nl, netbus->Size());
1686
+ if (netbus->Size() == 1)
1687
+ wire->set_bool_attribute(ID::single_bit_vector);
1688
+
1689
+ RTLIL::Const initval = Const(State::Sx, GetSize(wire));
1690
+ bool initval_valid = false;
1691
+
1692
+ for (int i = netbus->LeftIndex();; i += netbus->IsUp() ? +1 : -1)
1693
+ {
1694
+ if (netbus->ElementAtIndex(i))
1695
+ {
1696
+ int bitidx = wire->upto ? (wire->width - 1 - (i - wire->start_offset)) : (i - wire->start_offset);
1697
+ net = netbus->ElementAtIndex(i);
1698
+ RTLIL::SigBit bit(wire, bitidx);
1699
+
1700
+ if (init_nets.count(net)) {
1701
+ if (init_nets.at(net) == '0')
1702
+ initval.set(bitidx, State::S0);
1703
+ if (init_nets.at(net) == '1')
1704
+ initval.set(bitidx, State::S1);
1705
+ initval_valid = true;
1706
+ init_nets.erase(net);
1707
+ }
1708
+
1709
+ if (net_map.count(net) == 0)
1710
+ net_map[net] = bit;
1711
+ else
1712
+ module->connect(bit, net_map_at(net));
1713
+ }
1714
+
1715
+ if (i == netbus->RightIndex())
1716
+ break;
1717
+ }
1718
+
1719
+ if (initval_valid)
1720
+ wire->attributes[ID::init] = initval;
1721
+ }
1722
+ else
1723
+ {
1724
+ if (verific_verbose)
1725
+ log(" skipping netbus %s.\n", netbus->Name());
1726
+ }
1727
+
1728
+ SigSpec anyconst_sig;
1729
+ SigSpec anyseq_sig;
1730
+ SigSpec allconst_sig;
1731
+ SigSpec allseq_sig;
1732
+
1733
+ for (int i = netbus->RightIndex();; i += netbus->IsUp() ? -1 : +1) {
1734
+ net = netbus->ElementAtIndex(i);
1735
+ if (net != nullptr && anyconst_nets.count(net)) {
1736
+ anyconst_sig.append(net_map_at(net));
1737
+ anyconst_nets.erase(net);
1738
+ }
1739
+ if (net != nullptr && anyseq_nets.count(net)) {
1740
+ anyseq_sig.append(net_map_at(net));
1741
+ anyseq_nets.erase(net);
1742
+ }
1743
+ if (net != nullptr && allconst_nets.count(net)) {
1744
+ allconst_sig.append(net_map_at(net));
1745
+ allconst_nets.erase(net);
1746
+ }
1747
+ if (net != nullptr && allseq_nets.count(net)) {
1748
+ allseq_sig.append(net_map_at(net));
1749
+ allseq_nets.erase(net);
1750
+ }
1751
+ if (i == netbus->LeftIndex())
1752
+ break;
1753
+ }
1754
+
1755
+ if (GetSize(anyconst_sig))
1756
+ module->connect(anyconst_sig, module->Anyconst(new_verific_id(netbus), GetSize(anyconst_sig)));
1757
+
1758
+ if (GetSize(anyseq_sig))
1759
+ module->connect(anyseq_sig, module->Anyseq(new_verific_id(netbus), GetSize(anyseq_sig)));
1760
+
1761
+ if (GetSize(allconst_sig))
1762
+ module->connect(allconst_sig, module->Allconst(new_verific_id(netbus), GetSize(allconst_sig)));
1763
+
1764
+ if (GetSize(allseq_sig))
1765
+ module->connect(allseq_sig, module->Allseq(new_verific_id(netbus), GetSize(allseq_sig)));
1766
+ }
1767
+
1768
+ for (auto it : init_nets)
1769
+ {
1770
+ Const initval;
1771
+ SigBit bit = net_map_at(it.first);
1772
+ log_assert(bit.wire);
1773
+
1774
+ if (bit.wire->attributes.count(ID::init))
1775
+ initval = bit.wire->attributes.at(ID::init);
1776
+
1777
+ if (GetSize(initval) < GetSize(bit.wire))
1778
+ initval.resize(GetSize(bit.wire), State::Sx);
1779
+
1780
+ if (it.second == '0')
1781
+ initval.set(bit.offset, State::S0);
1782
+ if (it.second == '1')
1783
+ initval.set(bit.offset, State::S1);
1784
+
1785
+ bit.wire->attributes[ID::init] = initval;
1786
+ }
1787
+
1788
+ for (auto net : anyconst_nets)
1789
+ module->connect(net_map_at(net), module->Anyconst(new_verific_id(net)));
1790
+
1791
+ for (auto net : anyseq_nets)
1792
+ module->connect(net_map_at(net), module->Anyseq(new_verific_id(net)));
1793
+
1794
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
1795
+ pool<Instance*> sva_asserts;
1796
+ pool<Instance*> sva_assumes;
1797
+ pool<Instance*> sva_covers;
1798
+ pool<Instance*> sva_triggers;
1799
+ pool<RTLIL::Cell*> past_ffs;
1800
+ #endif
1801
+
1802
+ FOREACH_INSTANCE_OF_NETLIST(nl, mi, inst)
1803
+ {
1804
+ RTLIL::IdString inst_name = module->uniquify(mode_names || inst->IsUserDeclared() ? design->twines().add(RTLIL::escape_id(inst->Name())) : new_verific_id(inst));
1805
+
1806
+ if (verific_verbose)
1807
+ log(" importing cell %s (%s) as %s.\n", inst->Name(), inst->View()->Owner()->Name(), PooledName(design, inst_name).unescape());
1808
+
1809
+ if (mode_verific)
1810
+ goto import_verific_cells;
1811
+
1812
+ if (inst->Type() == PRIM_PWR) {
1813
+ module->connect(net_map_at(inst->GetOutput()), RTLIL::State::S1);
1814
+ continue;
1815
+ }
1816
+
1817
+ if (inst->Type() == PRIM_GND) {
1818
+ module->connect(net_map_at(inst->GetOutput()), RTLIL::State::S0);
1819
+ continue;
1820
+ }
1821
+
1822
+ if (inst->Type() == PRIM_BUF) {
1823
+ auto outnet = inst->GetOutput();
1824
+ if (!any_all_nets.count(outnet))
1825
+ module->addBufGate(inst_name, net_map_at(inst->GetInput()), net_map_at(outnet));
1826
+ continue;
1827
+ }
1828
+
1829
+ if (inst->Type() == PRIM_X) {
1830
+ module->connect(net_map_at(inst->GetOutput()), RTLIL::State::Sx);
1831
+ continue;
1832
+ }
1833
+
1834
+ if (inst->Type() == PRIM_Z) {
1835
+ module->connect(net_map_at(inst->GetOutput()), RTLIL::State::Sz);
1836
+ continue;
1837
+ }
1838
+
1839
+ if (inst->Type() == OPER_READ_PORT)
1840
+ {
1841
+ RTLIL::Memory *memory = module->memories.at(module->twines().find(RTLIL::escape_id(inst->GetInput()->Name())), nullptr);
1842
+ if (!memory)
1843
+ log_error("%sMemory net '%s' missing, possibly no driver, use verific -flatten.\n", announce_src_location(inst), inst->GetInput()->Name());
1844
+
1845
+ int numchunks = int(inst->OutputSize()) / memory->width;
1846
+ int chunksbits = ceil_log2(numchunks);
1847
+
1848
+ for (int i = 0; i < numchunks; i++)
1849
+ {
1850
+ RTLIL::SigSpec addr = {operatorInput1(inst), RTLIL::Const(i, chunksbits)};
1851
+ RTLIL::SigSpec data = operatorOutput(inst).extract(i * memory->width, memory->width);
1852
+
1853
+ RTLIL::Cell *cell = module->addCell(numchunks == 1 ? inst_name :
1854
+ module->twines().add(inst_name, stringf("_%d", i)), ID($memrd));
1855
+ cell->parameters[ID::MEMID] = memory->name.str();
1856
+ cell->parameters[ID::CLK_ENABLE] = false;
1857
+ cell->parameters[ID::CLK_POLARITY] = true;
1858
+ cell->parameters[ID::TRANSPARENT] = false;
1859
+ cell->parameters[ID::ABITS] = GetSize(addr);
1860
+ cell->parameters[ID::WIDTH] = GetSize(data);
1861
+ import_attributes(cell->attributes, inst);
1862
+ cell->setPort(ID::CLK, RTLIL::State::Sx);
1863
+ cell->setPort(ID::EN, RTLIL::State::Sx);
1864
+ cell->setPort(ID::ADDR, addr);
1865
+ cell->setPort(ID::DATA, data);
1866
+ }
1867
+ continue;
1868
+ }
1869
+
1870
+ if (inst->Type() == OPER_WRITE_PORT || inst->Type() == OPER_CLOCKED_WRITE_PORT)
1871
+ {
1872
+ RTLIL::Memory *memory = module->memories.at(module->twines().find(RTLIL::escape_id(inst->GetOutput()->Name())), nullptr);
1873
+ if (!memory)
1874
+ log_error("%sMemory net '%s' missing, possibly no driver, use verific -flatten.\n", announce_src_location(inst), inst->GetInput()->Name());
1875
+ int numchunks = int(inst->Input2Size()) / memory->width;
1876
+ int chunksbits = ceil_log2(numchunks);
1877
+
1878
+ for (int i = 0; i < numchunks; i++)
1879
+ {
1880
+ RTLIL::SigSpec addr = {operatorInput1(inst), RTLIL::Const(i, chunksbits)};
1881
+ RTLIL::SigSpec data = operatorInput2(inst).extract(i * memory->width, memory->width);
1882
+
1883
+ RTLIL::Cell *cell = module->addCell(numchunks == 1 ? inst_name :
1884
+ module->twines().add(inst_name, stringf("_%d", i)), ID($memwr));
1885
+ cell->parameters[ID::MEMID] = memory->name.str();
1886
+ cell->parameters[ID::CLK_ENABLE] = false;
1887
+ cell->parameters[ID::CLK_POLARITY] = true;
1888
+ cell->parameters[ID::PRIORITY] = 0;
1889
+ cell->parameters[ID::ABITS] = GetSize(addr);
1890
+ cell->parameters[ID::WIDTH] = GetSize(data);
1891
+ import_attributes(cell->attributes, inst);
1892
+ cell->setPort(ID::EN, RTLIL::SigSpec(net_map_at(inst->GetControl())).repeat(GetSize(data)));
1893
+ cell->setPort(ID::CLK, RTLIL::State::S0);
1894
+ cell->setPort(ID::ADDR, addr);
1895
+ cell->setPort(ID::DATA, data);
1896
+
1897
+ if (inst->Type() == OPER_CLOCKED_WRITE_PORT) {
1898
+ cell->parameters[ID::CLK_ENABLE] = true;
1899
+ cell->setPort(ID::CLK, net_map_at(inst->GetClock()));
1900
+ }
1901
+ }
1902
+ continue;
1903
+ }
1904
+
1905
+ if (!mode_gates) {
1906
+ if (import_netlist_instance_cells(inst, inst_name))
1907
+ continue;
1908
+ if (inst->IsOperator() && !verific_sva_prims.count(inst->Type()))
1909
+ log_warning("%sUnsupported Verific operator: %s (fallback to gate level implementation provided by verific)\n", announce_src_location(inst), inst->View()->Owner()->Name());
1910
+ } else {
1911
+ if (import_netlist_instance_gates(inst, inst_name))
1912
+ continue;
1913
+ }
1914
+
1915
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
1916
+ if (inst->Type() == PRIM_SVA_ASSERT || inst->Type() == PRIM_SVA_IMMEDIATE_ASSERT)
1917
+ sva_asserts.insert(inst);
1918
+
1919
+ if (inst->Type() == PRIM_SVA_ASSUME || inst->Type() == PRIM_SVA_IMMEDIATE_ASSUME || inst->Type() == PRIM_SVA_RESTRICT)
1920
+ sva_assumes.insert(inst);
1921
+
1922
+ if (inst->Type() == PRIM_SVA_COVER || inst->Type() == PRIM_SVA_IMMEDIATE_COVER)
1923
+ sva_covers.insert(inst);
1924
+
1925
+ if (inst->Type() == PRIM_SVA_TRIGGERED)
1926
+ sva_triggers.insert(inst);
1927
+
1928
+ if (inst->Type() == OPER_SVA_STABLE)
1929
+ {
1930
+ VerificClocking clocking(this, inst->GetInput2Bit(0));
1931
+ log_assert(clocking.disable_sig == State::S0);
1932
+ log_assert(clocking.body_net == nullptr);
1933
+
1934
+ log_assert(inst->Input1Size() == inst->OutputSize());
1935
+
1936
+ unsigned width = inst->Input1Size();
1937
+
1938
+ SigSpec sig_d, sig_dx, sig_qx, sig_o, sig_ox;
1939
+ sig_dx = module->addWire(new_verific_id(inst), width * 2);
1940
+ sig_qx = module->addWire(new_verific_id(inst), width * 2);
1941
+ sig_ox = module->addWire(new_verific_id(inst), width * 2);
1942
+
1943
+ for (int i = int(width)-1; i >= 0; i--){
1944
+ sig_d.append(net_map_at(inst->GetInput1Bit(i)));
1945
+ sig_o.append(net_map_at(inst->GetOutputBit(i)));
1946
+ }
1947
+
1948
+ if (verific_verbose) {
1949
+ for (unsigned i = 0; i < width; i++) {
1950
+ log(" NEX with A=%s, B=0, Y=%s.\n",
1951
+ log_signal(sig_d[i]), log_signal(sig_dx[i]));
1952
+ log(" EQX with A=%s, B=1, Y=%s.\n",
1953
+ log_signal(sig_d[i]), log_signal(sig_dx[i + width]));
1954
+ }
1955
+ log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg",
1956
+ log_signal(sig_dx), log_signal(sig_qx), log_signal(clocking.clock_sig));
1957
+ log(" XNOR with A=%s, B=%s, Y=%s.\n",
1958
+ log_signal(sig_dx), log_signal(sig_qx), log_signal(sig_ox));
1959
+ log(" AND with A=%s, B=%s, Y=%s.\n",
1960
+ log_signal(sig_ox.extract(0, width)), log_signal(sig_ox.extract(width, width)), log_signal(sig_o));
1961
+ }
1962
+
1963
+ for (unsigned i = 0; i < width; i++) {
1964
+ module->addNex(new_verific_id(inst), sig_d[i], State::S0, sig_dx[i]);
1965
+ module->addEqx(new_verific_id(inst), sig_d[i], State::S1, sig_dx[i + width]);
1966
+ }
1967
+
1968
+ Const qx_init = Const(State::S1, width);
1969
+ qx_init.resize(2 * width, State::S0);
1970
+
1971
+ clocking.addDff(new_verific_id(inst), sig_dx, sig_qx, qx_init);
1972
+ module->addXnor(new_verific_id(inst), sig_dx, sig_qx, sig_ox);
1973
+
1974
+ module->addAnd(new_verific_id(inst), sig_ox.extract(0, width), sig_ox.extract(width, width), sig_o);
1975
+
1976
+ if (!mode_keep)
1977
+ continue;
1978
+ }
1979
+
1980
+ if (inst->Type() == PRIM_SVA_STABLE)
1981
+ {
1982
+ VerificClocking clocking(this, inst->GetInput2());
1983
+ log_assert(clocking.disable_sig == State::S0);
1984
+ log_assert(clocking.body_net == nullptr);
1985
+
1986
+ SigSpec sig_d = net_map_at(inst->GetInput1());
1987
+ SigSpec sig_o = net_map_at(inst->GetOutput());
1988
+ SigSpec sig_dx = module->addWire(new_verific_id(inst), 2);
1989
+ SigSpec sig_qx = module->addWire(new_verific_id(inst), 2);
1990
+
1991
+ if (verific_verbose) {
1992
+ log(" NEX with A=%s, B=0, Y=%s.\n",
1993
+ log_signal(sig_d), log_signal(sig_dx[0]));
1994
+ log(" EQX with A=%s, B=1, Y=%s.\n",
1995
+ log_signal(sig_d), log_signal(sig_dx[1]));
1996
+ log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg",
1997
+ log_signal(sig_dx), log_signal(sig_qx), log_signal(clocking.clock_sig));
1998
+ log(" EQ with A=%s, B=%s, Y=%s.\n",
1999
+ log_signal(sig_dx), log_signal(sig_qx), log_signal(sig_o));
2000
+ }
2001
+
2002
+ module->addNex(new_verific_id(inst), sig_d, State::S0, sig_dx[0]);
2003
+ module->addEqx(new_verific_id(inst), sig_d, State::S1, sig_dx[1]);
2004
+
2005
+ clocking.addDff(new_verific_id(inst), sig_dx, sig_qx, Const(1, 2));
2006
+ module->addEq(new_verific_id(inst), sig_dx, sig_qx, sig_o);
2007
+
2008
+ if (!mode_keep)
2009
+ continue;
2010
+ }
2011
+
2012
+ if (inst->Type() == PRIM_SVA_PAST)
2013
+ {
2014
+ VerificClocking clocking(this, inst->GetInput2());
2015
+ log_assert(clocking.disable_sig == State::S0);
2016
+ log_assert(clocking.body_net == nullptr);
2017
+
2018
+ SigBit sig_d = net_map_at(inst->GetInput1());
2019
+ SigBit sig_q = net_map_at(inst->GetOutput());
2020
+
2021
+ if (verific_verbose)
2022
+ log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg",
2023
+ log_signal(sig_d), log_signal(sig_q), log_signal(clocking.clock_sig));
2024
+
2025
+ past_ffs.insert(clocking.addDff(new_verific_id(inst), sig_d, sig_q));
2026
+
2027
+ if (!mode_keep)
2028
+ continue;
2029
+ }
2030
+
2031
+ if ((inst->Type() == PRIM_SVA_ROSE || inst->Type() == PRIM_SVA_FELL))
2032
+ {
2033
+ VerificClocking clocking(this, inst->GetInput2());
2034
+ log_assert(clocking.disable_sig == State::S0);
2035
+ log_assert(clocking.body_net == nullptr);
2036
+
2037
+ SigBit sig_d = net_map_at(inst->GetInput1());
2038
+ SigBit sig_o = net_map_at(inst->GetOutput());
2039
+ SigBit sig_q = module->addWire(new_verific_id(inst));
2040
+ SigBit sig_d_no_x = module->addWire(new_verific_id(inst));
2041
+
2042
+ if (verific_verbose) {
2043
+ log(" EQX with A=%s, B=%d, Y=%s.\n",
2044
+ log_signal(sig_d), inst->Type() == PRIM_SVA_ROSE, log_signal(sig_d_no_x));
2045
+ log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg",
2046
+ log_signal(sig_d_no_x), log_signal(sig_q), log_signal(clocking.clock_sig));
2047
+ log(" EQ with A={%s, %s}, B={0, 1}, Y=%s.\n",
2048
+ log_signal(sig_q), log_signal(sig_d_no_x), log_signal(sig_o));
2049
+ }
2050
+
2051
+ module->addEqx(new_verific_id(inst), sig_d, inst->Type() == PRIM_SVA_ROSE ? State::S1 : State::S0, sig_d_no_x);
2052
+ clocking.addDff(new_verific_id(inst), sig_d_no_x, sig_q, State::S0);
2053
+ module->addEq(new_verific_id(inst), {sig_q, sig_d_no_x}, Const(1, 2), sig_o);
2054
+
2055
+ if (!mode_keep)
2056
+ continue;
2057
+ }
2058
+ #endif
2059
+
2060
+ #ifdef YOSYSHQ_VERIFIC_API_VERSION
2061
+ if (inst->Type() == PRIM_YOSYSHQ_INITSTATE)
2062
+ {
2063
+ if (verific_verbose)
2064
+ log(" adding YosysHQ init state\n");
2065
+ SigBit initstate = module->Initstate(new_verific_id(inst));
2066
+ SigBit sig_o = net_map_at(inst->GetOutput());
2067
+ module->connect(sig_o, initstate);
2068
+
2069
+ if (!mode_keep)
2070
+ continue;
2071
+ }
2072
+ #endif
2073
+
2074
+ if (inst->Type() == PRIM_HDL_ASSERTION)
2075
+ {
2076
+ SigBit cond = net_map_at(inst->GetInput());
2077
+
2078
+ if (verific_verbose)
2079
+ log(" assert condition %s.\n", log_signal(cond));
2080
+
2081
+ Cell *cell = module->addAssert(new_verific_id(inst), cond, State::S1);
2082
+ import_attributes(cell->attributes, inst);
2083
+ continue;
2084
+ }
2085
+
2086
+ if (verific_sva_prims.count(inst->Type()) && inst->Type() != PRIM_SVA_EXPECT)
2087
+ {
2088
+ if (!mode_keep)
2089
+ {
2090
+ if (verific_verbose)
2091
+ log(" skipping SVA cell in non k-mode\n");
2092
+ continue;
2093
+ }
2094
+ }
2095
+ else if (inst->IsPrimitive())
2096
+ {
2097
+ auto msg = stringf("%sUnsupported Verific primitive %s of type %s", announce_src_location(inst), inst->Name(), inst->View()->Owner()->Name());
2098
+ if (!mode_keep)
2099
+ log_error("%s\n", msg);
2100
+ else
2101
+ log_warning("%s\n", msg);
2102
+ }
2103
+
2104
+ import_verific_cells:
2105
+ std::string inst_type = is_blackbox(inst->View()) ? inst->View()->CellBaseName() : inst->View()->Owner()->Name();
2106
+
2107
+ nl_todo[inst_type] = inst->View();
2108
+
2109
+ if (inst->View()->IsOperator() || inst->View()->IsPrimitive()) {
2110
+ inst_type = "$verific$" + inst_type;
2111
+ } else {
2112
+ if (*inst->View()->Name() && !is_blackbox(inst->View())) {
2113
+ inst_type += "(";
2114
+ inst_type += inst->View()->Name();
2115
+ inst_type += ")";
2116
+ }
2117
+ inst_type = "\\" + sha1_if_contain_spaces(inst_type);
2118
+ }
2119
+
2120
+ RTLIL::Cell *cell = module->addCell(inst_name, inst_type);
2121
+ import_attributes(cell->attributes, inst);
2122
+
2123
+ if (inst->IsPrimitive() && mode_keep)
2124
+ cell->attributes[ID::keep] = 1;
2125
+
2126
+ dict<IdString, vector<SigBit>> cell_port_conns;
2127
+
2128
+ if (verific_verbose)
2129
+ log(" ports in verific db:\n");
2130
+
2131
+ const char *param_name ;
2132
+ const char *param_value ;
2133
+ if (is_blackbox(inst->View())) {
2134
+ FOREACH_PARAMETER_OF_INST(inst, mi2, param_name, param_value) {
2135
+ const TypeRange *tr = inst->View()->GetTypeRange(param_name) ;
2136
+ const char* type_name = (tr) ? tr->GetTypeName() : nullptr;
2137
+ cell->setParam(RTLIL::escape_id(param_name), verific_const(type_name, param_value, inst->View()));
2138
+ }
2139
+ }
2140
+
2141
+ FOREACH_PORTREF_OF_INST(inst, mi2, pr) {
2142
+ if (verific_verbose)
2143
+ log(" .%s(%s)\n", pr->GetPort()->Name(), pr->GetNet()->Name());
2144
+ const char *port_name = pr->GetPort()->Name();
2145
+ int port_offset = 0;
2146
+ if (pr->GetPort()->Bus()) {
2147
+ port_name = pr->GetPort()->Bus()->Name();
2148
+ int msb_index = pr->GetPort()->Bus()->LeftIndex();
2149
+ int lsb_index = pr->GetPort()->Bus()->RightIndex();
2150
+ int index_of_port = pr->GetPort()->Bus()->IndexOf(pr->GetPort());
2151
+ port_offset = index_of_port - min(msb_index, lsb_index);
2152
+ // In cases where the msb order is flipped we need to make sure
2153
+ // that the indices match LSB = 0 order to match the std::vector
2154
+ // to SigSpec LSB = 0 precondition.
2155
+ if (lsb_index > msb_index) {
2156
+ port_offset = abs(port_offset - (lsb_index - min(msb_index, lsb_index)));
2157
+ }
2158
+ }
2159
+ IdString port_name_id = module->twines().add(RTLIL::escape_id(port_name));
2160
+ auto &sigvec = cell_port_conns[port_name_id];
2161
+ if (GetSize(sigvec) <= port_offset) {
2162
+ SigSpec zwires = module->addWire(new_verific_id(inst), port_offset+1-GetSize(sigvec));
2163
+ for (auto bit : zwires)
2164
+ sigvec.push_back(bit);
2165
+ }
2166
+ // fixing issue where undriven interface nets get driver conflicts - issue 6409
2167
+ Net *port_net = pr->GetPort()->GetNet();
2168
+ bool unused_output = !is_blackbox(inst->View()) && pr->IsOutput() && port_net && !port_net->Driver();
2169
+ if (!unused_output) {
2170
+ sigvec[port_offset] = net_map_at(pr->GetNet());
2171
+ }
2172
+ }
2173
+
2174
+ if (verific_verbose)
2175
+ log(" ports in yosys db:\n");
2176
+
2177
+ for (auto &it : cell_port_conns) {
2178
+ if (verific_verbose)
2179
+ log(" .%s(%s)\n", PooledName(module, it.first).unescape(), log_signal(it.second));
2180
+ cell->setPort(it.first, it.second);
2181
+ }
2182
+ }
2183
+
2184
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
2185
+ if (!mode_nosva)
2186
+ {
2187
+ for (auto inst : sva_asserts) {
2188
+ if (mode_autocover)
2189
+ verific_import_sva_cover(this, inst);
2190
+ verific_import_sva_assert(this, inst);
2191
+ }
2192
+
2193
+ for (auto inst : sva_assumes)
2194
+ verific_import_sva_assume(this, inst);
2195
+
2196
+ for (auto inst : sva_covers)
2197
+ verific_import_sva_cover(this, inst);
2198
+
2199
+ for (auto inst : sva_triggers)
2200
+ verific_import_sva_trigger(this, inst);
2201
+
2202
+ merge_past_ffs(past_ffs);
2203
+ }
2204
+ #endif
2205
+
2206
+ if (!mode_fullinit)
2207
+ {
2208
+ pool<SigBit> non_ff_bits;
2209
+ CellTypes ff_types;
2210
+
2211
+ ff_types.setup_internals_ff();
2212
+ ff_types.setup_stdcells_mem();
2213
+
2214
+ for (auto cell : module->cells())
2215
+ {
2216
+ if (ff_types.cell_known(cell->type))
2217
+ continue;
2218
+
2219
+ for (auto conn : cell->connections())
2220
+ {
2221
+ if (!cell->output(conn.first))
2222
+ continue;
2223
+
2224
+ for (auto bit : conn.second)
2225
+ if (bit.wire != nullptr)
2226
+ non_ff_bits.insert(bit);
2227
+ }
2228
+ }
2229
+
2230
+ for (auto wire : module->wires())
2231
+ {
2232
+ if (!wire->attributes.count(ID::init))
2233
+ continue;
2234
+
2235
+ Const &initval = wire->attributes.at(ID::init);
2236
+ for (int i = 0; i < GetSize(initval); i++)
2237
+ {
2238
+ if (initval[i] != State::S0 && initval[i] != State::S1)
2239
+ continue;
2240
+
2241
+ if (non_ff_bits.count(SigBit(wire, i)))
2242
+ initval.set(i, State::Sx);
2243
+ }
2244
+
2245
+ if (wire->port_input) {
2246
+ wire->attributes[ID::defaultvalue] = Const(initval);
2247
+ wire->attributes.erase(ID::init);
2248
+ } else if (initval.is_fully_undef())
2249
+ wire->attributes.erase(ID::init);
2250
+ }
2251
+ }
2252
+
2253
+ if (num_sva_continue) {
2254
+ log_warning("Encountered %d items containing unsupported SVA!\n", num_sva_continue);
2255
+ log_warning("Unsupported SVA imported as 'x and marked using the `unsupported_sva' attribute due to -sva-continue-on-err.\n");
2256
+ }
2257
+ num_sva_continue = 0;
2258
+ }
2259
+
2260
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verific/verific_importer.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef VERIFIC_IMPORTER_H
21
+ #define VERIFIC_IMPORTER_H
22
+
23
+ #ifdef YOSYS_ENABLE_VERIFIC
24
+
25
+ #include "kernel/yosys.h"
26
+
27
+ #include "DataBase.h"
28
+
29
+ YOSYS_NAMESPACE_BEGIN
30
+
31
+ struct VerificImporter
32
+ {
33
+ private:
34
+ void recurse_mem_dimensions(RTLIL::Module *module, RTLIL::Memory *memory, Verific::Net *net, const char *&ascii_initdata, int max_bits_in_addr, const RTLIL::SigSpec &prefix, Verific::TypeRange *typeRange = nullptr);
35
+ public:
36
+ RTLIL::Module *module;
37
+ Verific::Netlist *netlist;
38
+
39
+ std::map<Verific::Net*, RTLIL::SigBit> net_map;
40
+ std::map<Verific::Net*, Verific::Net*> sva_posedge_map;
41
+ pool<Verific::Net*> any_all_nets;
42
+
43
+ bool mode_gates, mode_keep, mode_nosva, mode_sva_continue, mode_names, mode_verific;
44
+ bool mode_autocover, mode_fullinit;
45
+
46
+ int num_sva_continue = 0;
47
+
48
+ VerificImporter(bool mode_gates, bool mode_keep, bool mode_nosva, bool mode_sva_continue, bool mode_names, bool mode_verific, bool mode_autocover, bool mode_fullinit);
49
+
50
+ RTLIL::SigBit net_map_at(Verific::Net *net);
51
+
52
+ RTLIL::IdString new_verific_id(Verific::DesignObj *obj);
53
+ void import_attributes(dict<RTLIL::IdString, RTLIL::Const> &attributes, Verific::DesignObj *obj, Verific::Netlist *nl = nullptr, int wire_width_hint = -1);
54
+
55
+ RTLIL::SigBit netToSigBit(Verific::Net *net);
56
+ RTLIL::SigSpec operatorInput(Verific::Instance *inst);
57
+ RTLIL::SigSpec operatorInput1(Verific::Instance *inst);
58
+ RTLIL::SigSpec operatorInput2(Verific::Instance *inst);
59
+ RTLIL::SigSpec operatorInport(Verific::Instance *inst, const char *portname);
60
+ RTLIL::SigSpec operatorInportCase(Verific::Instance *inst, const char *portname);
61
+ RTLIL::SigSpec operatorOutput(Verific::Instance *inst, const pool<Verific::Net*> *any_all_nets = nullptr);
62
+
63
+ bool import_netlist_instance_gates(Verific::Instance *inst, RTLIL::IdString inst_name);
64
+ bool import_netlist_instance_cells(Verific::Instance *inst, RTLIL::IdString inst_name);
65
+
66
+ void merge_past_ffs_clock(pool<RTLIL::Cell*> &candidates, SigBit clock, bool clock_pol);
67
+ void merge_past_ffs(pool<RTLIL::Cell*> &candidates);
68
+
69
+ void import_netlist(RTLIL::Design *design, Verific::Netlist *nl, std::map<std::string,Verific::Netlist*> &nl_todo, bool norename = false);
70
+ };
71
+
72
+ YOSYS_NAMESPACE_END
73
+
74
+ #endif
75
+ #endif
chips/yosys/frontends/verific/verific_pass.cc ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/yosys.h"
21
+
22
+ #include "frontends/verific/verific.h"
23
+ #include "frontends/verific/verific_command.h"
24
+
25
+ #ifdef YOSYS_ENABLE_VERIFIC
26
+
27
+ #ifdef __clang__
28
+ #pragma clang diagnostic push
29
+ #pragma clang diagnostic ignored "-Woverloaded-virtual"
30
+ #endif
31
+
32
+ #include "Message.h"
33
+
34
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
35
+ #include "VerificExtensions.h"
36
+ #endif
37
+
38
+ #ifdef __clang__
39
+ #pragma clang diagnostic pop
40
+ #endif
41
+
42
+ #ifdef VERIFIC_NAMESPACE
43
+ using namespace Verific;
44
+ #endif
45
+
46
+ #endif
47
+
48
+ USING_YOSYS_NAMESPACE
49
+ PRIVATE_NAMESPACE_BEGIN
50
+
51
+ struct VerificPass : public Pass {
52
+ VerificPass() : Pass("verific", "load Verilog and VHDL designs using Verific") { }
53
+
54
+ #ifdef YOSYSHQ_VERIFIC_EXTENSIONS
55
+ void on_register() override { VerificExtensions::Reset(); }
56
+ #endif
57
+
58
+ void help() override
59
+ {
60
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
61
+ log("\n");
62
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
63
+ log(" verific {-vlog95|-vlog2k|-sv2005|-sv2009|-sv2012|\n");
64
+ log(" -sv2017|-sv2023|-sv} <verilog-file>..\n");
65
+ log("\n");
66
+ log("Load the specified Verilog/SystemVerilog files into Verific.\n");
67
+ log("Note that -sv option will use latest supported SystemVerilog standard.\n");
68
+ log("\n");
69
+ log("All files specified in one call to this command are one compilation unit.\n");
70
+ log("Files passed to different calls to this command are treated as belonging to\n");
71
+ log("different compilation units.\n");
72
+ log("\n");
73
+ log("Additional -D<macro>[=<value>] options may be added after the option indicating\n");
74
+ log("the language version (and before file names) to set additional verilog defines.\n");
75
+ log("The macros YOSYS, SYNTHESIS, and VERIFIC are defined implicitly.\n");
76
+ log("\n");
77
+ log("\n");
78
+ log(" verific -formal <verilog-file>..\n");
79
+ log("\n");
80
+ log("Like -sv, but define FORMAL instead of SYNTHESIS.\n");
81
+ log("\n");
82
+ log("\n");
83
+ #endif
84
+ #ifdef VERIFIC_VHDL_SUPPORT
85
+ log(" verific {-vhdl87|-vhdl93|-vhdl2k|-vhdl2008|-vhdl2019|-vhdl} <vhdl-file>..\n");
86
+ log("\n");
87
+ log("Load the specified VHDL files into Verific.\n");
88
+ log("\n");
89
+ log("\n");
90
+ #endif
91
+ #ifdef VERIFIC_EDIF_SUPPORT
92
+ log(" verific {-edif} <edif-file>..\n");
93
+ log("\n");
94
+ log("Load the specified EDIF files into Verific.\n");
95
+ log("\n");
96
+ log("\n");
97
+ #endif
98
+ #ifdef VERIFIC_LIBERTY_SUPPORT
99
+ log(" verific {-liberty} <liberty-file>..\n");
100
+ log("\n");
101
+ log("Load the specified Liberty files into Verific.\n");
102
+ log("Default library when -work is not present is one specified in liberty file.\n");
103
+ log("To use from SystemVerilog or VHDL use -L to specify liberty library.\n");
104
+ log("\n");
105
+ log(" -lib\n");
106
+ log(" only create empty blackbox modules\n");
107
+ log("\n");
108
+ log("\n");
109
+ #endif
110
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
111
+ log(" verific {-f|-F} [-vlog95|-vlog2k|-sv2005|-sv2009|\n");
112
+ #ifdef VERIFIC_VHDL_SUPPORT
113
+ log(" -vhdl87|-vhdl93|-vhdl2k|-vhdl2008|-vhdl2019|-vhdl|\n");
114
+ #endif
115
+ log(" -sv2012|-sv2017|-sv2023|-sv|-formal] <command-file>\n");
116
+ log("\n");
117
+ log("Load and execute the specified command file.\n");
118
+ log("Override verilog parsing mode can be set.\n");
119
+ log("The macros YOSYS, SYNTHESIS/FORMAL, and VERIFIC are defined implicitly.\n");
120
+ log("\n");
121
+ log("Command file parser supports following commands in file:\n");
122
+ log(" +define+<MACRO>=<VALUE> - defines macro\n");
123
+ log(" -u - upper case all identifier (makes Verilog parser\n");
124
+ log(" case insensitive)\n");
125
+ log(" -v <filepath> - register library name (file)\n");
126
+ log(" -y <filepath> - register library name (directory)\n");
127
+ log(" +incdir+<filepath> - specify include dir\n");
128
+ log(" +libext+<filepath> - specify library extension\n");
129
+ log(" +liborder+<id> - add library in ordered list\n");
130
+ log(" +librescan - unresolved modules will be always searched\n");
131
+ log(" starting with the first library specified\n");
132
+ log(" by -y/-v options.\n");
133
+ log(" -f/-file <filepath> - nested -f option\n");
134
+ log(" -F <filepath> - nested -F option (relative path)\n");
135
+ log(" parse files:\n");
136
+ log(" <filepath>\n");
137
+ log(" +systemverilogext+<filepath>\n");
138
+ log(" +verilog1995ext+<filepath>\n");
139
+ log(" +verilog2001ext+<filepath>\n");
140
+ log("\n");
141
+ log(" analysis mode:\n");
142
+ log(" -ams\n");
143
+ log(" +v2k\n");
144
+ log(" -sverilog\n");
145
+ log("\n");
146
+ log("\n");
147
+ #endif
148
+ log(" verific [-work <libname>] {-sv|-vhdl|...} <hdl-file>\n");
149
+ log("\n");
150
+ log("Load the specified Verilog/SystemVerilog/VHDL file into the specified library.\n");
151
+ log("(default library when -work is not present: \"work\")\n");
152
+ log("\n");
153
+ log("\n");
154
+ log(" verific [-L <libname>] {-sv|-vhdl|...} <hdl-file>\n");
155
+ log("\n");
156
+ log("Look up external definitions in the specified library.\n");
157
+ log("(-L may be used more than once)\n");
158
+ log("\n");
159
+ log("\n");
160
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
161
+ log(" verific -vlog-incdir <directory>..\n");
162
+ log("\n");
163
+ log("Add Verilog include directories.\n");
164
+ log("\n");
165
+ log("\n");
166
+ log(" verific -vlog-libdir <directory>..\n");
167
+ log("\n");
168
+ log("Add Verilog library directories. Verific will search in this directories to\n");
169
+ log("find undefined modules.\n");
170
+ log("\n");
171
+ log("\n");
172
+ log(" verific -vlog-libext <extension>..\n");
173
+ log("\n");
174
+ log("Add Verilog library extensions, used when searching in library directories.\n");
175
+ log("\n");
176
+ log("\n");
177
+ log(" verific -vlog-define <macro>[=<value>]..\n");
178
+ log("\n");
179
+ log("Add Verilog defines.\n");
180
+ log("\n");
181
+ log("\n");
182
+ log(" verific -vlog-undef <macro>..\n");
183
+ log("\n");
184
+ log("Remove Verilog defines previously set with -vlog-define.\n");
185
+ log("\n");
186
+ log("\n");
187
+ #endif
188
+ log(" verific -set-error <msg_id>..\n");
189
+ log(" verific -set-warning <msg_id>..\n");
190
+ log(" verific -set-info <msg_id>..\n");
191
+ log(" verific -set-ignore <msg_id>..\n");
192
+ log("\n");
193
+ log("Set message severity. <msg_id> is the string in square brackets when a message\n");
194
+ log("is printed, such as VERI-1209.\n");
195
+ log("Also errors, warnings, infos and comments could be used to set new severity for\n");
196
+ log("all messages of certain type.\n");
197
+ log("\n");
198
+ log("\n");
199
+ log(" verific -cleanup\n");
200
+ log("\n");
201
+ log("Discard all files read so far without importing them and reset the internal\n");
202
+ log("state of Verific.\n");
203
+ log("\n");
204
+ log("\n");
205
+ log(" verific -import [options] <top>..\n");
206
+ log("\n");
207
+ log("Elaborate the design for the specified top modules or configurations, import to\n");
208
+ log("Yosys and reset the internal state of Verific.\n");
209
+ log("\n");
210
+ log("Import options:\n");
211
+ log("\n");
212
+ log(" -all\n");
213
+ log(" Elaborate all modules, not just the hierarchy below the given top\n");
214
+ log(" modules. With this option the list of modules to import is optional.\n");
215
+ log("\n");
216
+ log(" -gates\n");
217
+ log(" Create a gate-level netlist.\n");
218
+ log("\n");
219
+ log(" -flatten\n");
220
+ log(" Flatten the design in Verific before importing.\n");
221
+ log("\n");
222
+ log(" -extnets\n");
223
+ log(" Resolve references to external nets by adding module ports as needed.\n");
224
+ log("\n");
225
+ log(" -no-split-complex-ports\n");
226
+ log(" Complex ports (structs or arrays) are not split and remain packed as a single port.\n");
227
+ log("\n");
228
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
229
+ log(" -autocover\n");
230
+ log(" Generate automatic cover statements for all asserts\n");
231
+ log("\n");
232
+ #endif
233
+ log(" -fullinit\n");
234
+ log(" Keep all register initializations, even those for non-FF registers.\n");
235
+ log("\n");
236
+ log(" -cells\n");
237
+ log(" Import all cell definitions from Verific loaded libraries even if they are\n");
238
+ log(" unused in design. Useful with \"-edif\" and \"-liberty\" option.\n");
239
+ log("\n");
240
+ log(" -chparam name value \n");
241
+ log(" Elaborate the specified top modules (all modules when -all given) using\n");
242
+ log(" this parameter value. Modules on which this parameter does not exist will\n");
243
+ log(" cause Verific to produce a VERI-1928 or VHDL-1676 message. This option\n");
244
+ log(" can be specified multiple times to override multiple parameters.\n");
245
+ log(" String values must be passed in double quotes (\").\n");
246
+ log("\n");
247
+ log(" -v, -vv\n");
248
+ log(" Verbose log messages. (-vv is even more verbose than -v.)\n");
249
+ log("\n");
250
+ log(" -pp <filename>\n");
251
+ log(" Pretty print design after elaboration to specified file.\n");
252
+ log("\n");
253
+ log("The following additional import options are useful for debugging the Verific\n");
254
+ log("bindings (for Yosys and/or Verific developers):\n");
255
+ log("\n");
256
+ log(" -k\n");
257
+ log(" Keep going after an unsupported verific primitive is found. The\n");
258
+ log(" unsupported primitive is added as blackbox module to the design.\n");
259
+ log(" This will also add all SVA related cells to the design parallel to\n");
260
+ log(" the checker logic inferred by it.\n");
261
+ log("\n");
262
+ log(" -V\n");
263
+ log(" Import Verific netlist as-is without translating to Yosys cell types. \n");
264
+ log("\n");
265
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
266
+ log(" -nosva\n");
267
+ log(" Ignore SVA properties, do not infer checker logic.\n");
268
+ log("\n");
269
+ log(" -sva-continue-on-err\n");
270
+ log(" Turns unsupported SVA from an error into a warning. Properties are imported\n");
271
+ log(" with their trigger condition replaced with 'x and with an `unsupported_sva'\n");
272
+ log(" attribute to produce a later error in SBY if they remain in the design.\n");
273
+ log("\n");
274
+ log(" -L <int>\n");
275
+ log(" Maximum number of ctrl bits for SVA checker FSMs (default=16).\n");
276
+ log("\n");
277
+ #endif
278
+ log(" -n\n");
279
+ log(" Keep all Verific names on instances and nets. By default only\n");
280
+ log(" user-declared names are preserved.\n");
281
+ log("\n");
282
+ log(" -d <dump_file>\n");
283
+ log(" Dump the Verific netlist as a verilog file.\n");
284
+ log("\n");
285
+ log("\n");
286
+ log(" verific [-work <libname>] -pp [options] <filename> [<module>]..\n");
287
+ log("\n");
288
+ log("Pretty print design (or just module) to the specified file from the\n");
289
+ log("specified library. (default library when -work is not present: \"work\")\n");
290
+ log("\n");
291
+ log("Pretty print options:\n");
292
+ log("\n");
293
+ log(" -verilog\n");
294
+ log(" Save output for Verilog/SystemVerilog design modules (default).\n");
295
+ log("\n");
296
+ log(" -vhdl\n");
297
+ log(" Save output for VHDL design units.\n");
298
+ log("\n");
299
+ log("\n");
300
+ log(" verific -cfg [<name> [<value>]]\n");
301
+ log("\n");
302
+ log("Get/set Verific runtime flags.\n");
303
+ log("\n");
304
+ log("\n");
305
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
306
+ log(" verific -target <target> [-family <family>]]\n");
307
+ log("\n");
308
+ log("Loads required cell definitions for specified <target> and <family>.\n");
309
+ log("\n");
310
+ log("\n");
311
+ #endif
312
+ #if defined(YOSYS_ENABLE_VERIFIC) and defined(YOSYSHQ_VERIFIC_EXTENSIONS)
313
+ VerificExtensions::Help();
314
+ #endif
315
+ log("Use YosysHQ Tabby CAD Suite if you need Yosys+Verific.\n");
316
+ log("https://www.yosyshq.com/\n");
317
+ log("\n");
318
+ log("Contact office@yosyshq.com for free evaluation\n");
319
+ log("binaries of YosysHQ Tabby CAD Suite.\n");
320
+ log("\n");
321
+ }
322
+ #ifdef YOSYS_ENABLE_VERIFIC
323
+ void log_release()
324
+ {
325
+ const char *release_str = Message::ReleaseString();
326
+ time_t release_time = Message::ReleaseDate();
327
+ char *release_tmstr = ctime(&release_time);
328
+
329
+ if (release_str == nullptr)
330
+ release_str = "(no release string)";
331
+
332
+ for (char *p = release_tmstr; *p; p++)
333
+ if (*p == '\n') *p = 0;
334
+
335
+ log("Built with Verific %s, released at %s.\n", release_str, release_tmstr);
336
+ }
337
+
338
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
339
+ {
340
+ if (check_noverific_env())
341
+ log_cmd_error("This version of Yosys is built without Verific support.\n"
342
+ "\n"
343
+ "Use YosysHQ Tabby CAD Suite if you need Yosys+Verific.\n"
344
+ "https://www.yosyshq.com/\n"
345
+ "\n"
346
+ "Contact office@yosyshq.com for free evaluation\n"
347
+ "binaries of YosysHQ Tabby CAD Suite.\n");
348
+
349
+ log_header(design, "Executing VERIFIC (loading SystemVerilog and VHDL designs using Verific).\n");
350
+
351
+ std::unique_ptr<VerificSession> ending_session = {};
352
+ {
353
+ VerificCommand command(*this, args, design);
354
+
355
+ if (command.mode == "-cleanup") {
356
+ (void)VerificSession::deferred_end(design);
357
+ return;
358
+ }
359
+
360
+ if (command.mode == "-import") {
361
+ ending_session = VerificSession::deferred_end(design);
362
+ if (!ending_session)
363
+ log_cmd_error("Nothing was read into Verific for this design.\n");
364
+ } else {
365
+ VerificSession::begin(design);
366
+ }
367
+
368
+ verific_setup();
369
+ verific_verbose = 0;
370
+ verific_sva_fsm_limit = 16;
371
+ log_release();
372
+ command.run();
373
+ }
374
+
375
+ if (!verific_error_msg.empty())
376
+ log_error("%s\n", verific_error_msg);
377
+ }
378
+ #else /* YOSYS_ENABLE_VERIFIC */
379
+ void execute(std::vector<std::string>, RTLIL::Design *) override {
380
+ log_cmd_error("This version of Yosys is built without Verific support.\n"
381
+ "\n"
382
+ "Use YosysHQ Tabby CAD Suite if you need Yosys+Verific.\n"
383
+ "https://www.yosyshq.com/\n"
384
+ "\n"
385
+ "Contact office@yosyshq.com for free evaluation\n"
386
+ "binaries of YosysHQ Tabby CAD Suite.\n");
387
+ }
388
+ #endif
389
+ } VerificPass;
390
+
391
+ PRIVATE_NAMESPACE_END
chips/yosys/frontends/verific/verificsva.cc ADDED
@@ -0,0 +1,1949 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+
21
+ // Currently supported SVA sequence and property syntax:
22
+ // https://yosyshq.readthedocs.io/projects/sby/en/latest/verific.html
23
+ //
24
+ // Next gen property syntax:
25
+ // basic_property
26
+ // [antecedent_condition] property
27
+ // [antecedent_condition] always.. property
28
+ // [antecedent_condition] eventually.. basic_property
29
+ // [antecedent_condition] property until.. expression
30
+ // [antecedent_condition] basic_property until.. basic_property (assert/assume only)
31
+ //
32
+ // antecedent_condition:
33
+ // sequence |->
34
+ // sequence |=>
35
+ //
36
+ // basic_property:
37
+ // sequence
38
+ // not basic_property
39
+ // nexttime basic_property
40
+ // nexttime[N] basic_property
41
+ // sequence #-# basic_property
42
+ // sequence #=# basic_property
43
+ // basic_property or basic_property (cover only)
44
+ // basic_property and basic_property (assert/assume only)
45
+ // basic_property implies basic_property
46
+ // basic_property iff basic_property
47
+ //
48
+ // sequence:
49
+ // expression
50
+ // sequence ##N sequence
51
+ // sequence ##[*] sequence
52
+ // sequence ##[+] sequence
53
+ // sequence ##[N:M] sequence
54
+ // sequence ##[N:$] sequence
55
+ // expression [*]
56
+ // expression [+]
57
+ // expression [*N]
58
+ // expression [*N:M]
59
+ // expression [*N:$]
60
+ // sequence or sequence
61
+ // sequence and sequence
62
+ // expression throughout sequence
63
+ // sequence intersect sequence
64
+ // sequence within sequence
65
+ // first_match( sequence )
66
+ // expression [=N]
67
+ // expression [=N:M]
68
+ // expression [=N:$]
69
+ // expression [->N]
70
+ // expression [->N:M]
71
+ // expression [->N:$]
72
+
73
+
74
+ #include "kernel/yosys.h"
75
+ #include "frontends/verific/verific.h"
76
+
77
+ USING_YOSYS_NAMESPACE
78
+
79
+ #ifdef VERIFIC_NAMESPACE
80
+ using namespace Verific;
81
+ #endif
82
+
83
+ #ifdef VERIFIC_SYSTEMVERILOG_SUPPORT
84
+ PRIVATE_NAMESPACE_BEGIN
85
+
86
+ // Non-deterministic FSM
87
+ struct SvaNFsmNode
88
+ {
89
+ // Edge: Activate the target node if ctrl signal is true, consumes clock cycle
90
+ // Link: Activate the target node if ctrl signal is true, doesn't consume clock cycle
91
+ vector<pair<int, SigBit>> edges, links;
92
+ bool is_cond_node;
93
+ };
94
+
95
+ // Non-deterministic FSM after resolving links
96
+ struct SvaUFsmNode
97
+ {
98
+ // Edge: Activate the target node if all bits in ctrl signal are true, consumes clock cycle
99
+ // Accept: This node functions as an accept node if all bits in ctrl signal are true
100
+ vector<pair<int, SigSpec>> edges;
101
+ vector<SigSpec> accept, cond;
102
+ bool reachable;
103
+ };
104
+
105
+ // Deterministic FSM
106
+ struct SvaDFsmNode
107
+ {
108
+ // A DFSM state corresponds to a set of NFSM states. We represent DFSM states as sorted vectors
109
+ // of NFSM state node ids. Edge/accept controls are constants matched against the ctrl sigspec.
110
+ SigSpec ctrl;
111
+ vector<pair<vector<int>, Const>> edges;
112
+ vector<Const> accept, reject;
113
+
114
+ // additional temp data for getReject()
115
+ Wire *ffoutwire;
116
+ SigBit statesig;
117
+ SigSpec nextstate;
118
+
119
+ // additional temp data for getDFsm()
120
+ int outnode;
121
+ };
122
+
123
+ struct SvaFsm
124
+ {
125
+ Module *module;
126
+ VerificClocking clocking;
127
+ std::function<void (std::string)> parser_error;
128
+
129
+ SigBit trigger_sig = State::S1, disable_sig;
130
+ SigBit throughout_sig = State::S1;
131
+ bool in_cond_mode = false;
132
+
133
+ vector<SigBit> disable_stack;
134
+ vector<SigBit> throughout_stack;
135
+
136
+ int startNode, acceptNode, condNode;
137
+ vector<SvaNFsmNode> nodes;
138
+
139
+ vector<SvaUFsmNode> unodes;
140
+ dict<vector<int>, SvaDFsmNode> dnodes;
141
+ dict<pair<SigSpec, SigSpec>, SigBit> cond_eq_cache;
142
+ bool materialized = false;
143
+
144
+ SigBit final_accept_sig = State::Sx;
145
+ SigBit final_reject_sig = State::Sx;
146
+
147
+ SvaFsm(const VerificClocking &clking, SigBit trig = State::S1)
148
+ {
149
+ module = clking.module;
150
+ clocking = clking;
151
+ trigger_sig = trig;
152
+ parser_error = [](std::string msg){ log_error("%s", msg); };
153
+
154
+ startNode = createNode();
155
+ acceptNode = createNode();
156
+
157
+ in_cond_mode = true;
158
+ condNode = createNode();
159
+ in_cond_mode = false;
160
+ }
161
+
162
+ void pushDisable(SigBit sig)
163
+ {
164
+ log_assert(!materialized);
165
+
166
+ disable_stack.push_back(disable_sig);
167
+
168
+ if (disable_sig == State::S0)
169
+ disable_sig = sig;
170
+ else
171
+ disable_sig = module->Or(NEW_ID, disable_sig, sig);
172
+ }
173
+
174
+ void popDisable()
175
+ {
176
+ log_assert(!materialized);
177
+ log_assert(!disable_stack.empty());
178
+
179
+ disable_sig = disable_stack.back();
180
+ disable_stack.pop_back();
181
+ }
182
+
183
+ void pushThroughout(SigBit sig)
184
+ {
185
+ log_assert(!materialized);
186
+
187
+ throughout_stack.push_back(throughout_sig);
188
+
189
+ if (throughout_sig == State::S1)
190
+ throughout_sig = sig;
191
+ else
192
+ throughout_sig = module->And(NEW_ID, throughout_sig, sig);
193
+ }
194
+
195
+ void popThroughout()
196
+ {
197
+ log_assert(!materialized);
198
+ log_assert(!throughout_stack.empty());
199
+
200
+ throughout_sig = throughout_stack.back();
201
+ throughout_stack.pop_back();
202
+ }
203
+
204
+ int createNode(int link_node = -1)
205
+ {
206
+ log_assert(!materialized);
207
+
208
+ int idx = GetSize(nodes);
209
+ nodes.push_back(SvaNFsmNode());
210
+ nodes.back().is_cond_node = in_cond_mode;
211
+ if (link_node >= 0)
212
+ createLink(link_node, idx);
213
+ return idx;
214
+ }
215
+
216
+ int createStartNode()
217
+ {
218
+ return createNode(startNode);
219
+ }
220
+
221
+ void createEdge(int from_node, int to_node, SigBit ctrl = State::S1)
222
+ {
223
+ log_assert(!materialized);
224
+ log_assert(0 <= from_node && from_node < GetSize(nodes));
225
+ log_assert(0 <= to_node && to_node < GetSize(nodes));
226
+ log_assert(from_node != acceptNode);
227
+ log_assert(to_node != acceptNode);
228
+ log_assert(from_node != condNode);
229
+ log_assert(to_node != condNode);
230
+ log_assert(to_node != startNode);
231
+
232
+ if (from_node != startNode)
233
+ log_assert(nodes.at(from_node).is_cond_node == nodes.at(to_node).is_cond_node);
234
+
235
+ if (throughout_sig != State::S1) {
236
+ if (ctrl != State::S1)
237
+ ctrl = module->And(NEW_ID, throughout_sig, ctrl);
238
+ else
239
+ ctrl = throughout_sig;
240
+ }
241
+
242
+ nodes[from_node].edges.push_back(make_pair(to_node, ctrl));
243
+ }
244
+
245
+ void createLink(int from_node, int to_node, SigBit ctrl = State::S1)
246
+ {
247
+ log_assert(!materialized);
248
+ log_assert(0 <= from_node && from_node < GetSize(nodes));
249
+ log_assert(0 <= to_node && to_node < GetSize(nodes));
250
+ log_assert(from_node != acceptNode);
251
+ log_assert(from_node != condNode);
252
+ log_assert(to_node != startNode);
253
+
254
+ if (from_node != startNode)
255
+ log_assert(nodes.at(from_node).is_cond_node == nodes.at(to_node).is_cond_node);
256
+
257
+ if (throughout_sig != State::S1) {
258
+ if (ctrl != State::S1)
259
+ ctrl = module->And(NEW_ID, throughout_sig, ctrl);
260
+ else
261
+ ctrl = throughout_sig;
262
+ }
263
+
264
+ nodes[from_node].links.push_back(make_pair(to_node, ctrl));
265
+ }
266
+
267
+ void make_link_order(vector<int> &order, int node, int min)
268
+ {
269
+ order[node] = std::max(order[node], min);
270
+ for (auto &it : nodes[node].links)
271
+ make_link_order(order, it.first, order[node]+1);
272
+ }
273
+
274
+ // ----------------------------------------------------
275
+ // Generating NFSM circuit to acquire accept signal
276
+
277
+ SigBit getAccept()
278
+ {
279
+ log_assert(!materialized);
280
+ materialized = true;
281
+
282
+ vector<Wire*> state_wire(GetSize(nodes));
283
+ vector<SigBit> state_sig(GetSize(nodes));
284
+ vector<SigBit> next_state_sig(GetSize(nodes));
285
+
286
+ // Create state signals
287
+
288
+ {
289
+ SigBit not_disable = State::S1;
290
+
291
+ if (disable_sig != State::S0)
292
+ not_disable = module->Not(NEW_ID, disable_sig);
293
+
294
+ for (int i = 0; i < GetSize(nodes); i++)
295
+ {
296
+ Wire *w = module->addWire(NEW_ID);
297
+ state_wire[i] = w;
298
+ state_sig[i] = w;
299
+
300
+ if (i == startNode)
301
+ state_sig[i] = module->Or(NEW_ID, state_sig[i], trigger_sig);
302
+
303
+ if (disable_sig != State::S0)
304
+ state_sig[i] = module->And(NEW_ID, state_sig[i], not_disable);
305
+ }
306
+ }
307
+
308
+ // Follow Links
309
+
310
+ {
311
+ vector<int> node_order(GetSize(nodes));
312
+ vector<vector<int>> order_to_nodes;
313
+
314
+ for (int i = 0; i < GetSize(nodes); i++)
315
+ make_link_order(node_order, i, 0);
316
+
317
+ for (int i = 0; i < GetSize(nodes); i++) {
318
+ if (node_order[i] >= GetSize(order_to_nodes))
319
+ order_to_nodes.resize(node_order[i]+1);
320
+ order_to_nodes[node_order[i]].push_back(i);
321
+ }
322
+
323
+ for (int order = 0; order < GetSize(order_to_nodes); order++)
324
+ for (int node : order_to_nodes[order])
325
+ {
326
+ for (auto &it : nodes[node].links)
327
+ {
328
+ int target = it.first;
329
+ SigBit ctrl = state_sig[node];
330
+
331
+ if (it.second != State::S1)
332
+ ctrl = module->And(NEW_ID, ctrl, it.second);
333
+
334
+ state_sig[target] = module->Or(NEW_ID, state_sig[target], ctrl);
335
+ }
336
+ }
337
+ }
338
+
339
+ // Construct activations
340
+
341
+ {
342
+ vector<SigSpec> activate_sig(GetSize(nodes));
343
+ vector<SigBit> activate_bit(GetSize(nodes));
344
+
345
+ for (int i = 0; i < GetSize(nodes); i++) {
346
+ for (auto &it : nodes[i].edges)
347
+ activate_sig[it.first].append(module->And(NEW_ID, state_sig[i], it.second));
348
+ }
349
+
350
+ for (int i = 0; i < GetSize(nodes); i++) {
351
+ if (GetSize(activate_sig[i]) == 0)
352
+ next_state_sig[i] = State::S0;
353
+ else if (GetSize(activate_sig[i]) == 1)
354
+ next_state_sig[i] = activate_sig[i];
355
+ else
356
+ next_state_sig[i] = module->ReduceOr(NEW_ID, activate_sig[i]);
357
+ }
358
+ }
359
+
360
+ // Create state FFs
361
+
362
+ for (int i = 0; i < GetSize(nodes); i++)
363
+ {
364
+ if (next_state_sig[i] != State::S0) {
365
+ clocking.addDff(NEW_ID, next_state_sig[i], state_wire[i], State::S0);
366
+ } else {
367
+ module->connect(state_wire[i], State::S0);
368
+ }
369
+ }
370
+
371
+ final_accept_sig = state_sig[acceptNode];
372
+ return final_accept_sig;
373
+ }
374
+
375
+ // ----------------------------------------------------
376
+ // Generating quantifier-based NFSM circuit to acquire reject signal
377
+
378
+ SigBit getAnyAllRejectWorker(bool /* allMode */)
379
+ {
380
+ // FIXME
381
+ log_abort();
382
+ }
383
+
384
+ SigBit getAnyReject()
385
+ {
386
+ return getAnyAllRejectWorker(false);
387
+ }
388
+
389
+ SigBit getAllReject()
390
+ {
391
+ return getAnyAllRejectWorker(true);
392
+ }
393
+
394
+ // ----------------------------------------------------
395
+ // Generating DFSM circuit to acquire reject signal
396
+
397
+ void node_to_unode(int node, int unode, SigSpec ctrl)
398
+ {
399
+ if (node == acceptNode)
400
+ unodes[unode].accept.push_back(ctrl);
401
+
402
+ if (node == condNode)
403
+ unodes[unode].cond.push_back(ctrl);
404
+
405
+ for (auto &it : nodes[node].edges) {
406
+ if (it.second != State::S1) {
407
+ SigSpec s = {ctrl, it.second};
408
+ s.sort_and_unify();
409
+ unodes[unode].edges.push_back(make_pair(it.first, s));
410
+ } else {
411
+ unodes[unode].edges.push_back(make_pair(it.first, ctrl));
412
+ }
413
+ }
414
+
415
+ for (auto &it : nodes[node].links) {
416
+ if (it.second != State::S1) {
417
+ SigSpec s = {ctrl, it.second};
418
+ s.sort_and_unify();
419
+ node_to_unode(it.first, unode, s);
420
+ } else {
421
+ node_to_unode(it.first, unode, ctrl);
422
+ }
423
+ }
424
+ }
425
+
426
+ void mark_reachable_unode(int unode)
427
+ {
428
+ if (unodes[unode].reachable)
429
+ return;
430
+
431
+ unodes[unode].reachable = true;
432
+ for (auto &it : unodes[unode].edges)
433
+ mark_reachable_unode(it.first);
434
+ }
435
+
436
+ void usortint(vector<int> &vec)
437
+ {
438
+ vector<int> newvec;
439
+ std::sort(vec.begin(), vec.end());
440
+ for (int i = 0; i < GetSize(vec); i++)
441
+ if (i == GetSize(vec)-1 || vec[i] != vec[i+1])
442
+ newvec.push_back(vec[i]);
443
+ vec.swap(newvec);
444
+ }
445
+
446
+ bool cmp_ctrl(const pool<SigBit> &ctrl_bits, const SigSpec &ctrl)
447
+ {
448
+ for (int i = 0; i < GetSize(ctrl); i++)
449
+ if (ctrl_bits.count(ctrl[i]) == 0)
450
+ return false;
451
+ return true;
452
+ }
453
+
454
+ void create_dnode(const vector<int> &state, bool firstmatch, bool condaccept)
455
+ {
456
+ if (dnodes.count(state) != 0)
457
+ return;
458
+
459
+ SvaDFsmNode dnode;
460
+ dnodes[state] = SvaDFsmNode();
461
+
462
+ for (int unode : state) {
463
+ log_assert(unodes[unode].reachable);
464
+ for (auto &it : unodes[unode].edges)
465
+ dnode.ctrl.append(it.second);
466
+ for (auto &it : unodes[unode].accept)
467
+ dnode.ctrl.append(it);
468
+ for (auto &it : unodes[unode].cond)
469
+ dnode.ctrl.append(it);
470
+ }
471
+
472
+ dnode.ctrl.sort_and_unify();
473
+
474
+ if (GetSize(dnode.ctrl) > verific_sva_fsm_limit) {
475
+ if (verific_verbose >= 2) {
476
+ log(" detected state explosion in DFSM generation:\n");
477
+ dump();
478
+ log(" ctrl signal: %s\n", log_signal(dnode.ctrl));
479
+ }
480
+ parser_error(stringf("SVA DFSM state ctrl signal has %d (>%d) bits. Stopping to prevent exponential design size explosion.\n",
481
+ GetSize(dnode.ctrl), verific_sva_fsm_limit));
482
+ }
483
+
484
+ for (unsigned long long i = 0; i < (1ull << GetSize(dnode.ctrl)); i++)
485
+ {
486
+ Const ctrl_val(i, GetSize(dnode.ctrl));
487
+ pool<SigBit> ctrl_bits;
488
+
489
+ for (int j = 0; j < GetSize(dnode.ctrl); j++)
490
+ if (ctrl_val[j] == State::S1)
491
+ ctrl_bits.insert(dnode.ctrl[j]);
492
+
493
+ vector<int> new_state;
494
+ bool accept = false, cond = false;
495
+
496
+ for (int unode : state) {
497
+ for (auto &it : unodes[unode].accept)
498
+ if (cmp_ctrl(ctrl_bits, it))
499
+ accept = true;
500
+ for (auto &it : unodes[unode].cond)
501
+ if (cmp_ctrl(ctrl_bits, it))
502
+ cond = true;
503
+ }
504
+
505
+ bool new_state_cond = false;
506
+ bool new_state_noncond = false;
507
+
508
+ if (accept && condaccept)
509
+ accept = cond;
510
+
511
+ if (!accept || !firstmatch) {
512
+ for (int unode : state)
513
+ for (auto &it : unodes[unode].edges)
514
+ if (cmp_ctrl(ctrl_bits, it.second)) {
515
+ if (nodes.at(it.first).is_cond_node)
516
+ new_state_cond = true;
517
+ else
518
+ new_state_noncond = true;
519
+ new_state.push_back(it.first);
520
+ }
521
+ }
522
+
523
+ if (accept)
524
+ dnode.accept.push_back(ctrl_val);
525
+
526
+ if (condaccept && (!new_state_cond || !new_state_noncond))
527
+ new_state.clear();
528
+
529
+ if (new_state.empty()) {
530
+ if (!accept)
531
+ dnode.reject.push_back(ctrl_val);
532
+ } else {
533
+ usortint(new_state);
534
+ dnode.edges.push_back(make_pair(new_state, ctrl_val));
535
+ create_dnode(new_state, firstmatch, condaccept);
536
+ }
537
+ }
538
+
539
+ dnodes[state] = dnode;
540
+ }
541
+
542
+ void optimize_cond(vector<Const> &values)
543
+ {
544
+ bool did_something = true;
545
+
546
+ while (did_something)
547
+ {
548
+ did_something = false;
549
+
550
+ for (int i = 0; i < GetSize(values); i++)
551
+ for (int j = 0; j < GetSize(values); j++)
552
+ {
553
+ if (i == j)
554
+ continue;
555
+
556
+ log_assert(GetSize(values[i]) == GetSize(values[j]));
557
+
558
+ int delta_pos = -1;
559
+ bool i_within_j = true;
560
+ bool j_within_i = true;
561
+
562
+ for (int k = 0; k < GetSize(values[i]); k++) {
563
+ if (values[i][k] == State::Sa && values[j][k] != State::Sa) {
564
+ i_within_j = false;
565
+ continue;
566
+ }
567
+ if (values[i][k] != State::Sa && values[j][k] == State::Sa) {
568
+ j_within_i = false;
569
+ continue;
570
+ }
571
+ if (values[i][k] == values[j][k])
572
+ continue;
573
+ if (delta_pos >= 0)
574
+ goto next_pair;
575
+ delta_pos = k;
576
+ }
577
+
578
+ if (delta_pos >= 0 && i_within_j && j_within_i) {
579
+ did_something = true;
580
+ values[i].set(delta_pos, State::Sa);
581
+ values[j] = values.back();
582
+ values.pop_back();
583
+ goto next_pair;
584
+ }
585
+
586
+ if (delta_pos < 0 && i_within_j) {
587
+ did_something = true;
588
+ values[i] = values.back();
589
+ values.pop_back();
590
+ goto next_pair;
591
+ }
592
+
593
+ if (delta_pos < 0 && j_within_i) {
594
+ did_something = true;
595
+ values[j] = values.back();
596
+ values.pop_back();
597
+ goto next_pair;
598
+ }
599
+ next_pair:;
600
+ }
601
+ }
602
+ }
603
+
604
+ SigBit make_cond_eq(const SigSpec &ctrl, const Const &value, SigBit enable = State::S1)
605
+ {
606
+ SigSpec sig_a, sig_b;
607
+
608
+ log_assert(GetSize(ctrl) == GetSize(value));
609
+
610
+ for (int i = 0; i < GetSize(ctrl); i++)
611
+ if (value[i] != State::Sa) {
612
+ sig_a.append(ctrl[i]);
613
+ sig_b.append(value[i]);
614
+ }
615
+
616
+ if (GetSize(sig_a) == 0)
617
+ return enable;
618
+
619
+ if (enable != State::S1) {
620
+ sig_a.append(enable);
621
+ sig_b.append(State::S1);
622
+ }
623
+
624
+ auto key = make_pair(sig_a, sig_b);
625
+
626
+ if (cond_eq_cache.count(key) == 0)
627
+ {
628
+ if (sig_b == State::S1)
629
+ cond_eq_cache[key] = sig_a;
630
+ else if (sig_b == State::S0)
631
+ cond_eq_cache[key] = module->Not(NEW_ID, sig_a);
632
+ else
633
+ cond_eq_cache[key] = module->Eq(NEW_ID, sig_a, sig_b);
634
+
635
+ if (verific_verbose >= 2) {
636
+ log(" Cond: %s := %s == %s\n", log_signal(cond_eq_cache[key]),
637
+ log_signal(sig_a), log_signal(sig_b));
638
+ }
639
+ }
640
+
641
+ return cond_eq_cache.at(key);
642
+ }
643
+
644
+ void getFirstAcceptReject(SigBit *accept_p, SigBit *reject_p)
645
+ {
646
+ log_assert(!materialized);
647
+ materialized = true;
648
+
649
+ // Create unlinked NFSM
650
+
651
+ unodes.resize(GetSize(nodes));
652
+
653
+ for (int node = 0; node < GetSize(nodes); node++)
654
+ node_to_unode(node, node, SigSpec());
655
+
656
+ mark_reachable_unode(startNode);
657
+
658
+ // Create DFSM
659
+
660
+ create_dnode(vector<int>{startNode}, true, false);
661
+ dnodes.sort();
662
+
663
+ // Create DFSM Circuit
664
+
665
+ SigSpec accept_sig, reject_sig;
666
+
667
+ for (auto &it : dnodes)
668
+ {
669
+ SvaDFsmNode &dnode = it.second;
670
+ dnode.ffoutwire = module->addWire(NEW_ID);
671
+ dnode.statesig = dnode.ffoutwire;
672
+
673
+ if (it.first == vector<int>{startNode})
674
+ dnode.statesig = module->Or(NEW_ID, dnode.statesig, trigger_sig);
675
+ }
676
+
677
+ for (auto &it : dnodes)
678
+ {
679
+ SvaDFsmNode &dnode = it.second;
680
+ dict<vector<int>, vector<Const>> edge_cond;
681
+
682
+ for (auto &edge : dnode.edges)
683
+ edge_cond[edge.first].push_back(edge.second);
684
+
685
+ for (auto &it : edge_cond) {
686
+ optimize_cond(it.second);
687
+ for (auto &value : it.second)
688
+ dnodes.at(it.first).nextstate.append(make_cond_eq(dnode.ctrl, value, dnode.statesig));
689
+ }
690
+
691
+ if (accept_p) {
692
+ vector<Const> accept_cond = dnode.accept;
693
+ optimize_cond(accept_cond);
694
+ for (auto &value : accept_cond)
695
+ accept_sig.append(make_cond_eq(dnode.ctrl, value, dnode.statesig));
696
+ }
697
+
698
+ if (reject_p) {
699
+ vector<Const> reject_cond = dnode.reject;
700
+ optimize_cond(reject_cond);
701
+ for (auto &value : reject_cond)
702
+ reject_sig.append(make_cond_eq(dnode.ctrl, value, dnode.statesig));
703
+ }
704
+ }
705
+
706
+ for (auto &it : dnodes)
707
+ {
708
+ SvaDFsmNode &dnode = it.second;
709
+ if (GetSize(dnode.nextstate) == 0) {
710
+ module->connect(dnode.ffoutwire, State::S0);
711
+ } else
712
+ if (GetSize(dnode.nextstate) == 1) {
713
+ clocking.addDff(NEW_ID, dnode.nextstate, dnode.ffoutwire, State::S0);
714
+ } else {
715
+ SigSpec nextstate = module->ReduceOr(NEW_ID, dnode.nextstate);
716
+ clocking.addDff(NEW_ID, nextstate, dnode.ffoutwire, State::S0);
717
+ }
718
+ }
719
+
720
+ if (accept_p)
721
+ {
722
+ if (GetSize(accept_sig) == 0)
723
+ final_accept_sig = State::S0;
724
+ else if (GetSize(accept_sig) == 1)
725
+ final_accept_sig = accept_sig;
726
+ else
727
+ final_accept_sig = module->ReduceOr(NEW_ID, accept_sig);
728
+ *accept_p = final_accept_sig;
729
+ }
730
+
731
+ if (reject_p)
732
+ {
733
+ if (GetSize(reject_sig) == 0)
734
+ final_reject_sig = State::S0;
735
+ else if (GetSize(reject_sig) == 1)
736
+ final_reject_sig = reject_sig;
737
+ else
738
+ final_reject_sig = module->ReduceOr(NEW_ID, reject_sig);
739
+ *reject_p = final_reject_sig;
740
+ }
741
+ }
742
+
743
+ SigBit getFirstAccept()
744
+ {
745
+ SigBit accept;
746
+ getFirstAcceptReject(&accept, nullptr);
747
+ return accept;
748
+ }
749
+
750
+ SigBit getReject()
751
+ {
752
+ SigBit reject;
753
+ getFirstAcceptReject(nullptr, &reject);
754
+ return reject;
755
+ }
756
+
757
+ void getDFsm(SvaFsm &output_fsm, int output_start_node, int output_accept_node, int output_reject_node = -1, bool firstmatch = true, bool condaccept = false)
758
+ {
759
+ log_assert(!materialized);
760
+ materialized = true;
761
+
762
+ // Create unlinked NFSM
763
+
764
+ unodes.resize(GetSize(nodes));
765
+
766
+ for (int node = 0; node < GetSize(nodes); node++)
767
+ node_to_unode(node, node, SigSpec());
768
+
769
+ mark_reachable_unode(startNode);
770
+
771
+ // Create DFSM
772
+
773
+ create_dnode(vector<int>{startNode}, firstmatch, condaccept);
774
+ dnodes.sort();
775
+
776
+ // Create DFSM Graph
777
+
778
+ for (auto &it : dnodes)
779
+ {
780
+ SvaDFsmNode &dnode = it.second;
781
+ dnode.outnode = output_fsm.createNode();
782
+
783
+ if (it.first == vector<int>{startNode})
784
+ output_fsm.createLink(output_start_node, dnode.outnode);
785
+
786
+ if (output_accept_node >= 0) {
787
+ vector<Const> accept_cond = dnode.accept;
788
+ optimize_cond(accept_cond);
789
+ for (auto &value : accept_cond)
790
+ output_fsm.createLink(it.second.outnode, output_accept_node, make_cond_eq(dnode.ctrl, value));
791
+ }
792
+
793
+ if (output_reject_node >= 0) {
794
+ vector<Const> reject_cond = dnode.reject;
795
+ optimize_cond(reject_cond);
796
+ for (auto &value : reject_cond)
797
+ output_fsm.createLink(it.second.outnode, output_reject_node, make_cond_eq(dnode.ctrl, value));
798
+ }
799
+ }
800
+
801
+ for (auto &it : dnodes)
802
+ {
803
+ SvaDFsmNode &dnode = it.second;
804
+ dict<vector<int>, vector<Const>> edge_cond;
805
+
806
+ for (auto &edge : dnode.edges)
807
+ edge_cond[edge.first].push_back(edge.second);
808
+
809
+ for (auto &it : edge_cond) {
810
+ optimize_cond(it.second);
811
+ for (auto &value : it.second)
812
+ output_fsm.createEdge(dnode.outnode, dnodes.at(it.first).outnode, make_cond_eq(dnode.ctrl, value));
813
+ }
814
+ }
815
+ }
816
+
817
+ // ----------------------------------------------------
818
+ // State dump for verbose log messages
819
+
820
+ void dump_nodes()
821
+ {
822
+ if (nodes.empty())
823
+ return;
824
+
825
+ log(" non-deterministic encoding:\n");
826
+ for (int i = 0; i < GetSize(nodes); i++)
827
+ {
828
+ log(" node %d:%s\n", i,
829
+ i == startNode ? " [start]" :
830
+ i == acceptNode ? " [accept]" :
831
+ i == condNode ? " [cond]" : "");
832
+
833
+ for (auto &it : nodes[i].edges) {
834
+ if (it.second != State::S1)
835
+ log(" edge %s -> %d\n", log_signal(it.second), it.first);
836
+ else
837
+ log(" edge -> %d\n", it.first);
838
+ }
839
+
840
+ for (auto &it : nodes[i].links) {
841
+ if (it.second != State::S1)
842
+ log(" link %s -> %d\n", log_signal(it.second), it.first);
843
+ else
844
+ log(" link -> %d\n", it.first);
845
+ }
846
+ }
847
+ }
848
+
849
+ void dump_unodes()
850
+ {
851
+ if (unodes.empty())
852
+ return;
853
+
854
+ log(" unlinked non-deterministic encoding:\n");
855
+ for (int i = 0; i < GetSize(unodes); i++)
856
+ {
857
+ if (!unodes[i].reachable)
858
+ continue;
859
+
860
+ log(" unode %d:%s\n", i, i == startNode ? " [start]" : "");
861
+
862
+ for (auto &it : unodes[i].edges) {
863
+ if (!it.second.empty())
864
+ log(" edge %s -> %d\n", log_signal(it.second), it.first);
865
+ else
866
+ log(" edge -> %d\n", it.first);
867
+ }
868
+
869
+ for (auto &ctrl : unodes[i].accept) {
870
+ if (!ctrl.empty())
871
+ log(" accept %s\n", log_signal(ctrl));
872
+ else
873
+ log(" accept\n");
874
+ }
875
+
876
+ for (auto &ctrl : unodes[i].cond) {
877
+ if (!ctrl.empty())
878
+ log(" cond %s\n", log_signal(ctrl));
879
+ else
880
+ log(" cond\n");
881
+ }
882
+ }
883
+ }
884
+
885
+ void dump_dnodes()
886
+ {
887
+ if (dnodes.empty())
888
+ return;
889
+
890
+ log(" deterministic encoding:\n");
891
+ for (auto &it : dnodes)
892
+ {
893
+ std::string message;
894
+ for (int i = 0; i < GetSize(it.first); i++)
895
+ message += stringf("%s%d", i ? "," : "", it.first[i]);
896
+ log(" dnode {%s}:%s\n", message, GetSize(it.first) == 1 && it.first[0] == startNode ? " [start]" : "");
897
+
898
+ log(" ctrl %s\n", log_signal(it.second.ctrl));
899
+
900
+ for (auto &edge : it.second.edges) {
901
+ std::string message;
902
+ for (int i = 0; i < GetSize(edge.first); i++)
903
+ message += stringf("%s%d", i ? "," : "", edge.first[i]);
904
+ log(" edge %s -> {%s}\n", log_signal(edge.second), message);
905
+ }
906
+
907
+ for (auto &value : it.second.accept)
908
+ log(" accept %s\n", log_signal(value));
909
+
910
+ for (auto &value : it.second.reject)
911
+ log(" reject %s\n", log_signal(value));
912
+ }
913
+ }
914
+
915
+ void dump()
916
+ {
917
+ if (!nodes.empty())
918
+ log(" number of NFSM states: %d\n", GetSize(nodes));
919
+
920
+ if (!unodes.empty()) {
921
+ int count = 0;
922
+ for (auto &unode : unodes)
923
+ if (unode.reachable)
924
+ count++;
925
+ log(" number of reachable UFSM states: %d\n", count);
926
+ }
927
+
928
+ if (!dnodes.empty())
929
+ log(" number of DFSM states: %d\n", GetSize(dnodes));
930
+
931
+ if (verific_verbose >= 2) {
932
+ dump_nodes();
933
+ dump_unodes();
934
+ dump_dnodes();
935
+ }
936
+
937
+ if (trigger_sig != State::S1)
938
+ log(" trigger signal: %s\n", log_signal(trigger_sig));
939
+
940
+ if (final_accept_sig != State::Sx)
941
+ log(" accept signal: %s\n", log_signal(final_accept_sig));
942
+
943
+ if (final_reject_sig != State::Sx)
944
+ log(" reject signal: %s\n", log_signal(final_reject_sig));
945
+ }
946
+ };
947
+
948
+ PRIVATE_NAMESPACE_END
949
+
950
+ YOSYS_NAMESPACE_BEGIN
951
+
952
+ pool<int> verific_sva_prims = {
953
+ // Copy&paste from Verific 3.16_484_32_170630 Netlist.h
954
+ PRIM_SVA_IMMEDIATE_ASSERT, PRIM_SVA_ASSERT, PRIM_SVA_COVER, PRIM_SVA_ASSUME,
955
+ PRIM_SVA_EXPECT, PRIM_SVA_POSEDGE, PRIM_SVA_NOT, PRIM_SVA_FIRST_MATCH,
956
+ PRIM_SVA_ENDED, PRIM_SVA_MATCHED, PRIM_SVA_CONSECUTIVE_REPEAT,
957
+ PRIM_SVA_NON_CONSECUTIVE_REPEAT, PRIM_SVA_GOTO_REPEAT,
958
+ PRIM_SVA_MATCH_ITEM_TRIGGER, PRIM_SVA_AND, PRIM_SVA_OR, PRIM_SVA_SEQ_AND,
959
+ PRIM_SVA_SEQ_OR, PRIM_SVA_EVENT_OR, PRIM_SVA_OVERLAPPED_IMPLICATION,
960
+ PRIM_SVA_NON_OVERLAPPED_IMPLICATION, PRIM_SVA_OVERLAPPED_FOLLOWED_BY,
961
+ PRIM_SVA_NON_OVERLAPPED_FOLLOWED_BY, PRIM_SVA_INTERSECT, PRIM_SVA_THROUGHOUT,
962
+ PRIM_SVA_WITHIN, PRIM_SVA_AT, PRIM_SVA_DISABLE_IFF, PRIM_SVA_SAMPLED,
963
+ PRIM_SVA_ROSE, PRIM_SVA_FELL, PRIM_SVA_STABLE, PRIM_SVA_PAST,
964
+ PRIM_SVA_MATCH_ITEM_ASSIGN, PRIM_SVA_SEQ_CONCAT, PRIM_SVA_IF,
965
+ PRIM_SVA_RESTRICT, PRIM_SVA_TRIGGERED, PRIM_SVA_STRONG, PRIM_SVA_WEAK,
966
+ PRIM_SVA_NEXTTIME, PRIM_SVA_S_NEXTTIME, PRIM_SVA_ALWAYS, PRIM_SVA_S_ALWAYS,
967
+ PRIM_SVA_S_EVENTUALLY, PRIM_SVA_EVENTUALLY, PRIM_SVA_UNTIL, PRIM_SVA_S_UNTIL,
968
+ PRIM_SVA_UNTIL_WITH, PRIM_SVA_S_UNTIL_WITH, PRIM_SVA_IMPLIES, PRIM_SVA_IFF,
969
+ PRIM_SVA_ACCEPT_ON, PRIM_SVA_REJECT_ON, PRIM_SVA_SYNC_ACCEPT_ON,
970
+ PRIM_SVA_SYNC_REJECT_ON, PRIM_SVA_GLOBAL_CLOCKING_DEF,
971
+ PRIM_SVA_GLOBAL_CLOCKING_REF, PRIM_SVA_IMMEDIATE_ASSUME,
972
+ PRIM_SVA_IMMEDIATE_COVER, OPER_SVA_SAMPLED, OPER_SVA_STABLE
973
+ };
974
+
975
+ struct VerificSvaImporter
976
+ {
977
+ VerificImporter *importer = nullptr;
978
+ Module *module = nullptr;
979
+
980
+ Netlist *netlist = nullptr;
981
+ Instance *root = nullptr;
982
+
983
+ VerificClocking clocking;
984
+
985
+ bool mode_assert = false;
986
+ bool mode_assume = false;
987
+ bool mode_cover = false;
988
+ bool mode_trigger = false;
989
+
990
+ Instance *net_to_ast_driver(Net *n)
991
+ {
992
+ if (n == nullptr)
993
+ return nullptr;
994
+
995
+ if (n->IsMultipleDriven())
996
+ return nullptr;
997
+
998
+ Instance *inst = n->Driver();
999
+
1000
+ if (inst == nullptr)
1001
+ return nullptr;
1002
+
1003
+ if (!verific_sva_prims.count(inst->Type()))
1004
+ return nullptr;
1005
+
1006
+ if (inst->Type() == PRIM_SVA_ROSE || inst->Type() == PRIM_SVA_FELL ||
1007
+ inst->Type() == PRIM_SVA_STABLE || inst->Type() == OPER_SVA_STABLE ||
1008
+ inst->Type() == PRIM_SVA_PAST || inst->Type() == PRIM_SVA_TRIGGERED)
1009
+ return nullptr;
1010
+
1011
+ return inst;
1012
+ }
1013
+
1014
+ Instance *get_ast_input(Instance *inst) { return net_to_ast_driver(inst->GetInput()); }
1015
+ Instance *get_ast_input1(Instance *inst) { return net_to_ast_driver(inst->GetInput1()); }
1016
+ Instance *get_ast_input2(Instance *inst) { return net_to_ast_driver(inst->GetInput2()); }
1017
+ Instance *get_ast_input3(Instance *inst) { return net_to_ast_driver(inst->GetInput3()); }
1018
+ Instance *get_ast_control(Instance *inst) { return net_to_ast_driver(inst->GetControl()); }
1019
+
1020
+ // ----------------------------------------------------------
1021
+ // SVA Importer
1022
+
1023
+ struct ParserErrorException {
1024
+ };
1025
+
1026
+ [[noreturn]] void parser_error(std::string errmsg)
1027
+ {
1028
+ if (!importer->mode_keep && !importer->mode_sva_continue)
1029
+ log_error("%s", errmsg);
1030
+ log_warning("%s", errmsg);
1031
+ throw ParserErrorException();
1032
+ }
1033
+
1034
+ [[noreturn]] void parser_error(std::string errmsg, linefile_type loc)
1035
+ {
1036
+ parser_error(stringf("%s at %s:%d.\n", errmsg, LineFile::GetFileName(loc), LineFile::GetLineNo(loc)));
1037
+ }
1038
+
1039
+ [[noreturn]] void parser_error(std::string errmsg, Instance *inst)
1040
+ {
1041
+ parser_error(stringf("%s at %s (%s)", errmsg, inst->View()->Owner()->Name(), inst->Name()), inst->Linefile());
1042
+ }
1043
+
1044
+ [[noreturn]] void parser_error(Instance *inst)
1045
+ {
1046
+ std::string msg;
1047
+ if (inst->Type() == PRIM_SVA_MATCH_ITEM_TRIGGER || inst->Type() == PRIM_SVA_MATCH_ITEM_ASSIGN)
1048
+ {
1049
+ msg = "SVA sequences with local variable assignments are currently not supported.\n";
1050
+ }
1051
+
1052
+ parser_error(stringf("%sVerific SVA primitive %s (%s) is currently unsupported in this context",
1053
+ msg, inst->View()->Owner()->Name(), inst->Name()), inst->Linefile());
1054
+ }
1055
+
1056
+ dict<Net*, bool> check_expression_cache;
1057
+
1058
+ bool check_expression(Net *net, bool raise_error = false)
1059
+ {
1060
+ while (!check_expression_cache.count(net))
1061
+ {
1062
+ Instance *inst = net_to_ast_driver(net);
1063
+
1064
+ if (inst == nullptr) {
1065
+ check_expression_cache[net] = true;
1066
+ break;
1067
+ }
1068
+
1069
+ if (inst->Type() == PRIM_SVA_AT)
1070
+ {
1071
+ VerificClocking new_clocking(importer, net);
1072
+ log_assert(new_clocking.cond_net == nullptr);
1073
+ if (!clocking.property_matches_sequence(new_clocking))
1074
+ parser_error("Mixed clocking is currently not supported", inst);
1075
+ check_expression_cache[net] = check_expression(new_clocking.body_net, raise_error);
1076
+ break;
1077
+ }
1078
+
1079
+ if (inst->Type() == PRIM_SVA_FIRST_MATCH || inst->Type() == PRIM_SVA_NOT)
1080
+ {
1081
+ check_expression_cache[net] = check_expression(inst->GetInput(), raise_error);
1082
+ break;
1083
+ }
1084
+
1085
+ if (inst->Type() == PRIM_SVA_SEQ_OR || inst->Type() == PRIM_SVA_SEQ_AND || inst->Type() == PRIM_SVA_INTERSECT ||
1086
+ inst->Type() == PRIM_SVA_WITHIN || inst->Type() == PRIM_SVA_THROUGHOUT ||
1087
+ inst->Type() == PRIM_SVA_OR || inst->Type() == PRIM_SVA_AND)
1088
+ {
1089
+ check_expression_cache[net] = check_expression(inst->GetInput1(), raise_error) && check_expression(inst->GetInput2(), raise_error);
1090
+ break;
1091
+ }
1092
+
1093
+ if (inst->Type() == PRIM_SVA_SEQ_CONCAT)
1094
+ {
1095
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1096
+ const char *sva_high_s = inst->GetAttValue("sva:high");
1097
+
1098
+ int sva_low = atoi(sva_low_s);
1099
+ int sva_high = atoi(sva_high_s);
1100
+ bool sva_inf = !strcmp(sva_high_s, "$");
1101
+
1102
+ if (sva_low == 0 && sva_high == 0 && !sva_inf)
1103
+ check_expression_cache[net] = check_expression(inst->GetInput1(), raise_error) && check_expression(inst->GetInput2(), raise_error);
1104
+ else
1105
+ check_expression_cache[net] = false;
1106
+ break;
1107
+ }
1108
+
1109
+ check_expression_cache[net] = false;
1110
+ }
1111
+
1112
+ if (raise_error && !check_expression_cache.at(net))
1113
+ parser_error(net_to_ast_driver(net));
1114
+ return check_expression_cache.at(net);
1115
+ }
1116
+
1117
+ SigBit parse_expression(Net *net)
1118
+ {
1119
+ check_expression(net, true);
1120
+
1121
+ Instance *inst = net_to_ast_driver(net);
1122
+
1123
+ if (inst == nullptr) {
1124
+ return importer->net_map_at(net);
1125
+ }
1126
+
1127
+ if (inst->Type() == PRIM_SVA_AT)
1128
+ {
1129
+ VerificClocking new_clocking(importer, net);
1130
+ log_assert(new_clocking.cond_net == nullptr);
1131
+ if (!clocking.property_matches_sequence(new_clocking))
1132
+ parser_error("Mixed clocking is currently not supported", inst);
1133
+ return parse_expression(new_clocking.body_net);
1134
+ }
1135
+
1136
+ if (inst->Type() == PRIM_SVA_FIRST_MATCH)
1137
+ return parse_expression(inst->GetInput());
1138
+
1139
+ if (inst->Type() == PRIM_SVA_NOT)
1140
+ return module->Not(NEW_ID, parse_expression(inst->GetInput()));
1141
+
1142
+ if (inst->Type() == PRIM_SVA_SEQ_OR || inst->Type() == PRIM_SVA_OR)
1143
+ return module->Or(NEW_ID, parse_expression(inst->GetInput1()), parse_expression(inst->GetInput2()));
1144
+
1145
+ if (inst->Type() == PRIM_SVA_SEQ_AND || inst->Type() == PRIM_SVA_AND || inst->Type() == PRIM_SVA_INTERSECT ||
1146
+ inst->Type() == PRIM_SVA_WITHIN || inst->Type() == PRIM_SVA_THROUGHOUT || inst->Type() == PRIM_SVA_SEQ_CONCAT)
1147
+ return module->And(NEW_ID, parse_expression(inst->GetInput1()), parse_expression(inst->GetInput2()));
1148
+
1149
+ log_abort();
1150
+ }
1151
+
1152
+ bool check_zero_consecutive_repeat(Net *net)
1153
+ {
1154
+ Instance *inst = net_to_ast_driver(net);
1155
+
1156
+ if (inst == nullptr)
1157
+ return false;
1158
+
1159
+ if (inst->Type() != PRIM_SVA_CONSECUTIVE_REPEAT)
1160
+ return false;
1161
+
1162
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1163
+ int sva_low = atoi(sva_low_s);
1164
+
1165
+ return sva_low == 0;
1166
+ }
1167
+
1168
+ int parse_consecutive_repeat(SvaFsm &fsm, int start_node, Net *net, bool add_pre_delay, bool add_post_delay)
1169
+ {
1170
+ Instance *inst = net_to_ast_driver(net);
1171
+
1172
+ log_assert(inst->Type() == PRIM_SVA_CONSECUTIVE_REPEAT);
1173
+
1174
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1175
+ const char *sva_high_s = inst->GetAttValue("sva:high");
1176
+
1177
+ int sva_low = atoi(sva_low_s);
1178
+ int sva_high = atoi(sva_high_s);
1179
+ bool sva_inf = !strcmp(sva_high_s, "$");
1180
+
1181
+ Net *body_net = inst->GetInput();
1182
+
1183
+ if (add_pre_delay || add_post_delay)
1184
+ log_assert(sva_low == 0);
1185
+
1186
+ if (sva_low == 0) {
1187
+ if (!add_pre_delay && !add_post_delay)
1188
+ parser_error("Possibly zero-length consecutive repeat must follow or precede a delay of at least one cycle", inst);
1189
+ sva_low++;
1190
+ }
1191
+
1192
+ int node = fsm.createNode(start_node);
1193
+ start_node = node;
1194
+
1195
+ if (add_pre_delay) {
1196
+ node = fsm.createNode(start_node);
1197
+ fsm.createEdge(start_node, node);
1198
+ }
1199
+
1200
+ int prev_node = node;
1201
+ node = parse_sequence(fsm, node, body_net);
1202
+
1203
+ for (int i = 1; i < sva_low; i++)
1204
+ {
1205
+ int next_node = fsm.createNode();
1206
+ fsm.createEdge(node, next_node);
1207
+
1208
+ prev_node = node;
1209
+ node = parse_sequence(fsm, next_node, body_net);
1210
+ }
1211
+
1212
+ if (sva_inf)
1213
+ {
1214
+ log_assert(prev_node >= 0);
1215
+ fsm.createEdge(node, prev_node);
1216
+ }
1217
+ else
1218
+ {
1219
+ for (int i = sva_low; i < sva_high; i++)
1220
+ {
1221
+ int next_node = fsm.createNode();
1222
+ fsm.createEdge(node, next_node);
1223
+
1224
+ prev_node = node;
1225
+ node = parse_sequence(fsm, next_node, body_net);
1226
+
1227
+ fsm.createLink(prev_node, node);
1228
+ }
1229
+ }
1230
+
1231
+ if (add_post_delay) {
1232
+ int next_node = fsm.createNode();
1233
+ fsm.createEdge(node, next_node);
1234
+ node = next_node;
1235
+ }
1236
+
1237
+ if (add_pre_delay || add_post_delay)
1238
+ fsm.createLink(start_node, node);
1239
+
1240
+ return node;
1241
+ }
1242
+
1243
+ int parse_sequence(SvaFsm &fsm, int start_node, Net *net)
1244
+ {
1245
+ if (check_expression(net)) {
1246
+ int node = fsm.createNode();
1247
+ fsm.createLink(start_node, node, parse_expression(net));
1248
+ return node;
1249
+ }
1250
+
1251
+ Instance *inst = net_to_ast_driver(net);
1252
+
1253
+ if (inst->Type() == PRIM_SVA_AT)
1254
+ {
1255
+ VerificClocking new_clocking(importer, net);
1256
+ log_assert(new_clocking.cond_net == nullptr);
1257
+ if (!clocking.property_matches_sequence(new_clocking))
1258
+ parser_error("Mixed clocking is currently not supported", inst);
1259
+ return parse_sequence(fsm, start_node, new_clocking.body_net);
1260
+ }
1261
+
1262
+ if (inst->Type() == PRIM_SVA_FIRST_MATCH)
1263
+ {
1264
+ SvaFsm match_fsm(clocking);
1265
+ match_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1266
+ match_fsm.createLink(parse_sequence(match_fsm, match_fsm.createStartNode(), inst->GetInput()), match_fsm.acceptNode);
1267
+
1268
+ int node = fsm.createNode();
1269
+ match_fsm.getDFsm(fsm, start_node, node);
1270
+
1271
+ if (verific_verbose) {
1272
+ log(" First Match FSM:\n");
1273
+ match_fsm.dump();
1274
+ }
1275
+
1276
+ return node;
1277
+ }
1278
+
1279
+ if (inst->Type() == PRIM_SVA_NEXTTIME || inst->Type() == PRIM_SVA_S_NEXTTIME)
1280
+ {
1281
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1282
+ const char *sva_high_s = inst->GetAttValue("sva:high");
1283
+
1284
+ int sva_low = atoi(sva_low_s);
1285
+ int sva_high = atoi(sva_high_s);
1286
+ log_assert(sva_low == sva_high);
1287
+
1288
+ int node = start_node;
1289
+
1290
+ for (int i = 0; i < sva_low; i++) {
1291
+ int next_node = fsm.createNode();
1292
+ fsm.createEdge(node, next_node);
1293
+ node = next_node;
1294
+ }
1295
+
1296
+ return parse_sequence(fsm, node, inst->GetInput());
1297
+ }
1298
+
1299
+ if (inst->Type() == PRIM_SVA_SEQ_CONCAT)
1300
+ {
1301
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1302
+ const char *sva_high_s = inst->GetAttValue("sva:high");
1303
+
1304
+ int sva_low = atoi(sva_low_s);
1305
+ int sva_high = atoi(sva_high_s);
1306
+ bool sva_inf = !strcmp(sva_high_s, "$");
1307
+
1308
+ int node = -1;
1309
+ bool past_add_delay = false;
1310
+
1311
+ if (check_zero_consecutive_repeat(inst->GetInput1()) && sva_low > 0) {
1312
+ node = parse_consecutive_repeat(fsm, start_node, inst->GetInput1(), false, true);
1313
+ sva_low--, sva_high--;
1314
+ } else {
1315
+ node = parse_sequence(fsm, start_node, inst->GetInput1());
1316
+ }
1317
+
1318
+ if (check_zero_consecutive_repeat(inst->GetInput2()) && sva_low > 0) {
1319
+ past_add_delay = true;
1320
+ sva_low--, sva_high--;
1321
+ }
1322
+
1323
+ for (int i = 0; i < sva_low; i++) {
1324
+ int next_node = fsm.createNode();
1325
+ fsm.createEdge(node, next_node);
1326
+ node = next_node;
1327
+ }
1328
+
1329
+ if (sva_inf)
1330
+ {
1331
+ fsm.createEdge(node, node);
1332
+ }
1333
+ else
1334
+ {
1335
+ for (int i = sva_low; i < sva_high; i++)
1336
+ {
1337
+ int next_node = fsm.createNode();
1338
+ fsm.createEdge(node, next_node);
1339
+ fsm.createLink(node, next_node);
1340
+ node = next_node;
1341
+ }
1342
+ }
1343
+
1344
+ if (past_add_delay)
1345
+ node = parse_consecutive_repeat(fsm, node, inst->GetInput2(), true, false);
1346
+ else
1347
+ node = parse_sequence(fsm, node, inst->GetInput2());
1348
+
1349
+ return node;
1350
+ }
1351
+
1352
+ if (inst->Type() == PRIM_SVA_CONSECUTIVE_REPEAT)
1353
+ {
1354
+ return parse_consecutive_repeat(fsm, start_node, net, false, false);
1355
+ }
1356
+
1357
+ if (inst->Type() == PRIM_SVA_NON_CONSECUTIVE_REPEAT || inst->Type() == PRIM_SVA_GOTO_REPEAT)
1358
+ {
1359
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1360
+ const char *sva_high_s = inst->GetAttValue("sva:high");
1361
+
1362
+ int sva_low = atoi(sva_low_s);
1363
+ int sva_high = atoi(sva_high_s);
1364
+ bool sva_inf = !strcmp(sva_high_s, "$");
1365
+
1366
+ Net *body_net = inst->GetInput();
1367
+ int node = fsm.createNode(start_node);
1368
+
1369
+ SigBit cond = parse_expression(body_net);
1370
+ SigBit not_cond = module->Not(NEW_ID, cond);
1371
+
1372
+ for (int i = 0; i < sva_low; i++)
1373
+ {
1374
+ int wait_node = fsm.createNode();
1375
+ fsm.createEdge(wait_node, wait_node, not_cond);
1376
+
1377
+ if (i == 0)
1378
+ fsm.createLink(node, wait_node);
1379
+ else
1380
+ fsm.createEdge(node, wait_node);
1381
+
1382
+ int next_node = fsm.createNode();
1383
+ fsm.createLink(wait_node, next_node, cond);
1384
+
1385
+ node = next_node;
1386
+ }
1387
+
1388
+ if (sva_inf)
1389
+ {
1390
+ int wait_node = fsm.createNode();
1391
+ fsm.createEdge(wait_node, wait_node, not_cond);
1392
+ fsm.createEdge(node, wait_node);
1393
+ fsm.createLink(wait_node, node, cond);
1394
+ }
1395
+ else
1396
+ {
1397
+ for (int i = sva_low; i < sva_high; i++)
1398
+ {
1399
+ int wait_node = fsm.createNode();
1400
+ fsm.createEdge(wait_node, wait_node, not_cond);
1401
+
1402
+ if (i == 0)
1403
+ fsm.createLink(node, wait_node);
1404
+ else
1405
+ fsm.createEdge(node, wait_node);
1406
+
1407
+ int next_node = fsm.createNode();
1408
+ fsm.createLink(wait_node, next_node, cond);
1409
+
1410
+ fsm.createLink(node, next_node);
1411
+ node = next_node;
1412
+ }
1413
+ }
1414
+
1415
+ if (inst->Type() == PRIM_SVA_NON_CONSECUTIVE_REPEAT)
1416
+ fsm.createEdge(node, node);
1417
+
1418
+ return node;
1419
+ }
1420
+
1421
+ if (inst->Type() == PRIM_SVA_SEQ_OR || inst->Type() == PRIM_SVA_OR)
1422
+ {
1423
+ int node = parse_sequence(fsm, start_node, inst->GetInput1());
1424
+ int node2 = parse_sequence(fsm, start_node, inst->GetInput2());
1425
+ fsm.createLink(node2, node);
1426
+ return node;
1427
+ }
1428
+
1429
+ if (inst->Type() == PRIM_SVA_SEQ_AND || inst->Type() == PRIM_SVA_AND)
1430
+ {
1431
+ SvaFsm fsm1(clocking);
1432
+ fsm1.parser_error = [&](std::string msg) { this->parser_error(msg); };
1433
+ fsm1.createLink(parse_sequence(fsm1, fsm1.createStartNode(), inst->GetInput1()), fsm1.acceptNode);
1434
+
1435
+ SvaFsm fsm2(clocking);
1436
+ fsm2.parser_error = [&](std::string msg) { this->parser_error(msg); };
1437
+ fsm2.createLink(parse_sequence(fsm2, fsm2.createStartNode(), inst->GetInput2()), fsm2.acceptNode);
1438
+
1439
+ SvaFsm combined_fsm(clocking);
1440
+ combined_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1441
+ fsm1.getDFsm(combined_fsm, combined_fsm.createStartNode(), -1, combined_fsm.acceptNode);
1442
+ fsm2.getDFsm(combined_fsm, combined_fsm.createStartNode(), -1, combined_fsm.acceptNode);
1443
+
1444
+ int node = fsm.createNode();
1445
+ combined_fsm.getDFsm(fsm, start_node, -1, node);
1446
+
1447
+ if (verific_verbose)
1448
+ {
1449
+ log(" Left And FSM:\n");
1450
+ fsm1.dump();
1451
+
1452
+ log(" Right And FSM:\n");
1453
+ fsm1.dump();
1454
+
1455
+ log(" Combined And FSM:\n");
1456
+ combined_fsm.dump();
1457
+ }
1458
+
1459
+ return node;
1460
+ }
1461
+
1462
+ if (inst->Type() == PRIM_SVA_INTERSECT || inst->Type() == PRIM_SVA_WITHIN)
1463
+ {
1464
+ SvaFsm intersect_fsm(clocking);
1465
+ intersect_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1466
+
1467
+ if (inst->Type() == PRIM_SVA_INTERSECT)
1468
+ {
1469
+ intersect_fsm.createLink(parse_sequence(intersect_fsm, intersect_fsm.createStartNode(), inst->GetInput1()), intersect_fsm.acceptNode);
1470
+ }
1471
+ else
1472
+ {
1473
+ int n = intersect_fsm.createNode();
1474
+ intersect_fsm.createLink(intersect_fsm.createStartNode(), n);
1475
+ intersect_fsm.createEdge(n, n);
1476
+
1477
+ n = parse_sequence(intersect_fsm, n, inst->GetInput1());
1478
+
1479
+ intersect_fsm.createLink(n, intersect_fsm.acceptNode);
1480
+ intersect_fsm.createEdge(n, n);
1481
+ }
1482
+
1483
+ intersect_fsm.in_cond_mode = true;
1484
+ intersect_fsm.createLink(parse_sequence(intersect_fsm, intersect_fsm.createStartNode(), inst->GetInput2()), intersect_fsm.condNode);
1485
+ intersect_fsm.in_cond_mode = false;
1486
+
1487
+ int node = fsm.createNode();
1488
+ intersect_fsm.getDFsm(fsm, start_node, node, -1, false, true);
1489
+
1490
+ if (verific_verbose) {
1491
+ log(" Intersect FSM:\n");
1492
+ intersect_fsm.dump();
1493
+ }
1494
+
1495
+ return node;
1496
+ }
1497
+
1498
+ if (inst->Type() == PRIM_SVA_THROUGHOUT)
1499
+ {
1500
+ SigBit expr = parse_expression(inst->GetInput1());
1501
+
1502
+ fsm.pushThroughout(expr);
1503
+ int node = parse_sequence(fsm, start_node, inst->GetInput2());
1504
+ fsm.popThroughout();
1505
+
1506
+ return node;
1507
+ }
1508
+
1509
+ parser_error(inst);
1510
+ }
1511
+
1512
+ void get_fsm_accept_reject(SvaFsm &fsm, SigBit *accept_p, SigBit *reject_p, bool swap_accept_reject = false)
1513
+ {
1514
+ log_assert(accept_p != nullptr || reject_p != nullptr);
1515
+
1516
+ if (swap_accept_reject)
1517
+ get_fsm_accept_reject(fsm, reject_p, accept_p);
1518
+ else if (reject_p == nullptr)
1519
+ *accept_p = fsm.getAccept();
1520
+ else if (accept_p == nullptr)
1521
+ *reject_p = fsm.getReject();
1522
+ else
1523
+ fsm.getFirstAcceptReject(accept_p, reject_p);
1524
+ }
1525
+
1526
+ void check_eventually(Instance *inst)
1527
+ {
1528
+ if (mode_cover || mode_trigger)
1529
+ parser_error("Unsupported eventually cover", inst);
1530
+
1531
+ const char *sva_low_s = inst->GetAttValue("sva:low");
1532
+ const char *sva_high_s = inst->GetAttValue("sva:high");
1533
+ int sva_low = atoi(sva_low_s);
1534
+ bool sva_inf = !strcmp(sva_high_s, "$");
1535
+
1536
+ if (sva_low != 0 || !sva_inf)
1537
+ parser_error("Unsupported bounded eventually", inst);
1538
+ }
1539
+
1540
+ bool eventually_property(Net *&net, SigBit &trig)
1541
+ {
1542
+ Instance *inst = net_to_ast_driver(net);
1543
+
1544
+ if (inst == nullptr)
1545
+ return false;
1546
+
1547
+ if (clocking.cond_net != nullptr) {
1548
+ trig = importer->net_map_at(clocking.cond_net);
1549
+ if (!clocking.cond_pol)
1550
+ trig = module->Not(NEW_ID, trig);
1551
+ } else {
1552
+ trig = State::S1;
1553
+ }
1554
+
1555
+ if (inst->Type() == PRIM_SVA_S_EVENTUALLY || inst->Type() == PRIM_SVA_EVENTUALLY)
1556
+ {
1557
+ check_eventually(inst);
1558
+
1559
+ net = inst->GetInput();
1560
+ clocking.cond_net = nullptr;
1561
+
1562
+ return true;
1563
+ }
1564
+
1565
+ if (inst->Type() == PRIM_SVA_OVERLAPPED_IMPLICATION ||
1566
+ inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION)
1567
+ {
1568
+ Net *antecedent_net = inst->GetInput1();
1569
+ Net *consequent_net = inst->GetInput2();
1570
+
1571
+ Instance *consequent_inst = net_to_ast_driver(consequent_net);
1572
+
1573
+ if (consequent_inst == nullptr)
1574
+ return false;
1575
+
1576
+ if (consequent_inst->Type() != PRIM_SVA_S_EVENTUALLY && consequent_inst->Type() != PRIM_SVA_EVENTUALLY)
1577
+ return false;
1578
+
1579
+ check_eventually(consequent_inst);
1580
+
1581
+ int node;
1582
+
1583
+ SvaFsm antecedent_fsm(clocking, trig);
1584
+ antecedent_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1585
+ node = parse_sequence(antecedent_fsm, antecedent_fsm.createStartNode(), antecedent_net);
1586
+ if (inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION) {
1587
+ int next_node = antecedent_fsm.createNode();
1588
+ antecedent_fsm.createEdge(node, next_node);
1589
+ node = next_node;
1590
+ }
1591
+ antecedent_fsm.createLink(node, antecedent_fsm.acceptNode);
1592
+
1593
+ trig = antecedent_fsm.getAccept();
1594
+ net = consequent_inst->GetInput();
1595
+ clocking.cond_net = nullptr;
1596
+
1597
+ if (verific_verbose) {
1598
+ log(" Eventually Antecedent FSM:\n");
1599
+ antecedent_fsm.dump();
1600
+ }
1601
+
1602
+ return true;
1603
+ }
1604
+
1605
+ return false;
1606
+ }
1607
+
1608
+ void parse_property(Net *net, SigBit *accept_p, SigBit *reject_p)
1609
+ {
1610
+ Instance *inst = net_to_ast_driver(net);
1611
+
1612
+ SigBit trig = State::S1;
1613
+
1614
+ if (clocking.cond_net != nullptr) {
1615
+ trig = importer->net_map_at(clocking.cond_net);
1616
+ if (!clocking.cond_pol)
1617
+ trig = module->Not(NEW_ID, trig);
1618
+ }
1619
+
1620
+ if (inst == nullptr)
1621
+ {
1622
+ if (trig != State::S1) {
1623
+ if (accept_p != nullptr)
1624
+ *accept_p = module->And(NEW_ID, trig, importer->net_map_at(net));
1625
+ if (reject_p != nullptr)
1626
+ *reject_p = module->And(NEW_ID, trig, module->Not(NEW_ID, importer->net_map_at(net)));
1627
+ } else {
1628
+ if (accept_p != nullptr)
1629
+ *accept_p = importer->net_map_at(net);
1630
+ if (reject_p != nullptr)
1631
+ *reject_p = module->Not(NEW_ID, importer->net_map_at(net));
1632
+ }
1633
+ }
1634
+ else
1635
+ if (inst->Type() == PRIM_SVA_OVERLAPPED_IMPLICATION ||
1636
+ inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION ||
1637
+ (mode_cover && (
1638
+ inst->Type() == PRIM_SVA_OVERLAPPED_FOLLOWED_BY ||
1639
+ inst->Type() == PRIM_SVA_NON_OVERLAPPED_FOLLOWED_BY)))
1640
+ {
1641
+ Net *antecedent_net = inst->GetInput1();
1642
+ Net *consequent_net = inst->GetInput2();
1643
+ int node;
1644
+
1645
+ SvaFsm antecedent_fsm(clocking, trig);
1646
+ antecedent_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1647
+ node = parse_sequence(antecedent_fsm, antecedent_fsm.createStartNode(), antecedent_net);
1648
+ if (inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION || inst->Type() == PRIM_SVA_NON_OVERLAPPED_FOLLOWED_BY) {
1649
+ int next_node = antecedent_fsm.createNode();
1650
+ antecedent_fsm.createEdge(node, next_node);
1651
+ node = next_node;
1652
+ }
1653
+
1654
+ Instance *consequent_inst = net_to_ast_driver(consequent_net);
1655
+
1656
+ if (consequent_inst && (consequent_inst->Type() == PRIM_SVA_UNTIL || consequent_inst->Type() == PRIM_SVA_S_UNTIL ||
1657
+ consequent_inst->Type() == PRIM_SVA_UNTIL_WITH || consequent_inst->Type() == PRIM_SVA_S_UNTIL_WITH ||
1658
+ consequent_inst->Type() == PRIM_SVA_ALWAYS || consequent_inst->Type() == PRIM_SVA_S_ALWAYS))
1659
+ {
1660
+ bool until_with = consequent_inst->Type() == PRIM_SVA_UNTIL_WITH || consequent_inst->Type() == PRIM_SVA_S_UNTIL_WITH;
1661
+
1662
+ Net *until_net = nullptr;
1663
+ if (consequent_inst->Type() == PRIM_SVA_ALWAYS || consequent_inst->Type() == PRIM_SVA_S_ALWAYS)
1664
+ {
1665
+ consequent_net = consequent_inst->GetInput();
1666
+ consequent_inst = net_to_ast_driver(consequent_net);
1667
+ }
1668
+ else
1669
+ {
1670
+ until_net = consequent_inst->GetInput2();
1671
+ consequent_net = consequent_inst->GetInput1();
1672
+ consequent_inst = net_to_ast_driver(consequent_net);
1673
+ }
1674
+
1675
+ SigBit until_sig = until_net ? parse_expression(until_net) : RTLIL::S0;
1676
+ SigBit not_until_sig = module->Not(NEW_ID, until_sig);
1677
+ antecedent_fsm.createEdge(node, node, not_until_sig);
1678
+
1679
+ antecedent_fsm.createLink(node, antecedent_fsm.acceptNode, until_with ? State::S1 : not_until_sig);
1680
+ }
1681
+ else
1682
+ {
1683
+ antecedent_fsm.createLink(node, antecedent_fsm.acceptNode);
1684
+ }
1685
+
1686
+ SigBit antecedent_match = antecedent_fsm.getAccept();
1687
+
1688
+ if (verific_verbose) {
1689
+ log(" Antecedent FSM:\n");
1690
+ antecedent_fsm.dump();
1691
+ }
1692
+
1693
+ bool consequent_not = false;
1694
+ if (consequent_inst && consequent_inst->Type() == PRIM_SVA_NOT) {
1695
+ consequent_not = true;
1696
+ consequent_net = consequent_inst->GetInput();
1697
+ consequent_inst = net_to_ast_driver(consequent_net);
1698
+ }
1699
+
1700
+ SvaFsm consequent_fsm(clocking, antecedent_match);
1701
+ consequent_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1702
+ node = parse_sequence(consequent_fsm, consequent_fsm.createStartNode(), consequent_net);
1703
+ consequent_fsm.createLink(node, consequent_fsm.acceptNode);
1704
+
1705
+ get_fsm_accept_reject(consequent_fsm, accept_p, reject_p, consequent_not);
1706
+
1707
+ if (verific_verbose) {
1708
+ log(" Consequent FSM:\n");
1709
+ consequent_fsm.dump();
1710
+ }
1711
+ }
1712
+ else
1713
+ {
1714
+ bool prop_not = inst->Type() == PRIM_SVA_NOT;
1715
+ if (prop_not) {
1716
+ net = inst->GetInput();
1717
+ inst = net_to_ast_driver(net);
1718
+ }
1719
+
1720
+ SvaFsm fsm(clocking, trig);
1721
+ fsm.parser_error = [&](std::string msg) { this->parser_error(msg); };
1722
+ int node = parse_sequence(fsm, fsm.createStartNode(), net);
1723
+ fsm.createLink(node, fsm.acceptNode);
1724
+
1725
+ get_fsm_accept_reject(fsm, accept_p, reject_p, prop_not);
1726
+
1727
+ if (verific_verbose) {
1728
+ log(" Sequence FSM:\n");
1729
+ fsm.dump();
1730
+ }
1731
+ }
1732
+ }
1733
+
1734
+ void import()
1735
+ {
1736
+ module = importer->module;
1737
+ netlist = root->Owner();
1738
+
1739
+ int initial_cell_count = GetSize(module->cells_);
1740
+ int initial_wire_count = GetSize(module->wires_);
1741
+ int initial_connection_count = GetSize(module->connections_);
1742
+
1743
+ if (verific_verbose)
1744
+ log(" importing SVA property at root cell %s (%s) at %s:%d.\n", root->Name(), root->View()->Owner()->Name(),
1745
+ LineFile::GetFileName(root->Linefile()), LineFile::GetLineNo(root->Linefile()));
1746
+
1747
+ bool is_user_declared = root->IsUserDeclared();
1748
+
1749
+ // FIXME
1750
+ if (!is_user_declared) {
1751
+ const char *name = root->Name();
1752
+ for (int i = 0; name[i]; i++) {
1753
+ if (i ? (name[i] < '0' || name[i] > '9') : (name[i] != 'i')) {
1754
+ is_user_declared = true;
1755
+ break;
1756
+ }
1757
+ }
1758
+ }
1759
+
1760
+ RTLIL::IdString root_name = module->uniquify(importer->mode_names || is_user_declared ? module->twines().add(RTLIL::escape_id(root->Name())) : module->twines().add(NEW_ID));
1761
+
1762
+ try
1763
+ {
1764
+ // parse SVA sequence into trigger signal
1765
+
1766
+ clocking = VerificClocking(importer, root->GetInput(), true);
1767
+ SigBit accept_bit = State::S0, reject_bit = State::S0;
1768
+
1769
+ if (clocking.body_net == nullptr)
1770
+ {
1771
+ if (clocking.clock_net != nullptr || clocking.enable_net != nullptr || clocking.disable_net != nullptr || clocking.cond_net != nullptr)
1772
+ parser_error(stringf("Failed to parse SVA clocking"), root);
1773
+
1774
+ if (mode_assert || mode_assume) {
1775
+ reject_bit = module->Not(NEW_ID, parse_expression(root->GetInput()));
1776
+ } else {
1777
+ accept_bit = parse_expression(root->GetInput());
1778
+ }
1779
+ }
1780
+ else
1781
+ {
1782
+ Net *net = clocking.body_net;
1783
+ SigBit trig;
1784
+
1785
+ if (eventually_property(net, trig))
1786
+ {
1787
+ SigBit sig_a, sig_en = trig;
1788
+ parse_property(net, &sig_a, nullptr);
1789
+
1790
+ // add final FF stage
1791
+
1792
+ SigBit sig_a_q, sig_en_q;
1793
+
1794
+ if (clocking.body_net == nullptr) {
1795
+ sig_a_q = sig_a;
1796
+ sig_en_q = sig_en;
1797
+ } else {
1798
+ sig_a_q = module->addWire(NEW_ID);
1799
+ sig_en_q = module->addWire(NEW_ID);
1800
+ clocking.addDff(NEW_ID, sig_a, sig_a_q, State::S0);
1801
+ clocking.addDff(NEW_ID, sig_en, sig_en_q, State::S0);
1802
+ }
1803
+
1804
+ // accept in disable case
1805
+
1806
+ if (clocking.disable_sig != State::S0)
1807
+ sig_a_q = module->Or(NEW_ID, sig_a_q, clocking.disable_sig);
1808
+
1809
+ // generate fair/live cell
1810
+
1811
+ RTLIL::Cell *c = nullptr;
1812
+
1813
+ if (mode_assert) c = module->addLive(root_name, sig_a_q, sig_en_q);
1814
+ if (mode_assume) c = module->addFair(root_name, sig_a_q, sig_en_q);
1815
+
1816
+ if (c) importer->import_attributes(c->attributes, root);
1817
+
1818
+ return;
1819
+ }
1820
+ else
1821
+ {
1822
+ if (mode_assert || mode_assume) {
1823
+ parse_property(net, nullptr, &reject_bit);
1824
+ } else {
1825
+ parse_property(net, &accept_bit, nullptr);
1826
+ }
1827
+ }
1828
+ }
1829
+
1830
+ if (mode_trigger)
1831
+ {
1832
+ module->connect(importer->net_map_at(root->GetOutput()), accept_bit);
1833
+ }
1834
+ else
1835
+ {
1836
+ SigBit sig_a = module->Not(NEW_ID, reject_bit);
1837
+ SigBit sig_en = module->Or(NEW_ID, accept_bit, reject_bit);
1838
+
1839
+ // add final FF stage
1840
+
1841
+ SigBit sig_a_q, sig_en_q;
1842
+
1843
+ if (clocking.body_net == nullptr) {
1844
+ sig_a_q = sig_a;
1845
+ sig_en_q = sig_en;
1846
+ } else {
1847
+ sig_a_q = module->addWire(NEW_ID);
1848
+ sig_en_q = module->addWire(NEW_ID);
1849
+ clocking.addDff(NEW_ID, sig_a, sig_a_q, State::S0);
1850
+ clocking.addDff(NEW_ID, sig_en, sig_en_q, State::S0);
1851
+ }
1852
+
1853
+ // generate assert/assume/cover cell
1854
+
1855
+ RTLIL::Cell *c = nullptr;
1856
+
1857
+ if (mode_assert) c = module->addAssert(root_name, sig_a_q, sig_en_q);
1858
+ if (mode_assume) c = module->addAssume(root_name, sig_a_q, sig_en_q);
1859
+ if (mode_cover) c = module->addCover(root_name, sig_a_q, sig_en_q);
1860
+
1861
+ if (c) {
1862
+ c->set_bool_attribute(ID(keep));
1863
+ importer->import_attributes(c->attributes, root);
1864
+ }
1865
+ }
1866
+ }
1867
+ catch (ParserErrorException)
1868
+ {
1869
+ if (importer->mode_sva_continue) {
1870
+
1871
+ std::vector<Cell *> remove_cells;
1872
+ pool<Wire *> remove_wires;
1873
+
1874
+ for (int i = 0, end = GetSize(module->cells_) - initial_cell_count; i != end; ++i)
1875
+ remove_cells.push_back(module->cells_.element(i)->second);
1876
+
1877
+ for (int i = 0, end = GetSize(module->wires_) - initial_wire_count; i != end; ++i)
1878
+ remove_wires.emplace(module->wires_.element(i)->second);
1879
+
1880
+ for (auto cell : remove_cells)
1881
+ module->remove(cell);
1882
+ module->remove(remove_wires);
1883
+
1884
+ module->connections_.resize(initial_connection_count);
1885
+
1886
+ RTLIL::Cell *c = nullptr;
1887
+
1888
+ if (mode_assert) c = module->addAssert(root_name, State::Sx, State::Sx);
1889
+ if (mode_assume) c = module->addAssume(root_name, State::Sx, State::Sx);
1890
+ if (mode_cover) c = module->addCover(root_name, State::Sx, State::Sx);
1891
+
1892
+ if (c) {
1893
+ importer->import_attributes(c->attributes, root);
1894
+ c->set_bool_attribute(ID(unsupported_sva));
1895
+ }
1896
+
1897
+ importer->num_sva_continue++;
1898
+ }
1899
+ }
1900
+ }
1901
+ };
1902
+
1903
+ void verific_import_sva_assert(VerificImporter *importer, Instance *inst)
1904
+ {
1905
+ VerificSvaImporter worker;
1906
+ worker.importer = importer;
1907
+ worker.root = inst;
1908
+ worker.mode_assert = true;
1909
+ worker.import();
1910
+ }
1911
+
1912
+ void verific_import_sva_assume(VerificImporter *importer, Instance *inst)
1913
+ {
1914
+ VerificSvaImporter worker;
1915
+ worker.importer = importer;
1916
+ worker.root = inst;
1917
+ worker.mode_assume = true;
1918
+ worker.import();
1919
+ }
1920
+
1921
+ void verific_import_sva_cover(VerificImporter *importer, Instance *inst)
1922
+ {
1923
+ VerificSvaImporter worker;
1924
+ worker.importer = importer;
1925
+ worker.root = inst;
1926
+ worker.mode_cover = true;
1927
+ worker.import();
1928
+ }
1929
+
1930
+ void verific_import_sva_trigger(VerificImporter *importer, Instance *inst)
1931
+ {
1932
+ VerificSvaImporter worker;
1933
+ worker.importer = importer;
1934
+ worker.root = inst;
1935
+ worker.mode_trigger = true;
1936
+ worker.import();
1937
+ }
1938
+
1939
+ bool verific_is_sva_net(VerificImporter *importer, Verific::Net *net)
1940
+ {
1941
+ VerificSvaImporter worker;
1942
+ worker.importer = importer;
1943
+ return worker.net_to_ast_driver(net) != nullptr;
1944
+ }
1945
+ #else
1946
+ YOSYS_NAMESPACE_BEGIN
1947
+ pool<int> verific_sva_prims = {};
1948
+ #endif
1949
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verilog/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ verilog_lexer.cc
2
+ verilog_parser.output
3
+ verilog_parser.tab.cc
4
+ verilog_parser.tab.hh
chips/yosys/frontends/verilog/CMakeLists.txt ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if (NOT FLEX_INCLUDE_DIRS)
2
+ set(FLEX_INCLUDE_DIRS ${YOSYS_CMAKE_SOURCE_DIR}/libs/flex)
3
+ endif()
4
+
5
+ flex_target(verilog_lexer
6
+ verilog_lexer.l
7
+ verilog_lexer.cc
8
+ )
9
+ bison_target(verilog_parser
10
+ verilog_parser.y
11
+ verilog_parser.tab.cc
12
+ # (requires CMake 4.0)
13
+ # OPTIONS
14
+ # -Wall -Werror
15
+ )
16
+ yosys_frontend(verilog
17
+ const2ast.cc
18
+ preproc.cc
19
+ preproc.h
20
+ verilog_error.cc
21
+ verilog_error.h
22
+ verilog_frontend.cc
23
+ verilog_frontend.h
24
+ verilog_lexer.h
25
+ verilog_location.h
26
+ ${FLEX_verilog_lexer_OUTPUTS}
27
+ ${BISON_verilog_parser_OUTPUTS}
28
+ INCLUDE_DIRS
29
+ ${FLEX_INCLUDE_DIRS}
30
+ REQUIRES
31
+ sha1
32
+ ast
33
+ PROVIDES
34
+ verilog_defaults
35
+ verilog_defines
36
+ read_verilog_file_list
37
+ ESSENTIAL
38
+ )
39
+ set_source_files_properties(
40
+ ${BISON_verilog_parser_OUTPUT_SOURCE}
41
+ PROPERTIES
42
+ COMPILE_DEFINITIONS -DYYMAXDEPTH=10000000
43
+ )
chips/yosys/frontends/verilog/const2ast.cc ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * The Verilog frontend.
21
+ *
22
+ * This frontend is using the AST frontend library (see frontends/ast/).
23
+ * Thus this frontend does not generate RTLIL code directly but creates an
24
+ * AST directly from the Verilog parse tree and then passes this AST to
25
+ * the AST frontend library.
26
+ *
27
+ * ---
28
+ *
29
+ * This file contains an ad-hoc parser for Verilog constants. The Verilog
30
+ * lexer does only recognize a constant but does not actually split it to its
31
+ * components. I.e. it just passes the Verilog code for the constant to the
32
+ * bison parser. The parser then uses the function const2ast() from this file
33
+ * to create an AST node for the constant.
34
+ *
35
+ */
36
+
37
+ #include "verilog_frontend.h"
38
+ #include "kernel/log.h"
39
+ #include "kernel/register.h"
40
+ #include <string.h>
41
+ #include <math.h>
42
+
43
+ YOSYS_NAMESPACE_BEGIN
44
+
45
+ using namespace AST;
46
+ using namespace VERILOG_FRONTEND;
47
+
48
+ void ConstParser::log_maybe_loc_error(std::string msg) {
49
+ if (loc.begin.filename)
50
+ log_file_error(loc.to_loc(), "%s\n", msg);
51
+ else if (!Frontend::current_script_filename.empty())
52
+ log_file_error(LogSourceLocation(Frontend::current_script_filename, Frontend::current_script_lineno),
53
+ "Failed to parse constant `%s': %s\n", code_str, msg);
54
+ else
55
+ log_error("Failed to parse constant `%s': %s\n", code_str, msg);
56
+ }
57
+
58
+ void ConstParser::log_maybe_loc_warn(std::string msg) {
59
+ if (loc.begin.filename)
60
+ log_file_warning(loc.to_loc(), "%s\n", msg);
61
+ else if (!Frontend::current_script_filename.empty())
62
+ log_file_warning(LogSourceLocation(Frontend::current_script_filename, Frontend::current_script_lineno),
63
+ "While parsing constant `%s': %s\n", code_str, msg);
64
+ else
65
+ log_warning("While parsing constant `%s': %s\n", code_str, msg);
66
+ }
67
+
68
+ // divide an arbitrary length decimal number by two and return the rest
69
+ int ConstParser::my_decimal_div_by_two(std::vector<uint8_t> &digits)
70
+ {
71
+ int carry = 0;
72
+ for (size_t i = 0; i < digits.size(); i++) {
73
+ if (digits[i] >= 10)
74
+ log_maybe_loc_error("Invalid use of [a-fxz?] in decimal constant.");
75
+ digits[i] += carry * 10;
76
+ carry = digits[i] % 2;
77
+ digits[i] /= 2;
78
+ }
79
+ while (!digits.empty() && !digits.front())
80
+ digits.erase(digits.begin());
81
+ return carry;
82
+ }
83
+
84
+ // find the number of significant bits in a binary number (not including the sign bit)
85
+ int ConstParser::my_ilog2(int x)
86
+ {
87
+ int ret = 0;
88
+ while (x != 0 && x != -1) {
89
+ x = x >> 1;
90
+ ret++;
91
+ }
92
+ return ret;
93
+ }
94
+
95
+ // parse a binary, decimal, hexadecimal or octal number with support for special bits ('x', 'z' and '?')
96
+ void ConstParser::my_strtobin(std::vector<RTLIL::State> &data, const char *str, int len_in_bits, int base, char case_type, bool is_unsized)
97
+ {
98
+ // all digits in string (MSB at index 0)
99
+ std::vector<uint8_t> digits;
100
+
101
+ while (*str) {
102
+ if ('0' <= *str && *str <= '9')
103
+ digits.push_back(*str - '0');
104
+ else if ('a' <= *str && *str <= 'f')
105
+ digits.push_back(10 + *str - 'a');
106
+ else if ('A' <= *str && *str <= 'F')
107
+ digits.push_back(10 + *str - 'A');
108
+ else if (*str == 'x' || *str == 'X')
109
+ digits.push_back(0xf0);
110
+ else if (*str == 'z' || *str == 'Z' || *str == '?')
111
+ digits.push_back(0xf1);
112
+ str++;
113
+ }
114
+
115
+ if (base == 10 && GetSize(digits) == 1 && digits.front() >= 0xf0)
116
+ base = 2;
117
+
118
+ data.clear();
119
+
120
+ if (base == 10) {
121
+ while (!digits.empty())
122
+ data.push_back(my_decimal_div_by_two(digits) ? State::S1 : State::S0);
123
+ } else {
124
+ int bits_per_digit = my_ilog2(base-1);
125
+ for (auto it = digits.rbegin(), e = digits.rend(); it != e; it++) {
126
+ if (*it > (base-1) && *it < 0xf0)
127
+ log_maybe_loc_error(stringf("Digit larger than %d used in in base-%d constant.",
128
+ base-1, base));
129
+ for (int i = 0; i < bits_per_digit; i++) {
130
+ int bitmask = 1 << i;
131
+ if (*it == 0xf0)
132
+ data.push_back(case_type == 'x' ? RTLIL::Sa : RTLIL::Sx);
133
+ else if (*it == 0xf1)
134
+ data.push_back(case_type == 'x' || case_type == 'z' ? RTLIL::Sa : RTLIL::Sz);
135
+ else
136
+ data.push_back((*it & bitmask) ? State::S1 : State::S0);
137
+ }
138
+ }
139
+ }
140
+
141
+ int len = GetSize(data);
142
+ RTLIL::State msb = data.empty() ? State::S0 : data.back();
143
+
144
+ if (len_in_bits < 0) {
145
+ if (len < 32)
146
+ data.resize(32, msb == State::S0 || msb == State::S1 ? RTLIL::S0 : msb);
147
+ return;
148
+ }
149
+
150
+ if (is_unsized && (len > len_in_bits))
151
+ log_maybe_loc_error(stringf("Unsized constant must have width of 1 bit, but have %d bits!", len));
152
+
153
+ for (len = len - 1; len >= 0; len--)
154
+ if (data[len] == State::S1)
155
+ break;
156
+ if (msb == State::S0 || msb == State::S1) {
157
+ len += 1;
158
+ data.resize(len_in_bits, State::S0);
159
+ } else {
160
+ len += 2;
161
+ data.resize(len_in_bits, msb);
162
+ }
163
+
164
+ if (len_in_bits == 0)
165
+ log_maybe_loc_error("Illegal integer constant size of zero (IEEE 1800-2012, 5.7).");
166
+
167
+ if (len > len_in_bits)
168
+ log_maybe_loc_warn(stringf("Literal has a width of %d bit, but value requires %d bit.",
169
+ len_in_bits, len));
170
+ }
171
+ // convert the Verilog code for a constant to an AST node
172
+ std::unique_ptr<AstNode> ConstParser::const2ast(std::string code, char case_type, bool warn_z)
173
+ {
174
+ code_str = code;
175
+
176
+ if (warn_z) {
177
+ auto ret = const2ast(code, case_type);
178
+ if (ret != nullptr && std::find(ret->bits.begin(), ret->bits.end(), RTLIL::State::Sz) != ret->bits.end())
179
+ log_maybe_loc_warn("Yosys has only limited support for tri-state logic at the moment.");
180
+ return ret;
181
+ }
182
+
183
+ const char *str = code.c_str();
184
+
185
+ // Strings
186
+ if (*str == '"') {
187
+ int len = strlen(str) - 2;
188
+ std::vector<RTLIL::State> data;
189
+ data.reserve(len * 8);
190
+ for (int i = 0; i < len; i++) {
191
+ unsigned char ch = str[len - i];
192
+ for (int j = 0; j < 8; j++) {
193
+ data.push_back((ch & 1) ? State::S1 : State::S0);
194
+ ch = ch >> 1;
195
+ }
196
+ }
197
+ auto ast = AstNode::mkconst_bits(loc, data, false);
198
+ ast->str = code;
199
+ return ast;
200
+ }
201
+
202
+ for (size_t i = 0; i < code.size(); i++)
203
+ if (code[i] == '_' || code[i] == ' ' || code[i] == '\t' || code[i] == '\r' || code[i] == '\n')
204
+ code.erase(code.begin()+(i--));
205
+ str = code.c_str();
206
+
207
+ char *endptr;
208
+ long len_in_bits = strtol(str, &endptr, 10);
209
+
210
+ // Simple base-10 integer
211
+ if (*endptr == 0) {
212
+ std::vector<RTLIL::State> data;
213
+ my_strtobin(data, str, -1, 10, case_type, false);
214
+ if (data.back() == State::S1)
215
+ data.push_back(State::S0);
216
+ return AstNode::mkconst_bits(loc, data, true);
217
+ }
218
+
219
+ // unsized constant
220
+ if (str == endptr)
221
+ len_in_bits = -1;
222
+
223
+ // The "<bits>'[sS]?[bodhBODH]<digits>" syntax
224
+ if (*endptr == '\'')
225
+ {
226
+ std::vector<RTLIL::State> data;
227
+ bool is_signed = false;
228
+ bool is_unsized = len_in_bits < 0;
229
+ if (*(endptr+1) == 's' || *(endptr+1) == 'S') {
230
+ is_signed = true;
231
+ endptr++;
232
+ }
233
+ switch (*(endptr+1))
234
+ {
235
+ case 'b':
236
+ case 'B':
237
+ my_strtobin(data, endptr+2, len_in_bits, 2, case_type, is_unsized);
238
+ break;
239
+ case 'o':
240
+ case 'O':
241
+ my_strtobin(data, endptr+2, len_in_bits, 8, case_type, is_unsized);
242
+ break;
243
+ case 'd':
244
+ case 'D':
245
+ my_strtobin(data, endptr+2, len_in_bits, 10, case_type, is_unsized);
246
+ break;
247
+ case 'h':
248
+ case 'H':
249
+ my_strtobin(data, endptr+2, len_in_bits, 16, case_type, is_unsized);
250
+ break;
251
+ default:
252
+ char next_char = char(tolower(*(endptr+1)));
253
+ if (next_char == '0' || next_char == '1' || next_char == 'x' || next_char == 'z') {
254
+ is_unsized = true;
255
+ my_strtobin(data, endptr+1, 1, 2, case_type, is_unsized);
256
+ } else {
257
+ return NULL;
258
+ }
259
+ }
260
+ if (len_in_bits < 0) {
261
+ if (is_signed && data.back() == State::S1)
262
+ data.push_back(State::S0);
263
+ }
264
+ return AstNode::mkconst_bits(loc, data, is_signed, is_unsized);
265
+ }
266
+
267
+ return NULL;
268
+ }
269
+
270
+
271
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verilog/preproc.cc ADDED
@@ -0,0 +1,1006 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * The Verilog frontend.
21
+ *
22
+ * This frontend is using the AST frontend library (see frontends/ast/).
23
+ * Thus this frontend does not generate RTLIL code directly but creates an
24
+ * AST directly from the Verilog parse tree and then passes this AST to
25
+ * the AST frontend library.
26
+ *
27
+ * ---
28
+ *
29
+ * Ad-hoc implementation of a Verilog preprocessor. The directives `define,
30
+ * `include, `ifdef, `ifndef, `else and `endif are handled here. All other
31
+ * directives are handled by the lexer (see verilog_lexer.l).
32
+ *
33
+ */
34
+
35
+ #include "preproc.h"
36
+ #include "verilog_frontend.h"
37
+ #include "frontends/verilog/verilog_parser.tab.hh"
38
+ #include "kernel/log.h"
39
+ #include <assert.h>
40
+ #include <stack>
41
+ #include <stdarg.h>
42
+ #include <stdio.h>
43
+ #include <string.h>
44
+
45
+ YOSYS_NAMESPACE_BEGIN
46
+ using namespace VERILOG_FRONTEND;
47
+
48
+ static std::list<std::string> output_code;
49
+ static std::list<std::string> input_buffer;
50
+ static size_t input_buffer_charp;
51
+
52
+ static void return_char(char ch)
53
+ {
54
+ if (input_buffer_charp == 0)
55
+ input_buffer.push_front(std::string() + ch);
56
+ else
57
+ input_buffer.front()[--input_buffer_charp] = ch;
58
+ }
59
+
60
+ static void insert_input(std::string str)
61
+ {
62
+ if (input_buffer_charp != 0) {
63
+ input_buffer.front() = input_buffer.front().substr(input_buffer_charp);
64
+ input_buffer_charp = 0;
65
+ }
66
+ input_buffer.push_front(str);
67
+ }
68
+
69
+ static char next_char()
70
+ {
71
+ if (input_buffer.empty())
72
+ return 0;
73
+
74
+ log_assert(input_buffer_charp <= input_buffer.front().size());
75
+ if (input_buffer_charp == input_buffer.front().size()) {
76
+ input_buffer_charp = 0;
77
+ input_buffer.pop_front();
78
+ return next_char();
79
+ }
80
+
81
+ char ch = input_buffer.front()[input_buffer_charp++];
82
+ return ch == '\r' ? next_char() : ch;
83
+ }
84
+
85
+ static std::string skip_spaces()
86
+ {
87
+ std::string spaces;
88
+ while (1) {
89
+ char ch = next_char();
90
+ if (ch == 0)
91
+ break;
92
+ if (ch != ' ' && ch != '\t') {
93
+ return_char(ch);
94
+ break;
95
+ }
96
+ spaces += ch;
97
+ }
98
+ return spaces;
99
+ }
100
+
101
+ static std::string next_token(bool pass_newline = false)
102
+ {
103
+ std::string token;
104
+
105
+ char ch = next_char();
106
+ if (ch == 0)
107
+ return token;
108
+
109
+ token += ch;
110
+ if (ch == '\n') {
111
+ if (pass_newline) {
112
+ output_code.push_back(token);
113
+ return "";
114
+ }
115
+ return token;
116
+ }
117
+
118
+ if (ch == ' ' || ch == '\t')
119
+ {
120
+ while ((ch = next_char()) != 0) {
121
+ if (ch != ' ' && ch != '\t') {
122
+ return_char(ch);
123
+ break;
124
+ }
125
+ token += ch;
126
+ }
127
+ }
128
+ else if (ch == '"')
129
+ {
130
+ while ((ch = next_char()) != 0) {
131
+ token += ch;
132
+ if (ch == '"')
133
+ break;
134
+ if (ch == '\\') {
135
+ if ((ch = next_char()) != 0)
136
+ token += ch;
137
+ }
138
+ }
139
+ if (token == "\"\"" && (ch = next_char()) != 0) {
140
+ if (ch == '"')
141
+ token += ch;
142
+ else
143
+ return_char(ch);
144
+ }
145
+ }
146
+ else if (ch == '\\')
147
+ {
148
+ while ((ch = next_char()) != 0) {
149
+ if (ch < 33 || ch > 126) {
150
+ return_char(ch);
151
+ break;
152
+ }
153
+ token += ch;
154
+ }
155
+ }
156
+ else if (ch == '/')
157
+ {
158
+ if ((ch = next_char()) != 0) {
159
+ if (ch == '/') {
160
+ token += '*';
161
+ char last_ch = 0;
162
+ while ((ch = next_char()) != 0) {
163
+ if (ch == '\n') {
164
+ return_char(ch);
165
+ break;
166
+ }
167
+ if (last_ch != '*' || ch != '/') {
168
+ token += ch;
169
+ last_ch = ch;
170
+ }
171
+ }
172
+ token += " */";
173
+ }
174
+ else if (ch == '*') {
175
+ token += '*';
176
+ int newline_count = 0;
177
+ char last_ch = 0;
178
+ while ((ch = next_char()) != 0) {
179
+ if (ch == '\n') {
180
+ newline_count++;
181
+ token += ' ';
182
+ } else
183
+ token += ch;
184
+ if (last_ch == '*' && ch == '/')
185
+ break;
186
+ last_ch = ch;
187
+ }
188
+ while (newline_count-- > 0)
189
+ return_char('\n');
190
+ }
191
+ else
192
+ return_char(ch);
193
+ }
194
+ }
195
+ else
196
+ {
197
+ const char *ok = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ$0123456789";
198
+ if (ch == '`' || strchr(ok, ch) != NULL)
199
+ {
200
+ char first = ch;
201
+ ch = next_char();
202
+ if (first == '`' && (ch == '"' || ch == '`')) {
203
+ token += ch;
204
+ } else do {
205
+ if (strchr(ok, ch) == NULL) {
206
+ return_char(ch);
207
+ break;
208
+ }
209
+ token += ch;
210
+ } while ((ch = next_char()) != 0);
211
+ }
212
+ }
213
+ return token;
214
+ }
215
+
216
+ struct macro_arg_t
217
+ {
218
+ macro_arg_t(const std::string &name_, const char *default_value_)
219
+ : name(name_),
220
+ has_default(default_value_ != nullptr),
221
+ default_value(default_value_ ? default_value_ : "")
222
+ {}
223
+
224
+ std::string name;
225
+ bool has_default;
226
+ std::string default_value;
227
+ };
228
+
229
+ static bool all_white(const std::string &str)
230
+ {
231
+ for (char c : str)
232
+ if (!isspace(c))
233
+ return false;
234
+ return true;
235
+ }
236
+
237
+ struct arg_map_t
238
+ {
239
+ arg_map_t()
240
+ {}
241
+
242
+ void add_arg(const std::string &name, const char *default_value)
243
+ {
244
+ if (find(name)) {
245
+ log_error("Duplicate macro arguments with name `%s'.\n", name);
246
+ }
247
+
248
+ name_to_pos[name] = args.size();
249
+ args.push_back(macro_arg_t(name, default_value));
250
+ }
251
+
252
+ // Find an argument by name; return nullptr if it doesn't exist. If pos is not null, write
253
+ // the argument's position to it on success.
254
+ const macro_arg_t *find(const std::string &name, int *pos = nullptr) const
255
+ {
256
+ auto it = name_to_pos.find(name);
257
+ if (it == name_to_pos.end())
258
+ return nullptr;
259
+
260
+ if (pos) *pos = it->second;
261
+ return &args[it->second];
262
+ }
263
+
264
+ // Construct the name for the local macro definition we use for the given argument
265
+ // (something like macro_foobar_arg2). This doesn't include the leading backtick.
266
+ static std::string str_token(const std::string &macro_name, int pos)
267
+ {
268
+ return stringf("macro_%s_arg%d", macro_name, pos);
269
+ }
270
+
271
+ // Return definitions for the macro arguments (so that substituting in the macro body and
272
+ // then performing macro expansion will do argument substitution properly).
273
+ std::vector<std::pair<std::string, std::string>>
274
+ get_vals(const std::string &macro_name, const std::vector<std::string> &arg_vals) const
275
+ {
276
+ std::vector<std::pair<std::string, std::string>> ret;
277
+ for (int i = 0; i < GetSize(args); ++ i) {
278
+ // The SystemVerilog rules are:
279
+ //
280
+ // - If the call site specifies an argument and it's not whitespace, use
281
+ // it.
282
+ //
283
+ // - Otherwise, if the argument has a default value, use it.
284
+ //
285
+ // - Otherwise, if the call site specified whitespace, use that.
286
+ //
287
+ // - Otherwise, error.
288
+ const std::string *dflt = nullptr;
289
+ if (args[i].has_default)
290
+ dflt = &args[i].default_value;
291
+
292
+ const std::string *given = nullptr;
293
+ if (i < GetSize(arg_vals))
294
+ given = &arg_vals[i];
295
+
296
+ const std::string *val = nullptr;
297
+ if (given && (! (dflt && all_white(*given))))
298
+ val = given;
299
+ else if (dflt)
300
+ val = dflt;
301
+ else if (given)
302
+ val = given;
303
+ else
304
+ log_error("Cannot expand macro `%s by giving only %d argument%s "
305
+ "(argument %d has no default).\n",
306
+ macro_name, GetSize(arg_vals),
307
+ (GetSize(arg_vals) == 1 ? "" : "s"), i + 1);
308
+
309
+ assert(val);
310
+ ret.push_back(std::make_pair(str_token(macro_name, i), * val));
311
+ }
312
+ return ret;
313
+ }
314
+
315
+
316
+ std::vector<macro_arg_t> args;
317
+ std::map<std::string, int> name_to_pos;
318
+ };
319
+
320
+ struct define_body_t
321
+ {
322
+ define_body_t(const std::string &body, const arg_map_t *args = nullptr)
323
+ : body(body),
324
+ has_args(args != nullptr),
325
+ args(args ? *args : arg_map_t())
326
+ {}
327
+
328
+ std::string body;
329
+ bool has_args;
330
+ arg_map_t args;
331
+ };
332
+
333
+ define_map_t::define_map_t()
334
+ {
335
+ add("YOSYS", "1");
336
+ }
337
+
338
+ // We must define this destructor here (rather than relying on the default), because we need to
339
+ // define it somewhere we've got a complete definition of define_body_t.
340
+ define_map_t::~define_map_t()
341
+ {}
342
+
343
+ void
344
+ define_map_t::add(const std::string &name, const std::string &txt, const arg_map_t *args)
345
+ {
346
+ defines[name] = std::unique_ptr<define_body_t>(new define_body_t(txt, args));
347
+ }
348
+
349
+ void define_map_t::add(const std::string &name, const define_body_t &body)
350
+ {
351
+ defines[name] = std::unique_ptr<define_body_t>(new define_body_t(body));
352
+ }
353
+
354
+ void define_map_t::merge(const define_map_t &map)
355
+ {
356
+ for (const auto &pr : map.defines) {
357
+ // These contortions are so that we take a copy of each definition body in
358
+ // map.defines.
359
+ defines[pr.first] = std::unique_ptr<define_body_t>(new define_body_t(*pr.second));
360
+ }
361
+ }
362
+
363
+ const define_body_t *define_map_t::find(const std::string &name) const
364
+ {
365
+ auto it = defines.find(name);
366
+ return (it == defines.end()) ? nullptr : it->second.get();
367
+ }
368
+
369
+ void define_map_t::erase(const std::string &name)
370
+ {
371
+ defines.erase(name);
372
+ }
373
+
374
+ void define_map_t::clear()
375
+ {
376
+ defines.clear();
377
+ }
378
+
379
+ void define_map_t::log() const
380
+ {
381
+ for (auto &it : defines) {
382
+ const std::string &name = it.first;
383
+ const define_body_t &body = *it.second;
384
+ Yosys::log("`define %s%s %s\n",
385
+ name, body.has_args ? "()" : "", body.body);
386
+ }
387
+ }
388
+
389
+ static void input_file(std::istream &f, std::string filename)
390
+ {
391
+ char buffer[513];
392
+ int rc;
393
+
394
+ insert_input("");
395
+ auto it = input_buffer.begin();
396
+
397
+ input_buffer.insert(it, "`file_push \"" + filename + "\"\n");
398
+ while ((rc = readsome(f, buffer, sizeof(buffer)-1)) > 0) {
399
+ buffer[rc] = 0;
400
+ input_buffer.insert(it, buffer);
401
+ }
402
+ input_buffer.insert(it, "\n`file_pop\n");
403
+ }
404
+
405
+ static bool is_blank_token(const std::string &tok)
406
+ {
407
+ return tok.empty() || tok[0] == ' ' || tok[0] == '\t' || tok.compare(0, 2, "/*") == 0;
408
+ }
409
+
410
+ // Read tokens to get one argument (either a macro argument at a callsite or a default argument in a
411
+ // macro definition). Writes the argument to dest. Returns true if we finished with ')' (the end of
412
+ // the argument list); false if we finished with ','.
413
+ static bool read_argument(std::string &dest)
414
+ {
415
+ std::vector<char> openers;
416
+ bool pending_space = false;
417
+ for (;;) {
418
+ std::string tok = next_token(true);
419
+ if (is_blank_token(tok)) {
420
+ pending_space = !dest.empty();
421
+ continue;
422
+ }
423
+ if (openers.empty() && (tok == ")" || tok == ","))
424
+ return tok == ")";
425
+ if (pending_space)
426
+ dest += ' ';
427
+ pending_space = false;
428
+
429
+ if (tok == ")") {
430
+ if (openers.back() != '(')
431
+ log_error("Mismatched brackets in macro argument: %c and %c.\n",
432
+ openers.back(), tok[0]);
433
+
434
+ openers.pop_back();
435
+ dest += tok;
436
+ continue;
437
+ }
438
+ if (tok == "]") {
439
+ char opener = openers.empty() ? '(' : openers.back();
440
+ if (opener != '[')
441
+ log_error("Mismatched brackets in macro argument: %c and %c.\n",
442
+ opener, tok[0]);
443
+
444
+ openers.pop_back();
445
+ dest += tok;
446
+ continue;
447
+ }
448
+ if (tok == "}") {
449
+ char opener = openers.empty() ? '(' : openers.back();
450
+ if (opener != '{')
451
+ log_error("Mismatched brackets in macro argument: %c and %c.\n",
452
+ opener, tok[0]);
453
+
454
+ openers.pop_back();
455
+ dest += tok;
456
+ continue;
457
+ }
458
+
459
+ if (tok == "(" || tok == "[" || tok == "{")
460
+ openers.push_back(tok[0]);
461
+
462
+ dest += tok;
463
+ }
464
+ }
465
+
466
+ using macro_arg_stack_t = std::stack<std::pair<std::string, define_body_t>>;
467
+
468
+ static void restore_macro_arg(define_map_t &defines, macro_arg_stack_t &macro_arg_stack)
469
+ {
470
+ log_assert(!macro_arg_stack.empty());
471
+ auto &overwritten_arg = macro_arg_stack.top();
472
+ defines.add(overwritten_arg.first, overwritten_arg.second);
473
+ macro_arg_stack.pop();
474
+ }
475
+
476
+ static bool try_expand_macro(define_map_t &defines, macro_arg_stack_t &macro_arg_stack, std::string &tok)
477
+ {
478
+ if (tok == "`\"") {
479
+ std::string literal("\"");
480
+ // Expand string literal
481
+ while (!input_buffer.empty()) {
482
+ std::string ntok = next_token();
483
+ if (ntok == "`\"") {
484
+ insert_input(literal+"\"");
485
+ return true;
486
+ } else if (!try_expand_macro(defines, macro_arg_stack, ntok)) {
487
+ literal += ntok;
488
+ }
489
+ }
490
+ return false; // error - unmatched `"
491
+ }
492
+
493
+ if (tok == "``") {
494
+ // Swallow `` in macro expansion
495
+ return true;
496
+ }
497
+
498
+ if (tok.size() <= 1 || tok[0] != '`')
499
+ return false;
500
+
501
+ // This token looks like a macro name (`foo).
502
+ std::string macro_name = tok.substr(1);
503
+ const define_body_t *body = defines.find(tok.substr(1));
504
+
505
+ if (! body) {
506
+ // Apparently not a name we know.
507
+ return false;
508
+ }
509
+
510
+ std::string name = tok.substr(1);
511
+ std::string skipped_spaces = skip_spaces();
512
+ tok = next_token(false);
513
+ if (body->has_args) {
514
+ if (tok != "(") {
515
+ if (tok.size() == 1 && iscntrl(tok[0])) {
516
+ char buf[5];
517
+ snprintf(buf, sizeof(buf), "\\x%02x", tok[0]);
518
+ tok = buf;
519
+ }
520
+ log_error("Expected to find '(' to begin macro arguments for '%s', but instead found '%s'\n",
521
+ name, tok);
522
+ }
523
+ std::vector<std::string> args;
524
+ bool done = false;
525
+ while (!done) {
526
+ std::string arg;
527
+ done = read_argument(arg);
528
+ args.push_back(arg);
529
+ }
530
+ for (const auto &pr : body->args.get_vals(name, args)) {
531
+ if (const define_body_t *existing = defines.find(pr.first)) {
532
+ macro_arg_stack.push({pr.first, *existing});
533
+ insert_input("`__restore_macro_arg ");
534
+ }
535
+ defines.add(pr.first, pr.second);
536
+ }
537
+ } else {
538
+ insert_input(tok);
539
+ insert_input(skipped_spaces);
540
+ }
541
+ insert_input(body->body);
542
+ return true;
543
+ }
544
+
545
+ // Read the arguments for a `define preprocessor directive with formal arguments. This is called
546
+ // just after reading the token containing "(". Returns the number of newlines to emit afterwards to
547
+ // keep line numbers in sync, together with the map from argument name to data (pos and default
548
+ // value).
549
+ static std::pair<int, arg_map_t>
550
+ read_define_args()
551
+ {
552
+ // Each argument looks like one of the following:
553
+ //
554
+ // identifier
555
+ // identifier = default_text
556
+ // identifier =
557
+ //
558
+ // The first example is an argument with no default value. The second is an argument whose
559
+ // default value is default_text. The third is an argument with default value the empty
560
+ // string.
561
+
562
+ int newline_count = 0;
563
+ arg_map_t args;
564
+
565
+ // FSM state.
566
+ //
567
+ // 0: At start of identifier
568
+ // 1: After identifier (stored in arg_name)
569
+ // 2: After closing paren
570
+ int state = 0;
571
+
572
+ std::string arg_name, default_val;
573
+
574
+ skip_spaces();
575
+ for (;;) {
576
+ if (state == 2)
577
+ // We've read the closing paren.
578
+ break;
579
+
580
+ std::string tok = next_token();
581
+
582
+ // Cope with escaped EOLs
583
+ if (tok == "\\") {
584
+ char ch = next_char();
585
+ if (ch == '\n') {
586
+ // Eat the \, the \n and any trailing space and keep going.
587
+ skip_spaces();
588
+ continue;
589
+ } else {
590
+ // There aren't any other situations where a backslash makes sense.
591
+ log_error("Backslash in macro arguments (not at end of line).\n");
592
+ }
593
+ }
594
+
595
+ switch (state) {
596
+ case 0:
597
+ // At start of argument. If the token is ')', we've presumably just seen
598
+ // something like "`define foo() ...". Set state to 2 to finish. Otherwise,
599
+ // the token should be a valid simple identifier, but we'll allow anything
600
+ // here.
601
+ if (tok == ")") {
602
+ state = 2;
603
+ } else {
604
+ arg_name = tok;
605
+ state = 1;
606
+ }
607
+ skip_spaces();
608
+ break;
609
+
610
+ case 1:
611
+ // After argument. The token should either be an equals sign or a comma or
612
+ // closing paren.
613
+ if (tok == "=") {
614
+ std::string default_val;
615
+ //Read an argument into default_val and set state to 2 if we're at
616
+ // the end; 0 if we hit a comma.
617
+ state = read_argument(default_val) ? 2 : 0;
618
+ args.add_arg(arg_name, default_val.c_str());
619
+ skip_spaces();
620
+ break;
621
+ }
622
+ if (tok == ",") {
623
+ // Take the identifier as an argument with no default value.
624
+ args.add_arg(arg_name, nullptr);
625
+ state = 0;
626
+ skip_spaces();
627
+ break;
628
+ }
629
+ if (tok == ")") {
630
+ // As with comma, but set state to 2 (end of args)
631
+ args.add_arg(arg_name, nullptr);
632
+ state = 2;
633
+ skip_spaces();
634
+ break;
635
+ }
636
+ log_error("Trailing contents after identifier in macro argument `%s': "
637
+ "expected '=', ',' or ')'.\n",
638
+ arg_name);
639
+
640
+ default:
641
+ // The only FSM states are 0-2 and we dealt with 2 at the start of the loop.
642
+ log_assert(false);
643
+ }
644
+ }
645
+
646
+ return std::make_pair(newline_count, args);
647
+ }
648
+
649
+ // Read a `define preprocessor directive. This is called just after reading the token containing
650
+ // "`define".
651
+ static void
652
+ read_define(const std::string &filename,
653
+ define_map_t &defines_map,
654
+ define_map_t &global_defines_cache)
655
+ {
656
+ std::string name, value;
657
+ arg_map_t args;
658
+
659
+ skip_spaces();
660
+ name = next_token(true);
661
+
662
+ bool here_doc_mode = false;
663
+ int newline_count = 0;
664
+
665
+ // The FSM state starts at 0. If it sees space (or enters here_doc_mode), it assumes this is
666
+ // a macro without formal arguments and jumps to state 1.
667
+ //
668
+ // In state 0, if it sees an opening parenthesis, it assumes this is a macro with formal
669
+ // arguments. It reads the arguments with read_define_args() and then jumps to state 2.
670
+ //
671
+ // In states 1 or 2, the FSM reads tokens to the end of line (or end of here_doc): this is
672
+ // the body of the macro definition.
673
+ int state = 0;
674
+
675
+ if (skip_spaces() != "")
676
+ state = 1;
677
+
678
+ for (;;) {
679
+ std::string tok = next_token();
680
+ if (tok.empty())
681
+ break;
682
+
683
+ // printf("define-tok: >>%s<<\n", tok != "\n" ? tok.c_str() : "NEWLINE");
684
+
685
+ if (tok == "\"\"\"") {
686
+ here_doc_mode = !here_doc_mode;
687
+ continue;
688
+ }
689
+
690
+ if (state == 0 && tok == "(") {
691
+ auto pr = read_define_args();
692
+ newline_count += pr.first;
693
+ args = pr.second;
694
+
695
+ state = 2;
696
+ continue;
697
+ }
698
+
699
+ // This token isn't an opening parenthesis immediately following the macro name, so
700
+ // it's presumably at or after the start of the macro body. If state isn't already 2
701
+ // (which would mean we'd parsed an argument list), set it to 1.
702
+ if (state == 0) {
703
+ state = 1;
704
+ }
705
+
706
+ if (tok == "\n") {
707
+ if (here_doc_mode) {
708
+ value += " ";
709
+ newline_count++;
710
+ } else {
711
+ return_char('\n');
712
+ break;
713
+ }
714
+ continue;
715
+ }
716
+
717
+ if (tok == "\\") {
718
+ char ch = next_char();
719
+ if (ch == '\n') {
720
+ value += " ";
721
+ newline_count++;
722
+ } else {
723
+ value += std::string("\\");
724
+ return_char(ch);
725
+ }
726
+ continue;
727
+ }
728
+
729
+ // Is this token the name of a macro argument? If so, replace it with a magic symbol
730
+ // that we'll replace with the argument value.
731
+ int arg_pos;
732
+ if (args.find(tok, &arg_pos)) {
733
+ value += '`' + args.str_token(name, arg_pos);
734
+ continue;
735
+ }
736
+
737
+ // This token is nothing special. Insert it verbatim into the macro body.
738
+ value += tok;
739
+ }
740
+
741
+ // Append some newlines so that we don't mess up line counts in error messages.
742
+ while (newline_count-- > 0)
743
+ return_char('\n');
744
+
745
+ if (strchr("abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ$0123456789", name[0])) {
746
+ // printf("define: >>%s<< -> >>%s<<\n", name.c_str(), value.c_str());
747
+ defines_map.add(name, value, (state == 2) ? &args : nullptr);
748
+ global_defines_cache.add(name, value, (state == 2) ? &args : nullptr);
749
+ } else {
750
+ log_file_error(LogSourceLocation(filename), "Invalid name for macro definition: >>%s<<.\n", name);
751
+ }
752
+ }
753
+
754
+ std::string
755
+ frontend_verilog_preproc(std::istream &f,
756
+ std::string filename,
757
+ const define_map_t &pre_defines,
758
+ define_map_t &global_defines_cache,
759
+ const std::list<std::string> &include_dirs,
760
+ ParseMode &parse_mode)
761
+ {
762
+ define_map_t defines;
763
+ defines.merge(pre_defines);
764
+ defines.merge(global_defines_cache);
765
+
766
+ macro_arg_stack_t macro_arg_stack;
767
+ std::vector<std::string> filename_stack;
768
+ // We are inside pass_level levels of satisfied ifdefs, and then within
769
+ // fail_level levels of unsatisfied ifdefs. The unsatisfied ones are
770
+ // always within satisfied ones — even if some condition within is true,
771
+ // the parent condition failing renders it moot.
772
+ int ifdef_fail_level = 0;
773
+ int ifdef_pass_level = 0;
774
+ // For the outermost unsatisfied ifdef, true iff that ifdef already
775
+ // had a satisfied branch, and further elsif/else branches should be
776
+ // considered unsatisfied even if the condition is true.
777
+ // Meaningless if ifdef_fail_level == 0.
778
+ bool ifdef_already_satisfied = false;
779
+
780
+ output_code.clear();
781
+ input_buffer.clear();
782
+ input_buffer_charp = 0;
783
+
784
+ input_file(f, filename);
785
+
786
+ while (!input_buffer.empty())
787
+ {
788
+ std::string tok = next_token();
789
+ // printf("token: >>%s<<\n", tok != "\n" ? tok.c_str() : "NEWLINE");
790
+
791
+ if (tok == "`endif") {
792
+ if (ifdef_fail_level > 0)
793
+ ifdef_fail_level--;
794
+ else if (ifdef_pass_level > 0)
795
+ ifdef_pass_level--;
796
+ else
797
+ log_error("Found %s outside of macro conditional branch!\n", tok);
798
+ continue;
799
+ }
800
+
801
+ if (tok == "`else") {
802
+ if (ifdef_fail_level == 0) {
803
+ if (ifdef_pass_level == 0)
804
+ log_error("Found %s outside of macro conditional branch!\n", tok);
805
+ ifdef_pass_level--;
806
+ ifdef_fail_level = 1;
807
+ ifdef_already_satisfied = true;
808
+ } else if (ifdef_fail_level == 1 && !ifdef_already_satisfied) {
809
+ ifdef_fail_level = 0;
810
+ ifdef_pass_level++;
811
+ ifdef_already_satisfied = true;
812
+ }
813
+ continue;
814
+ }
815
+
816
+ if (tok == "`elsif") {
817
+ skip_spaces();
818
+ std::string name = next_token(true);
819
+ if (ifdef_fail_level == 0) {
820
+ if (ifdef_pass_level == 0)
821
+ log_error("Found %s outside of macro conditional branch!\n", tok);
822
+ ifdef_pass_level--;
823
+ ifdef_fail_level = 1;
824
+ ifdef_already_satisfied = true;
825
+ } else if (ifdef_fail_level == 1 && !ifdef_already_satisfied && defines.find(name)) {
826
+ ifdef_fail_level = 0;
827
+ ifdef_pass_level++;
828
+ ifdef_already_satisfied = true;
829
+ }
830
+ continue;
831
+ }
832
+
833
+ if (tok == "`ifdef") {
834
+ skip_spaces();
835
+ std::string name = next_token(true);
836
+ if (ifdef_fail_level > 0 || !defines.find(name)) {
837
+ ifdef_fail_level++;
838
+ } else {
839
+ ifdef_pass_level++;
840
+ ifdef_already_satisfied = true;
841
+ }
842
+ if (ifdef_fail_level == 1)
843
+ ifdef_already_satisfied = false;
844
+ continue;
845
+ }
846
+
847
+ if (tok == "`ifndef") {
848
+ skip_spaces();
849
+ std::string name = next_token(true);
850
+ if (ifdef_fail_level > 0 || defines.find(name)) {
851
+ ifdef_fail_level++;
852
+ } else {
853
+ ifdef_pass_level++;
854
+ ifdef_already_satisfied = true;
855
+ }
856
+ if (ifdef_fail_level == 1)
857
+ ifdef_already_satisfied = false;
858
+ continue;
859
+ }
860
+
861
+ if (ifdef_fail_level > 0) {
862
+ if (tok == "\n")
863
+ output_code.push_back(tok);
864
+ continue;
865
+ }
866
+
867
+ if (tok == "`include") {
868
+ skip_spaces();
869
+ std::string fn = next_token(true);
870
+ while (try_expand_macro(defines, macro_arg_stack, fn)) {
871
+ fn = next_token();
872
+ }
873
+ while (1) {
874
+ size_t pos = fn.find('"');
875
+ if (pos == std::string::npos)
876
+ break;
877
+ if (pos == 0)
878
+ fn = fn.substr(1);
879
+ else
880
+ fn = fn.substr(0, pos) + fn.substr(pos+1);
881
+ }
882
+ std::ifstream ff;
883
+ ff.clear();
884
+ std::string fixed_fn = fn;
885
+ ff.open(fixed_fn.c_str());
886
+
887
+ bool filename_path_sep_found;
888
+ bool fn_relative;
889
+ #ifdef _WIN32
890
+ // Both forward and backslash are acceptable separators on Windows.
891
+ filename_path_sep_found = (filename.find_first_of("/\\") != std::string::npos);
892
+ // Easier just to invert the check for an absolute path (e.g. C:\ or C:/)
893
+ fn_relative = !(fn[1] == ':' && (fn[2] == '/' || fn[2] == '\\'));
894
+ #else
895
+ filename_path_sep_found = (filename.find('/') != std::string::npos);
896
+ fn_relative = (fn[0] != '/');
897
+ #endif
898
+
899
+ if (ff.fail() && fn.size() > 0 && fn_relative && filename_path_sep_found) {
900
+ // if the include file was not found, it is not given with an absolute path, and the
901
+ // currently read file is given with a path, then try again relative to its directory
902
+ ff.clear();
903
+ fixed_fn = parent_from_file_path(filename) + fn;
904
+ ff.open(fixed_fn);
905
+ }
906
+ if (ff.fail() && fn.size() > 0 && fn_relative) {
907
+ // if the include file was not found and it is not given with an absolute path, then
908
+ // search it in the include path
909
+ for (auto incdir : include_dirs) {
910
+ ff.clear();
911
+ fixed_fn = incdir + '/' + fn;
912
+ ff.open(fixed_fn);
913
+ if (!ff.fail()) break;
914
+ }
915
+ }
916
+ if (ff.fail()) {
917
+ output_code.push_back("`file_notfound " + fn);
918
+ } else {
919
+ input_file(ff, fixed_fn);
920
+ yosys_input_files.insert(fixed_fn);
921
+ }
922
+ continue;
923
+ }
924
+
925
+ if (tok == "`file_push") {
926
+ skip_spaces();
927
+ std::string fn = next_token(true);
928
+ if (!fn.empty() && fn.front() == '"' && fn.back() == '"')
929
+ fn = fn.substr(1, fn.size()-2);
930
+ output_code.push_back(tok + " \"" + fn + "\"");
931
+ filename_stack.push_back(filename);
932
+ filename = fn;
933
+ continue;
934
+ }
935
+
936
+ if (tok == "`file_pop") {
937
+ output_code.push_back(tok);
938
+ filename = filename_stack.back();
939
+ filename_stack.pop_back();
940
+ continue;
941
+ }
942
+
943
+ if (tok == "`define") {
944
+ read_define(filename, defines, global_defines_cache);
945
+ continue;
946
+ }
947
+
948
+ if (tok == "`undef") {
949
+ std::string name;
950
+ skip_spaces();
951
+ name = next_token(true);
952
+ // printf("undef: >>%s<<\n", name.c_str());
953
+ defines.erase(name);
954
+ global_defines_cache.erase(name);
955
+ continue;
956
+ }
957
+
958
+ if (tok == "`timescale") {
959
+ skip_spaces();
960
+ while (!tok.empty() && tok != "\n")
961
+ tok = next_token(true);
962
+ if (tok == "\n")
963
+ return_char('\n');
964
+ continue;
965
+ }
966
+
967
+ if (tok == "`resetall") {
968
+ // `resetall is consumed here and never reaches the lexer, which owns
969
+ // `default_nettype during parsing.
970
+ output_code.push_back("\n`default_nettype wire\n");
971
+ continue;
972
+ }
973
+
974
+ if (tok == "`undefineall" && parse_mode.sv) {
975
+ defines.clear();
976
+ global_defines_cache.clear();
977
+ continue;
978
+ }
979
+
980
+ if (tok == "`__restore_macro_arg") {
981
+ restore_macro_arg(defines, macro_arg_stack);
982
+ continue;
983
+ }
984
+
985
+ if (try_expand_macro(defines, macro_arg_stack, tok))
986
+ continue;
987
+
988
+ output_code.push_back(tok);
989
+ }
990
+
991
+ if (ifdef_fail_level > 0 || ifdef_pass_level > 0) {
992
+ log_error("Unterminated preprocessor conditional!\n");
993
+ }
994
+
995
+ std::string output;
996
+ for (auto &str : output_code)
997
+ output += str;
998
+
999
+ output_code.clear();
1000
+ input_buffer.clear();
1001
+ input_buffer_charp = 0;
1002
+
1003
+ return output;
1004
+ }
1005
+
1006
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verilog/preproc.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * The Verilog preprocessor.
21
+ *
22
+ */
23
+ #ifndef VERILOG_PREPROC_H
24
+ #define VERILOG_PREPROC_H
25
+
26
+ #include "kernel/yosys.h"
27
+
28
+ #include <iosfwd>
29
+ #include <list>
30
+ #include <memory>
31
+ #include <string>
32
+
33
+ YOSYS_NAMESPACE_BEGIN
34
+
35
+ struct define_body_t;
36
+ struct arg_map_t;
37
+
38
+ namespace VERILOG_FRONTEND {
39
+ struct ParseState;
40
+ struct ParseMode;
41
+ };
42
+
43
+ struct define_map_t
44
+ {
45
+ define_map_t();
46
+ ~ define_map_t();
47
+
48
+ // Add a definition, overwriting any existing definition for name.
49
+ void add(const std::string &name, const std::string &txt, const arg_map_t *args = nullptr);
50
+ void add(const std::string &name, const define_body_t &body);
51
+
52
+ // Merge in another map of definitions (which take precedence
53
+ // over anything currently defined).
54
+ void merge(const define_map_t &map);
55
+
56
+ // Find a definition by name. If no match, returns null.
57
+ const define_body_t *find(const std::string &name) const;
58
+
59
+ // Erase a definition by name (no effect if not defined).
60
+ void erase(const std::string &name);
61
+
62
+ // Clear any existing definitions
63
+ void clear();
64
+
65
+ // Print a list of definitions, using the log function
66
+ void log() const;
67
+
68
+ std::map<std::string, std::unique_ptr<define_body_t>> defines;
69
+ };
70
+
71
+
72
+ struct define_map_t;
73
+
74
+ std::string
75
+ frontend_verilog_preproc(std::istream &f,
76
+ std::string filename,
77
+ const define_map_t &pre_defines,
78
+ define_map_t &global_defines_cache,
79
+ const std::list<std::string> &include_dirs,
80
+ VERILOG_FRONTEND::ParseMode &parse_mode);
81
+
82
+ YOSYS_NAMESPACE_END
83
+
84
+ #endif
chips/yosys/frontends/verilog/verilog_error.cc ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ */
21
+
22
+ #include "kernel/yosys_common.h"
23
+ #include "frontends/verilog/verilog_error.h"
24
+ #include "frontends/verilog/verilog_location.h"
25
+
26
+ USING_YOSYS_NAMESPACE
27
+
28
+ /**
29
+ * Legacy behavior is to only track lines. Now we have columns too, but we don't
30
+ * report them in errors.
31
+ * TODO: report columns, too
32
+ */
33
+
34
+ [[noreturn]]
35
+ void VERILOG_FRONTEND::formatted_err_at_loc(Location loc, std::string str)
36
+ {
37
+ YOSYS_NAMESPACE_PREFIX log_file_error(loc.to_loc(), "%s\n", std::move(str));
38
+ }
39
+
40
+ void VERILOG_FRONTEND::formatted_warn_at_loc(Location loc, std::string str)
41
+ {
42
+ YOSYS_NAMESPACE_PREFIX log_file_warning(loc.to_loc(), "%s\n", std::move(str));
43
+ }
chips/yosys/frontends/verilog/verilog_error.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef VERILOG_ERROR_H
2
+ #define VERILOG_ERROR_H
3
+
4
+ #include "kernel/yosys_common.h"
5
+ #include "frontends/ast/ast.h"
6
+ #include "frontends/verilog/verilog_location.h"
7
+
8
+ YOSYS_NAMESPACE_BEGIN
9
+
10
+ namespace VERILOG_FRONTEND
11
+ {
12
+ [[noreturn]]
13
+ void formatted_err_at_loc(Location loc, std::string str);
14
+ template <typename... Args>
15
+ [[noreturn]]
16
+ void err_at_loc(Location loc, FmtString<TypeIdentity<Args>...> fmt, const Args &... args)
17
+ {
18
+ formatted_err_at_loc(std::move(loc), fmt.format(args...));
19
+ }
20
+
21
+ void formatted_warn_at_loc(Location loc, std::string str);
22
+ template <typename... Args>
23
+ void warn_at_loc(Location loc, FmtString<TypeIdentity<Args>...> fmt, const Args &... args)
24
+ {
25
+ formatted_warn_at_loc(std::move(loc), fmt.format(args...));
26
+ }
27
+ };
28
+
29
+ YOSYS_NAMESPACE_END
30
+
31
+ #endif
chips/yosys/frontends/verilog/verilog_frontend.cc ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * The Verilog frontend.
21
+ *
22
+ * This frontend is using the AST frontend library (see frontends/ast/).
23
+ * Thus this frontend does not generate RTLIL code directly but creates an
24
+ * AST directly from the Verilog parse tree and then passes this AST to
25
+ * the AST frontend library.
26
+ *
27
+ */
28
+
29
+ #include <filesystem>
30
+
31
+ #include "verilog_frontend.h"
32
+ #include "verilog_lexer.h"
33
+ #include "verilog_error.h"
34
+ #include "verilog_location.h"
35
+ #include "preproc.h"
36
+ #include "kernel/yosys.h"
37
+ #include "libs/sha1/sha1.h"
38
+ #include <stdarg.h>
39
+ #include <list>
40
+
41
+ YOSYS_NAMESPACE_BEGIN
42
+ using namespace VERILOG_FRONTEND;
43
+
44
+ // use the Verilog bison/flex parser to generate an AST and use AST::process() to convert it to RTLIL
45
+
46
+ static std::vector<std::string> verilog_defaults;
47
+ static std::list<std::vector<std::string>> verilog_defaults_stack;
48
+
49
+ static void error_on_dpi_function(AST::AstNode *node)
50
+ {
51
+ if (node->type == AST::AST_DPI_FUNCTION)
52
+ err_at_loc(node->location, "Found DPI function %s.\n", node->str);
53
+ for (auto& child : node->children)
54
+ error_on_dpi_function(child.get());
55
+ }
56
+
57
+ static void add_package_types(dict<std::string, AST::AstNode *> &user_types, std::vector<std::unique_ptr<AST::AstNode>> &package_list)
58
+ {
59
+ // prime the parser's user type lookup table with the package qualified names
60
+ // of typedefed names in the packages seen so far.
61
+ for (const auto &pkg : package_list) {
62
+ log_assert(pkg->type==AST::AST_PACKAGE);
63
+ for (const auto &node: pkg->children) {
64
+ if (node->type == AST::AST_TYPEDEF) {
65
+ std::string s = pkg->str + "::" + node->str.substr(1);
66
+ user_types[s] = node.get();
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ struct VerilogFrontend : public Frontend {
73
+ VerilogFrontend() : Frontend("verilog", "read modules from Verilog file") { }
74
+ void help() override
75
+ {
76
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
77
+ log("\n");
78
+ log(" read_verilog [options] [filename]\n");
79
+ log("\n");
80
+ log("Load modules from a Verilog file to the current design. A large subset of\n");
81
+ log("Verilog-2005 is supported.\n");
82
+ log("\n");
83
+ log(" -sv\n");
84
+ log(" enable support for SystemVerilog features. (only a small subset\n");
85
+ log(" of SystemVerilog is supported)\n");
86
+ log("\n");
87
+ log(" -formal\n");
88
+ log(" enable support for SystemVerilog assertions and some Yosys extensions\n");
89
+ log(" replace the implicit -D SYNTHESIS with -D FORMAL\n");
90
+ log("\n");
91
+ log(" -nosynthesis\n");
92
+ log(" don't add implicit -D SYNTHESIS\n");
93
+ log("\n");
94
+ log(" -noassert\n");
95
+ log(" ignore assert() statements\n");
96
+ log("\n");
97
+ log(" -noassume\n");
98
+ log(" ignore assume() statements\n");
99
+ log("\n");
100
+ log(" -norestrict\n");
101
+ log(" ignore restrict() statements\n");
102
+ log("\n");
103
+ log(" -assume-asserts\n");
104
+ log(" treat all assert() statements like assume() statements\n");
105
+ log("\n");
106
+ log(" -assert-assumes\n");
107
+ log(" treat all assume() statements like assert() statements\n");
108
+ log("\n");
109
+ log(" -nodisplay\n");
110
+ log(" suppress output from display system tasks ($display et. al).\n");
111
+ log(" This does not affect the output from a later 'sim' command.\n");
112
+ log("\n");
113
+ log(" -debug\n");
114
+ log(" alias for -dump_ast1 -dump_ast2 -dump_vlog1 -dump_vlog2 -yydebug\n");
115
+ log("\n");
116
+ log(" -dump_ast1\n");
117
+ log(" dump abstract syntax tree (before simplification)\n");
118
+ log("\n");
119
+ log(" -dump_ast2\n");
120
+ log(" dump abstract syntax tree (after simplification)\n");
121
+ log("\n");
122
+ log(" -no_dump_ptr\n");
123
+ log(" do not include hex memory addresses in dump (easier to diff dumps)\n");
124
+ log("\n");
125
+ log(" -dump_vlog1\n");
126
+ log(" dump ast as Verilog code (before simplification)\n");
127
+ log("\n");
128
+ log(" -dump_vlog2\n");
129
+ log(" dump ast as Verilog code (after simplification)\n");
130
+ log("\n");
131
+ log(" -dump_rtlil\n");
132
+ log(" dump generated RTLIL netlist\n");
133
+ log("\n");
134
+ log(" -yydebug\n");
135
+ log(" enable parser debug output\n");
136
+ log("\n");
137
+ log(" -nolatches\n");
138
+ log(" usually latches are synthesized into logic loops\n");
139
+ log(" this option prohibits this and sets the output to 'x'\n");
140
+ log(" in what would be the latches hold condition\n");
141
+ log("\n");
142
+ log(" this behavior can also be achieved by setting the\n");
143
+ log(" 'nolatches' attribute on the respective module or\n");
144
+ log(" always block.\n");
145
+ log("\n");
146
+ log(" -nomem2reg\n");
147
+ log(" under certain conditions memories are converted to registers\n");
148
+ log(" early during simplification to ensure correct handling of\n");
149
+ log(" complex corner cases. this option disables this behavior.\n");
150
+ log("\n");
151
+ log(" this can also be achieved by setting the 'nomem2reg'\n");
152
+ log(" attribute on the respective module or register.\n");
153
+ log("\n");
154
+ log(" This is potentially dangerous. Usually the front-end has good\n");
155
+ log(" reasons for converting an array to a list of registers.\n");
156
+ log(" Prohibiting this step will likely result in incorrect synthesis\n");
157
+ log(" results.\n");
158
+ log("\n");
159
+ log(" -mem2reg\n");
160
+ log(" always convert memories to registers. this can also be\n");
161
+ log(" achieved by setting the 'mem2reg' attribute on the respective\n");
162
+ log(" module or register.\n");
163
+ log("\n");
164
+ log(" -nomeminit\n");
165
+ log(" do not infer $meminit cells and instead convert initialized\n");
166
+ log(" memories to registers directly in the front-end.\n");
167
+ log("\n");
168
+ log(" -ppdump\n");
169
+ log(" dump Verilog code after pre-processor\n");
170
+ log("\n");
171
+ log(" -nopp\n");
172
+ log(" do not run the pre-processor\n");
173
+ log("\n");
174
+ log(" -nodpi\n");
175
+ log(" disable DPI-C support\n");
176
+ log("\n");
177
+ log(" -noblackbox\n");
178
+ log(" do not automatically add a (* blackbox *) attribute to an\n");
179
+ log(" empty module.\n");
180
+ log("\n");
181
+ log(" -lib\n");
182
+ log(" only create empty blackbox modules. This implies -DBLACKBOX.\n");
183
+ log(" modules with the (* whitebox *) attribute will be preserved.\n");
184
+ log(" (* lib_whitebox *) will be treated like (* whitebox *).\n");
185
+ log("\n");
186
+ log(" -nowb\n");
187
+ log(" delete (* whitebox *) and (* lib_whitebox *) attributes from\n");
188
+ log(" all modules.\n");
189
+ log("\n");
190
+ log(" -specify\n");
191
+ log(" parse and import specify blocks\n");
192
+ log("\n");
193
+ log(" -noopt\n");
194
+ log(" don't perform basic optimizations (such as const folding) in the\n");
195
+ log(" high-level front-end.\n");
196
+ log("\n");
197
+ log(" -icells\n");
198
+ log(" interpret cell types starting with '$' as internal cell types\n");
199
+ log("\n");
200
+ log(" -pwires\n");
201
+ log(" add a wire for each module parameter\n");
202
+ log("\n");
203
+ log(" -nooverwrite\n");
204
+ log(" ignore re-definitions of modules. (the default behavior is to\n");
205
+ log(" create an error message if the existing module is not a black box\n");
206
+ log(" module, and overwrite the existing module otherwise.)\n");
207
+ log("\n");
208
+ log(" -overwrite\n");
209
+ log(" overwrite existing modules with the same name\n");
210
+ log("\n");
211
+ log(" -defer\n");
212
+ log(" only read the abstract syntax tree and defer actual compilation\n");
213
+ log(" to a later 'hierarchy' command. Useful in cases where the default\n");
214
+ log(" parameters of modules yield invalid or not synthesizable code.\n");
215
+ log("\n");
216
+ log(" -noautowire\n");
217
+ log(" make the default of `default_nettype be \"none\" instead of \"wire\".\n");
218
+ log("\n");
219
+ log(" -unroll-limit <limit (default=4000)>\n");
220
+ log(" set the limit for how many loop unrolls occur by default\n");
221
+ log("\n");
222
+ log(" -setattr <attribute_name>\n");
223
+ log(" set the specified attribute (to the value 1) on all loaded modules\n");
224
+ log("\n");
225
+ log(" -Dname[=definition]\n");
226
+ log(" define the preprocessor symbol 'name' and set its optional value\n");
227
+ log(" 'definition'\n");
228
+ log("\n");
229
+ log(" -Idir\n");
230
+ log(" add 'dir' to the directories which are used when searching include\n");
231
+ log(" files\n");
232
+ log("\n");
233
+ log(" -relativeshare\n");
234
+ log(" use paths relative to share directory for source locations\n");
235
+ log(" where possible (experimental).\n");
236
+ log("\n");
237
+ log("The command 'verilog_defaults' can be used to register default options for\n");
238
+ log("subsequent calls to 'read_verilog'.\n");
239
+ log("\n");
240
+ log("Note that the Verilog frontend does a pretty good job of processing valid\n");
241
+ log("verilog input, but has not very good error reporting. It generally is\n");
242
+ log("recommended to use a simulator (for example Icarus Verilog) for checking\n");
243
+ log("the syntax of the code, rather than to rely on read_verilog for that.\n");
244
+ log("\n");
245
+ log("Depending on if read_verilog is run in -formal mode, either the macro\n");
246
+ log("SYNTHESIS or FORMAL is defined automatically, unless -nosynthesis is used.\n");
247
+ log("In addition, read_verilog always defines the macro YOSYS.\n");
248
+ log("\n");
249
+ log("See the Yosys README file for a list of non-standard Verilog features\n");
250
+ log("supported by the Yosys Verilog front-end.\n");
251
+ log("\n");
252
+ }
253
+ void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
254
+ {
255
+ bool flag_nodisplay = false;
256
+ bool flag_dump_ast1 = false;
257
+ bool flag_dump_ast2 = false;
258
+ bool flag_no_dump_ptr = false;
259
+ bool flag_dump_vlog1 = false;
260
+ bool flag_dump_vlog2 = false;
261
+ bool flag_dump_rtlil = false;
262
+ bool flag_debug_lexer = false;
263
+ bool flag_debug_parser = false;
264
+ bool flag_nolatches = false;
265
+ bool flag_nomeminit = false;
266
+ bool flag_nomem2reg = false;
267
+ bool flag_mem2reg = false;
268
+ bool flag_ppdump = false;
269
+ bool flag_nopp = false;
270
+ bool flag_nodpi = false;
271
+ bool flag_noopt = false;
272
+ bool flag_icells = false;
273
+ bool flag_pwires = false;
274
+ bool flag_nooverwrite = false;
275
+ bool flag_overwrite = false;
276
+ bool flag_defer = false;
277
+ bool flag_noblackbox = false;
278
+ bool flag_nowb = false;
279
+ bool flag_nosynthesis = false;
280
+ bool flag_yydebug = false;
281
+ bool flag_relative_share = false;
282
+ int flag_unroll_limit = 4000;
283
+ define_map_t defines_map;
284
+
285
+ std::list<std::string> include_dirs;
286
+ std::list<std::string> attributes;
287
+
288
+ ParseMode parse_mode = {};
289
+ ParseState parse_state = {};
290
+ parse_mode.sv = false;
291
+ parse_mode.formal = false;
292
+ parse_mode.noassert = false;
293
+ parse_mode.noassume = false;
294
+ parse_mode.norestrict = false;
295
+ parse_mode.assume_asserts = false;
296
+ parse_mode.assert_assumes = false;
297
+ parse_mode.lib = false;
298
+ parse_mode.specify = false;
299
+ parse_state.default_nettype_wire = true;
300
+
301
+ args.insert(args.begin()+1, verilog_defaults.begin(), verilog_defaults.end());
302
+
303
+ size_t argidx;
304
+ for (argidx = 1; argidx < args.size(); argidx++) {
305
+ std::string arg = args[argidx];
306
+ if (arg == "-sv") {
307
+ parse_mode.sv = true;
308
+ continue;
309
+ }
310
+ if (arg == "-formal") {
311
+ parse_mode.formal = true;
312
+ continue;
313
+ }
314
+ if (arg == "-nosynthesis") {
315
+ flag_nosynthesis = true;
316
+ continue;
317
+ }
318
+ if (arg == "-noassert") {
319
+ parse_mode.noassert = true;
320
+ continue;
321
+ }
322
+ if (arg == "-noassume") {
323
+ parse_mode.noassume = true;
324
+ continue;
325
+ }
326
+ if (arg == "-norestrict") {
327
+ parse_mode.norestrict = true;
328
+ continue;
329
+ }
330
+ if (arg == "-assume-asserts") {
331
+ parse_mode.assume_asserts = true;
332
+ continue;
333
+ }
334
+ if (arg == "-assert-assumes") {
335
+ parse_mode.assert_assumes = true;
336
+ continue;
337
+ }
338
+ if (arg == "-nodisplay") {
339
+ flag_nodisplay = true;
340
+ continue;
341
+ }
342
+ if (arg == "-debug") {
343
+ flag_dump_ast1 = true;
344
+ flag_dump_ast2 = true;
345
+ flag_dump_vlog1 = true;
346
+ flag_dump_vlog2 = true;
347
+ flag_debug_lexer = true;
348
+ flag_debug_parser = true;
349
+ continue;
350
+ }
351
+ if (arg == "-dump_ast1") {
352
+ flag_dump_ast1 = true;
353
+ continue;
354
+ }
355
+ if (arg == "-dump_ast2") {
356
+ flag_dump_ast2 = true;
357
+ continue;
358
+ }
359
+ if (arg == "-no_dump_ptr") {
360
+ flag_no_dump_ptr = true;
361
+ continue;
362
+ }
363
+ if (arg == "-dump_vlog1") {
364
+ flag_dump_vlog1 = true;
365
+ continue;
366
+ }
367
+ if (arg == "-dump_vlog2") {
368
+ flag_dump_vlog2 = true;
369
+ continue;
370
+ }
371
+ if (arg == "-dump_rtlil") {
372
+ flag_dump_rtlil = true;
373
+ continue;
374
+ }
375
+ if (arg == "-yydebug") {
376
+ flag_yydebug = true;
377
+ flag_debug_lexer = true;
378
+ flag_debug_parser = true;
379
+ continue;
380
+ }
381
+ if (arg == "-nolatches") {
382
+ flag_nolatches = true;
383
+ continue;
384
+ }
385
+ if (arg == "-nomeminit") {
386
+ flag_nomeminit = true;
387
+ continue;
388
+ }
389
+ if (arg == "-nomem2reg") {
390
+ flag_nomem2reg = true;
391
+ continue;
392
+ }
393
+ if (arg == "-mem2reg") {
394
+ flag_mem2reg = true;
395
+ continue;
396
+ }
397
+ if (arg == "-ppdump") {
398
+ flag_ppdump = true;
399
+ continue;
400
+ }
401
+ if (arg == "-nopp") {
402
+ flag_nopp = true;
403
+ continue;
404
+ }
405
+ if (arg == "-nodpi") {
406
+ flag_nodpi = true;
407
+ continue;
408
+ }
409
+ if (arg == "-noblackbox") {
410
+ flag_noblackbox = true;
411
+ continue;
412
+ }
413
+ if (arg == "-lib") {
414
+ parse_mode.lib = true;
415
+ defines_map.add("BLACKBOX", "");
416
+ continue;
417
+ }
418
+ if (arg == "-nowb") {
419
+ flag_nowb = true;
420
+ continue;
421
+ }
422
+ if (arg == "-specify") {
423
+ parse_mode.specify = true;
424
+ continue;
425
+ }
426
+ if (arg == "-noopt") {
427
+ flag_noopt = true;
428
+ continue;
429
+ }
430
+ if (arg == "-icells") {
431
+ flag_icells = true;
432
+ continue;
433
+ }
434
+ if (arg == "-pwires") {
435
+ flag_pwires = true;
436
+ continue;
437
+ }
438
+ if (arg == "-ignore_redef" || arg == "-nooverwrite") {
439
+ flag_nooverwrite = true;
440
+ flag_overwrite = false;
441
+ continue;
442
+ }
443
+ if (arg == "-overwrite") {
444
+ flag_nooverwrite = false;
445
+ flag_overwrite = true;
446
+ continue;
447
+ }
448
+ if (arg == "-defer") {
449
+ flag_defer = true;
450
+ continue;
451
+ }
452
+ if (arg == "-noautowire") {
453
+ parse_state.default_nettype_wire = false;
454
+ continue;
455
+ }
456
+ if (arg == "-unroll-limit" && argidx+1 < args.size()) {
457
+ flag_unroll_limit = stoi(args[++argidx]);
458
+ if (flag_unroll_limit < 0) log_error("Cannot choose negative value for -unroll-limit");
459
+ continue;
460
+ }
461
+ if (arg == "-setattr" && argidx+1 < args.size()) {
462
+ attributes.push_back(RTLIL::escape_id(args[++argidx]));
463
+ continue;
464
+ }
465
+ if (arg == "-relativeshare") {
466
+ flag_relative_share = true;
467
+ log_experimental("read_verilog -relativeshare");
468
+ continue;
469
+ }
470
+ if (arg == "-D" && argidx+1 < args.size()) {
471
+ std::string name = args[++argidx], value;
472
+ size_t equal = name.find('=');
473
+ if (equal != std::string::npos) {
474
+ value = name.substr(equal+1);
475
+ name = name.substr(0, equal);
476
+ }
477
+ defines_map.add(name, value);
478
+ continue;
479
+ }
480
+ if (arg.compare(0, 2, "-D") == 0) {
481
+ size_t equal = arg.find('=', 2);
482
+ std::string name = arg.substr(2, equal-2);
483
+ std::string value;
484
+ if (equal != std::string::npos)
485
+ value = arg.substr(equal+1);
486
+ defines_map.add(name, value);
487
+ continue;
488
+ }
489
+ if (arg == "-I" && argidx+1 < args.size()) {
490
+ include_dirs.push_back(args[++argidx]);
491
+ continue;
492
+ }
493
+ if (arg.compare(0, 2, "-I") == 0) {
494
+ include_dirs.push_back(arg.substr(2));
495
+ continue;
496
+ }
497
+ break;
498
+ }
499
+
500
+ if (parse_mode.formal || !flag_nosynthesis)
501
+ defines_map.add(parse_mode.formal ? "FORMAL" : "SYNTHESIS", "1");
502
+
503
+ extra_args(f, filename, args, argidx);
504
+
505
+ log_header(design, "Executing Verilog-2005 frontend: %s\n", filename);
506
+
507
+ AST::DesignScope design_scope(design);
508
+
509
+ log("Parsing %s%s input from `%s' to AST representation.\n",
510
+ parse_mode.formal ? "formal " : "", parse_mode.sv ? "SystemVerilog" : "Verilog", filename);
511
+
512
+ if (flag_relative_share) {
513
+ auto share_path = proc_share_dirname();
514
+ if (filename.substr(0, share_path.length()) == share_path)
515
+ filename = std::string("+/") + filename.substr(share_path.length());
516
+ log("new filename %s\n", filename);
517
+ }
518
+ AST::sv_mode_but_global_and_used_for_literally_one_condition = parse_mode.sv;
519
+ std::string code_after_preproc;
520
+
521
+ parse_state.lexin = f;
522
+ if (!flag_nopp) {
523
+ code_after_preproc = frontend_verilog_preproc(*f, filename, defines_map, *design->verilog_defines, include_dirs, parse_mode);
524
+ if (flag_ppdump) {
525
+ log("-- Verilog code after preprocessor --\n");
526
+ log_lines(code_after_preproc);
527
+ log("-- END OF DUMP --\n");
528
+ }
529
+ parse_state.lexin = new std::istringstream(code_after_preproc);
530
+ }
531
+
532
+ auto filename_shared = std::make_shared<std::string>(filename);
533
+ auto top_loc = Location();
534
+ top_loc.begin.filename = filename_shared;
535
+ parse_state.current_ast = new AST::AstNode(top_loc, AST::AST_DESIGN);
536
+ VerilogLexer lexer(&parse_state, &parse_mode, filename_shared);
537
+ frontend_verilog_yy::parser parser(&lexer, &parse_state, &parse_mode);
538
+ lexer.set_debug(flag_debug_lexer);
539
+ parser.set_debug_level(flag_debug_parser ? 1 : 0);
540
+
541
+ // make package typedefs available to parser
542
+ add_package_types(parse_state.pkg_user_types, design->verilog_packages);
543
+
544
+ UserTypeMap global_types_map;
545
+ for (auto& def : design->verilog_globals) {
546
+ if (def->type == AST::AST_TYPEDEF) {
547
+ global_types_map[def->str] = def.get();
548
+ }
549
+ }
550
+
551
+ log_assert(parse_state.user_type_stack.empty());
552
+ // use previous global typedefs as bottom level of user type stack
553
+ parse_state.user_type_stack.push_back(std::move(global_types_map));
554
+ // add a new empty type map to allow overriding existing global definitions
555
+ parse_state.user_type_stack.push_back(UserTypeMap());
556
+
557
+ if (flag_yydebug) {
558
+ lexer.set_debug(true);
559
+ parser.set_debug_level(1);
560
+ }
561
+ parser.parse();
562
+ // frontend_verilog_yyset_lineno(1);
563
+
564
+ for (auto &child : parse_state.current_ast->children) {
565
+ if (child->type == AST::AST_MODULE)
566
+ for (auto &attr : attributes) {
567
+ IdString attr_id = AST::intern_attr_name(attr);
568
+ if (child->attributes.count(attr_id) == 0)
569
+ child->attributes[attr_id] = AST::AstNode::mkconst_int(top_loc, 1, false);
570
+ }
571
+ }
572
+
573
+ if (flag_nodpi)
574
+ error_on_dpi_function(parse_state.current_ast);
575
+
576
+ AST::process(design, parse_state.current_ast, flag_nodisplay, flag_dump_ast1, flag_dump_ast2, flag_no_dump_ptr, flag_dump_vlog1, flag_dump_vlog2, flag_dump_rtlil, flag_nolatches,
577
+ flag_nomeminit, flag_nomem2reg, flag_mem2reg, flag_noblackbox, parse_mode.lib, flag_nowb, flag_noopt, flag_icells, flag_pwires, flag_nooverwrite, flag_overwrite, flag_defer, parse_state.default_nettype_wire, flag_unroll_limit);
578
+
579
+
580
+ if (!flag_nopp)
581
+ delete parse_state.lexin;
582
+
583
+ // only the previous and new global type maps remain
584
+ log_assert(parse_state.user_type_stack.size() == 2);
585
+ parse_state.user_type_stack.clear();
586
+
587
+ delete parse_state.current_ast;
588
+ parse_state.current_ast = NULL;
589
+
590
+ log("Successfully finished Verilog frontend.\n");
591
+ }
592
+ } VerilogFrontend;
593
+
594
+ struct VerilogDefaults : public Pass {
595
+ VerilogDefaults() : Pass("verilog_defaults", "set default options for read_verilog") { }
596
+ void help() override
597
+ {
598
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
599
+ log("\n");
600
+ log(" verilog_defaults -add [options]\n");
601
+ log("\n");
602
+ log("Add the specified options to the list of default options to read_verilog.\n");
603
+ log("\n");
604
+ log("\n");
605
+ log(" verilog_defaults -clear\n");
606
+ log("\n");
607
+ log("Clear the list of Verilog default options.\n");
608
+ log("\n");
609
+ log("\n");
610
+ log(" verilog_defaults -push\n");
611
+ log(" verilog_defaults -pop\n");
612
+ log("\n");
613
+ log("Push or pop the list of default options to a stack. Note that -push does\n");
614
+ log("not imply -clear.\n");
615
+ log("\n");
616
+ }
617
+ void execute(std::vector<std::string> args, RTLIL::Design*) override
618
+ {
619
+ if (args.size() < 2)
620
+ cmd_error(args, 1, "Missing argument.");
621
+
622
+ if (args[1] == "-add") {
623
+ verilog_defaults.insert(verilog_defaults.end(), args.begin()+2, args.end());
624
+ return;
625
+ }
626
+
627
+ if (args.size() != 2)
628
+ cmd_error(args, 2, "Extra argument.");
629
+
630
+ if (args[1] == "-clear") {
631
+ verilog_defaults.clear();
632
+ return;
633
+ }
634
+
635
+ if (args[1] == "-push") {
636
+ verilog_defaults_stack.push_back(verilog_defaults);
637
+ return;
638
+ }
639
+
640
+ if (args[1] == "-pop") {
641
+ if (verilog_defaults_stack.empty()) {
642
+ verilog_defaults.clear();
643
+ } else {
644
+ verilog_defaults.swap(verilog_defaults_stack.back());
645
+ verilog_defaults_stack.pop_back();
646
+ }
647
+ return;
648
+ }
649
+ }
650
+ } VerilogDefaults;
651
+
652
+ struct VerilogDefines : public Pass {
653
+ VerilogDefines() : Pass("verilog_defines", "define and undefine verilog defines") { }
654
+ void help() override
655
+ {
656
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
657
+ log("\n");
658
+ log(" verilog_defines [options]\n");
659
+ log("\n");
660
+ log("Define and undefine verilog preprocessor macros.\n");
661
+ log("\n");
662
+ log(" -Dname[=definition]\n");
663
+ log(" define the preprocessor symbol 'name' and set its optional value\n");
664
+ log(" 'definition'\n");
665
+ log("\n");
666
+ log(" -Uname[=definition]\n");
667
+ log(" undefine the preprocessor symbol 'name'\n");
668
+ log("\n");
669
+ log(" -reset\n");
670
+ log(" clear list of defined preprocessor symbols\n");
671
+ log("\n");
672
+ log(" -list\n");
673
+ log(" list currently defined preprocessor symbols\n");
674
+ log("\n");
675
+ }
676
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
677
+ {
678
+ size_t argidx;
679
+ for (argidx = 1; argidx < args.size(); argidx++) {
680
+ std::string arg = args[argidx];
681
+ if (arg == "-D" && argidx+1 < args.size()) {
682
+ std::string name = args[++argidx], value;
683
+ size_t equal = name.find('=');
684
+ if (equal != std::string::npos) {
685
+ value = name.substr(equal+1);
686
+ name = name.substr(0, equal);
687
+ }
688
+ design->verilog_defines->add(name, value);
689
+ continue;
690
+ }
691
+ if (arg.compare(0, 2, "-D") == 0) {
692
+ size_t equal = arg.find('=', 2);
693
+ std::string name = arg.substr(2, equal-2);
694
+ std::string value;
695
+ if (equal != std::string::npos)
696
+ value = arg.substr(equal+1);
697
+ design->verilog_defines->add(name, value);
698
+ continue;
699
+ }
700
+ if (arg == "-U" && argidx+1 < args.size()) {
701
+ std::string name = args[++argidx];
702
+ design->verilog_defines->erase(name);
703
+ continue;
704
+ }
705
+ if (arg.compare(0, 2, "-U") == 0) {
706
+ std::string name = arg.substr(2);
707
+ design->verilog_defines->erase(name);
708
+ continue;
709
+ }
710
+ if (arg == "-reset") {
711
+ design->verilog_defines->clear();
712
+ continue;
713
+ }
714
+ if (arg == "-list") {
715
+ design->verilog_defines->log();
716
+ continue;
717
+ }
718
+ break;
719
+ }
720
+
721
+ if (args.size() != argidx)
722
+ cmd_error(args, argidx, "Extra argument.");
723
+ }
724
+ } VerilogDefines;
725
+
726
+ static void parse_file_list(const std::string &file_list_path, RTLIL::Design *design, bool relative_to_file_list_path)
727
+ {
728
+ std::ifstream flist(file_list_path);
729
+ if (!flist.is_open()) {
730
+ log_error("Verilog file list file does not exist\n");
731
+ exit(1);
732
+ }
733
+
734
+ std::filesystem::path file_list_parent_dir = std::filesystem::path(file_list_path).parent_path();
735
+
736
+ std::string v_file_name;
737
+ while (std::getline(flist, v_file_name)) {
738
+ if (v_file_name.empty()) {
739
+ continue;
740
+ }
741
+
742
+ std::filesystem::path verilog_file_path;
743
+ if (relative_to_file_list_path) {
744
+ verilog_file_path = file_list_parent_dir / v_file_name;
745
+ } else {
746
+ verilog_file_path = std::filesystem::current_path() / v_file_name;
747
+ }
748
+
749
+ bool is_sv = (verilog_file_path.extension() == ".sv");
750
+
751
+ std::vector<std::string> read_verilog_cmd = {"read_verilog", "-defer"};
752
+ if (is_sv) {
753
+ read_verilog_cmd.push_back("-sv");
754
+ }
755
+ read_verilog_cmd.push_back(verilog_file_path.string());
756
+ Pass::call(design, read_verilog_cmd);
757
+ }
758
+
759
+ flist.close();
760
+ }
761
+
762
+ struct VerilogFileList : public Pass {
763
+ VerilogFileList() : Pass("read_verilog_file_list", "parse a Verilog file list") {}
764
+ void help() override
765
+ {
766
+ // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
767
+ log("\n");
768
+ log(" read_verilog_file_list [options]\n");
769
+ log("\n");
770
+ log("Parse a Verilog file list, and pass the list of Verilog files to read_verilog\n");
771
+ log("command\n");
772
+ log("\n");
773
+ log(" -F file_list_path\n");
774
+ log(" File list file contains list of Verilog files to be parsed, any path is\n");
775
+ log(" treated relative to the file list file\n");
776
+ log("\n");
777
+ log(" -f file_list_path\n");
778
+ log(" File list file contains list of Verilog files to be parsed, any path is\n");
779
+ log(" treated relative to current working directroy\n");
780
+ log("\n");
781
+ }
782
+
783
+ void execute(std::vector<std::string> args, RTLIL::Design *design) override
784
+ {
785
+ size_t argidx;
786
+ for (argidx = 1; argidx < args.size(); argidx++) {
787
+ std::string arg = args[argidx];
788
+ if (arg == "-F" && argidx + 1 < args.size()) {
789
+ std::string file_list_path = args[++argidx];
790
+ parse_file_list(file_list_path, design, true);
791
+ continue;
792
+ }
793
+ if (arg == "-f" && argidx + 1 < args.size()) {
794
+ std::string file_list_path = args[++argidx];
795
+ parse_file_list(file_list_path, design, false);
796
+ continue;
797
+ }
798
+ break;
799
+ }
800
+
801
+ extra_args(args, argidx, design, false);
802
+ }
803
+ } VerilogFilelist;
804
+
805
+ YOSYS_NAMESPACE_END
chips/yosys/frontends/verilog/verilog_frontend.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * The Verilog frontend.
21
+ *
22
+ * This frontend is using the AST frontend library (see frontends/ast/).
23
+ * Thus this frontend does not generate RTLIL code directly but creates an
24
+ * AST directly from the Verilog parse tree and then passes this AST to
25
+ * the AST frontend library.
26
+ *
27
+ */
28
+
29
+ #ifndef VERILOG_FRONTEND_H
30
+ #define VERILOG_FRONTEND_H
31
+
32
+ #include "kernel/yosys.h"
33
+ #include "frontends/ast/ast.h"
34
+
35
+ #include <stdio.h>
36
+ #include <stdint.h>
37
+
38
+ YOSYS_NAMESPACE_BEGIN
39
+
40
+ namespace VERILOG_FRONTEND
41
+ {
42
+ /* Ephemeral context class */
43
+ struct ConstParser {
44
+ AST::AstSrcLocType loc;
45
+ // original constant text, used in diagnostics when loc has no source file
46
+ std::string code_str = {};
47
+ private:
48
+ void log_maybe_loc_error(std::string msg);
49
+ void log_maybe_loc_warn(std::string msg);
50
+ // divide an arbitrary length decimal number by two and return the rest
51
+ int my_decimal_div_by_two(std::vector<uint8_t> &digits);
52
+ // find the number of significant bits in a binary number (not including the sign bit)
53
+ int my_ilog2(int x);
54
+ // parse a binary, decimal, hexadecimal or octal number with support for special bits ('x', 'z' and '?')
55
+ void my_strtobin(std::vector<RTLIL::State> &data, const char *str, int len_in_bits, int base, char case_type, bool is_unsized);
56
+ public:
57
+ // convert the Verilog code for a constant to an AST node
58
+ std::unique_ptr<AST::AstNode> const2ast(std::string code, char case_type = 0, bool warn_z = false);
59
+
60
+ };
61
+ };
62
+
63
+ YOSYS_NAMESPACE_END
64
+
65
+ #endif
chips/yosys/frontends/verilog/verilog_lexer.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef VERILOG_LEXER_H
2
+ #define VERILOG_LEXER_H
3
+
4
+ #include "kernel/yosys.h"
5
+ #include "frontends/ast/ast.h"
6
+ #include "frontends/verilog/verilog_parser.tab.hh"
7
+ #include <string>
8
+ #include <memory>
9
+
10
+ #if ! defined(yyFlexLexerOnce)
11
+ #define yyFlexLexer frontend_verilog_yyFlexLexer
12
+ #include <FlexLexer.h>
13
+ #endif
14
+
15
+ YOSYS_NAMESPACE_BEGIN
16
+
17
+ namespace VERILOG_FRONTEND {
18
+ using parser = frontend_verilog_yy::parser;
19
+ class VerilogLexer : public frontend_verilog_yyFlexLexer {
20
+ ParseState* extra;
21
+ ParseMode* mode;
22
+ parser::location_type out_loc;
23
+ public:
24
+ VerilogLexer(ParseState* e, ParseMode* m, std::shared_ptr<string> filename) : frontend_verilog_yyFlexLexer(e->lexin), extra(e), mode(m) {
25
+ out_loc.begin.filename = filename;
26
+ }
27
+ ~VerilogLexer() override {}
28
+ // autogenerated body due to YY_DECL
29
+ parser::symbol_type nextToken();
30
+ // get rid of override virtual function warning
31
+ using FlexLexer::yylex;
32
+ parser::symbol_type terminate() {
33
+ return parser::make_FRONTEND_VERILOG_YYEOF(out_loc);
34
+ }
35
+ private:
36
+ std::shared_ptr<std::string> current_filename;
37
+ std::vector<std::shared_ptr<std::string>> fn_stack;
38
+ std::vector<int> ln_stack;
39
+ int LexerInput(char* buf, int max_size) override {
40
+ return readsome(*extra->lexin, buf, max_size);
41
+ }
42
+ };
43
+
44
+ };
45
+
46
+ YOSYS_NAMESPACE_END
47
+
48
+ #endif
chips/yosys/frontends/verilog/verilog_lexer.l ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ * The Verilog frontend.
21
+ *
22
+ * This frontend is using the AST frontend library (see frontends/ast/).
23
+ * Thus this frontend does not generate RTLIL code directly but creates an
24
+ * AST directly from the Verilog parse tree and then passes this AST to
25
+ * the AST frontend library.
26
+ *
27
+ * ---
28
+ *
29
+ * A simple lexer for Verilog code. Non-preprocessor compiler directives are
30
+ * handled here. The preprocessor stuff is handled in preproc.cc. Everything
31
+ * else is left to the bison parser (see verilog_parser.y).
32
+ *
33
+ */
34
+
35
+ %option c++
36
+ %option yyclass="VerilogLexer"
37
+ %option noyywrap
38
+ %option nounput
39
+ %option yylineno
40
+ %option prefix="frontend_verilog_yy"
41
+
42
+ %{
43
+
44
+ #ifdef __clang__
45
+ // bison generates code using the 'register' storage class specifier
46
+ #pragma clang diagnostic ignored "-Wdeprecated-register"
47
+ // flex generates weirdly-indented code
48
+ #pragma clang diagnostic ignored "-Wmisleading-indentation"
49
+ #endif
50
+
51
+ #include "frontends/verilog/verilog_lexer.h"
52
+ #include "frontends/ast/ast.h"
53
+ #include "frontends/verilog/verilog_location.h"
54
+ #include "kernel/log.h"
55
+ #include <vector>
56
+ #include <memory>
57
+
58
+ USING_YOSYS_NAMESPACE
59
+ using namespace AST;
60
+ using namespace VERILOG_FRONTEND;
61
+ using parser = frontend_verilog_yy::parser;
62
+
63
+ YOSYS_NAMESPACE_BEGIN
64
+ #undef YY_DECL
65
+ #define YY_DECL parser::symbol_type VerilogLexer::nextToken()
66
+
67
+ #undef yyterminate
68
+ #define yyterminate() return terminate()
69
+
70
+ YOSYS_NAMESPACE_END
71
+
72
+ #define SV_KEYWORD(_tok) \
73
+ if (mode->sv) return _tok; \
74
+ log("Lexer warning: The SystemVerilog keyword `%s' (at %s:%d) is not "\
75
+ "recognized unless read_verilog is called with -sv!\n", YYText(), \
76
+ current_filename->c_str(), yylineno); \
77
+ string_t val = std::make_unique<std::string>(std::string("\\") + YYText()); \
78
+ return parser::make_TOK_ID(std::move(val), out_loc);
79
+
80
+ #define NON_KEYWORD() \
81
+ string_t val = std::make_unique<std::string>(std::string("\\") + YYText()); \
82
+ return parser::make_TOK_ID(std::move(val), out_loc);
83
+
84
+
85
+ #define YY_USER_ACTION \
86
+ out_loc.step(); \
87
+ for(int i = 0; YYText()[i] != '\0'; ++i){ \
88
+ if(YYText()[i] == '\n') { \
89
+ out_loc.lines(); \
90
+ } \
91
+ else { \
92
+ out_loc.columns(); \
93
+ } \
94
+ } \
95
+ out_loc.begin.filename = current_filename; \
96
+ out_loc.end.filename = current_filename;
97
+
98
+ #define YY_BREAK \
99
+ break;
100
+
101
+ #undef YY_BUF_SIZE
102
+ #define YY_BUF_SIZE 65536
103
+
104
+ static bool isUserType(ParseState* extra, std::string &s)
105
+ {
106
+ // check current scope then outer scopes for a name
107
+ for (auto it = extra->user_type_stack.rbegin(); it != extra->user_type_stack.rend(); ++it) {
108
+ if (it->count(s) > 0) {
109
+ return true;
110
+ }
111
+ }
112
+ return false;
113
+ }
114
+
115
+ parser::symbol_type char_tok(char c, parser::location_type loc) {
116
+ switch (c) {
117
+ case '!': return parser::make_TOK_EXCL(loc);
118
+ case '#': return parser::make_TOK_HASH(loc);
119
+ case '%': return parser::make_TOK_PERC(loc);
120
+ case '&': return parser::make_TOK_AMP(loc);
121
+ case '(': return parser::make_TOK_LPAREN(loc);
122
+ case ')': return parser::make_TOK_RPAREN(loc);
123
+ case '*': return parser::make_TOK_ASTER(loc);
124
+ case '+': return parser::make_TOK_PLUS(loc);
125
+ case ',': return parser::make_TOK_COMMA(loc);
126
+ case '-': return parser::make_TOK_MINUS(loc);
127
+ case '.': return parser::make_TOK_DOT(loc);
128
+ case '/': return parser::make_TOK_SLASH(loc);
129
+ case ':': return parser::make_TOK_COL(loc);
130
+ case ';': return parser::make_TOK_SEMICOL(loc);
131
+ case '<': return parser::make_TOK_LT(loc);
132
+ case '=': return parser::make_TOK_EQ(loc);
133
+ case '>': return parser::make_TOK_GT(loc);
134
+ case '?': return parser::make_TOK_QUE(loc);
135
+ case '@': return parser::make_TOK_AT(loc);
136
+ case '[': return parser::make_TOK_LBRA(loc);
137
+ case ']': return parser::make_TOK_RBRA(loc);
138
+ case '^': return parser::make_TOK_CARET(loc);
139
+ case '_': return parser::make_TOK_UNDER(loc);
140
+ case '{': return parser::make_TOK_LCURL(loc);
141
+ case '|': return parser::make_TOK_PIPE(loc);
142
+ case '}': return parser::make_TOK_RCURL(loc);
143
+ case '~': return parser::make_TOK_TILDE(loc);
144
+ case 'n': return parser::make_TOK_n(loc);
145
+ case 'p': return parser::make_TOK_p(loc);
146
+ case 'x': return parser::make_TOK_x(loc);
147
+ case 'z': return parser::make_TOK_z(loc);
148
+ case 0: return parser::make_FRONTEND_VERILOG_YYEOF(loc);
149
+ default:
150
+ return parser::make_ch_t(c, loc);
151
+ }
152
+ }
153
+ static bool is_hex_dig(char c, int *val, parser::location_type loc)
154
+ {
155
+ if ('0' <= c && c <= '9') {
156
+ *val = c - '0';
157
+ return true;
158
+ } else if ('a' <= c && c <= 'f') {
159
+ *val = c - 'a' + 0xA;
160
+ return true;
161
+ } else if ('A' <= c && c <= 'F') {
162
+ *val = c - 'A' + 0xA;
163
+ return true;
164
+ } else if (c == 'x' || c == 'X' || c == 'z' || c == 'Z' || c == '?') {
165
+ log_file_warning(loc.to_loc(), "'%c' not a valid digit in hex escape sequence.\n", c);
166
+ *val = 0; // not semantically valid in hex escape...
167
+ return true; // ...but still processed as part of hex token
168
+ }
169
+
170
+ return false;
171
+ }
172
+
173
+ static bool is_oct_dig(char c, int *val, parser::location_type loc)
174
+ {
175
+ if ('0' <= c && c <= '7') {
176
+ *val = c - '0';
177
+ return true;
178
+ } else if (c == 'x' || c == 'X' || c == 'z' || c == 'Z' || c == '?') {
179
+ log_file_warning(loc.to_loc(), "'%c' not a valid digit in octal escape sequence.\n", c);
180
+ *val = 0; // not semantically valid in octal escape...
181
+ return true; // ...but still processed as part of octal token
182
+ }
183
+
184
+ return false;
185
+ }
186
+
187
+ static parser::symbol_type process_str(char *str, int len, bool triple, parser::location_type loc)
188
+ {
189
+ char *in, *out; // Overwrite input buffer: flex manual states "Actions
190
+ // are free to modify 'yytext' except for lengthening it".
191
+
192
+ for (in = str, out = str; in < str + len; in++)
193
+ switch (*in) {
194
+ case '\n':
195
+ case '\r':
196
+ if (in + 1 < str + len && (in[1] ^ *in) == ('\n' ^ '\r'))
197
+ in++;
198
+ if (!triple)
199
+ log_file_warning(loc.to_loc(), "Multi-line string literals should be triple-quoted or escaped.\n");
200
+ *out++ = '\n';
201
+ break;
202
+ case '\\':
203
+ in++;
204
+ log_assert(in < str + len);
205
+ switch (*in) {
206
+ case 'a':
207
+ *out++ = '\a';
208
+ break;
209
+ case 'f':
210
+ *out++ = '\f';
211
+ break;
212
+ case 'n':
213
+ *out++ = '\n';
214
+ break;
215
+ case 'r': /* not part of IEEE-1800 2023, but seems
216
+ like a good idea to support it anyway */
217
+ *out++ = '\r';
218
+ break;
219
+ case 't':
220
+ *out++ = '\t';
221
+ break;
222
+ case 'v':
223
+ *out++ = '\v';
224
+ break;
225
+ case 'x':
226
+ int val;
227
+ if (in + 1 < str + len && is_hex_dig(in[1], &val, loc)) {
228
+ *out = val;
229
+ in++;
230
+ if (in + 1 < str + len && is_hex_dig(in[1], &val, loc)) {
231
+ *out = *out * 0x10 + val;
232
+ in++;
233
+ }
234
+ out++;
235
+ } else
236
+ log_file_warning(loc.to_loc(), "ignoring invalid hex escape.\n");
237
+ break;
238
+ case '\\':
239
+ *out++ = '\\';
240
+ break;
241
+ case '"':
242
+ *out++ = '"';
243
+ break;
244
+ case '\n':
245
+ case '\r':
246
+ if (in + 1 < str + len && (in[1] ^ *in) == ('\n' ^ '\r'))
247
+ in++;
248
+ break;
249
+ default:
250
+ if ('0' <= *in && *in <= '7') {
251
+ int val;
252
+
253
+ *out = *in - '0';
254
+ if (in + 1 < str + len && is_oct_dig(in[1], &val, loc)) {
255
+ *out = *out * 010 + val;
256
+ in++;
257
+ if (in + 1 < str + len && is_oct_dig(in[1], &val, loc)) {
258
+ if (*out >= 040)
259
+ log_file_warning(loc.to_loc(), "octal escape exceeds \\377\n");
260
+ *out = *out * 010 + val;
261
+ in++;
262
+ }
263
+ }
264
+ out++;
265
+ } else
266
+ *out++ = *in;
267
+ }
268
+ break;
269
+ default:
270
+ *out++ = *in;
271
+ }
272
+
273
+ return parser::make_TOK_STRING(std::make_unique<std::string>(str, out - str), loc);
274
+ }
275
+
276
+ %}
277
+
278
+ %x COMMENT
279
+ %x SYNOPSYS_TRANSLATE_OFF
280
+ %x SYNOPSYS_FLAGS
281
+ %x IMPORT_DPI
282
+ %x BASED_CONST
283
+
284
+ UNSIGNED_NUMBER [0-9][0-9_]*
285
+ FIXED_POINT_NUMBER_DEC [0-9][0-9_]*\.[0-9][0-9_]*([eE][-+]?[0-9_]+)?
286
+ FIXED_POINT_NUMBER_NO_DEC [0-9][0-9_]*[eE][-+]?[0-9_]+
287
+ TIME_SCALE_SUFFIX [munpf]?s
288
+
289
+ %%
290
+
291
+ // Initialise comment_caller to something to avoid a "maybe undefined"
292
+ // warning from GCC.
293
+ int comment_caller = INITIAL;
294
+
295
+ <INITIAL,SYNOPSYS_TRANSLATE_OFF>"`file_push "[^\n]* {
296
+ fn_stack.push_back(current_filename);
297
+ ln_stack.push_back(yylineno);
298
+ std::string filename = YYText()+11;
299
+ if (!filename.empty() && filename.front() == '"')
300
+ filename = filename.substr(1);
301
+ if (!filename.empty() && filename.back() == '"')
302
+ filename = filename.substr(0, filename.size()-1);
303
+ current_filename = std::make_shared<std::string>(filename);
304
+ yylineno = (0);
305
+ out_loc.begin.line = out_loc.end.line = 0;
306
+ }
307
+
308
+ <INITIAL,SYNOPSYS_TRANSLATE_OFF>"`file_pop"[^\n]*\n {
309
+ current_filename = fn_stack.back();
310
+ fn_stack.pop_back();
311
+ yylineno = (ln_stack.back());
312
+ out_loc.begin.line = out_loc.end.line = ln_stack.back();
313
+ ln_stack.pop_back();
314
+ }
315
+
316
+ <INITIAL,SYNOPSYS_TRANSLATE_OFF>"`line"[ \t]+[^ \t\r\n]+[ \t]+\"[^ \r\n]+\"[^\r\n]*\n {
317
+ const char *p = YYText() + 5;
318
+ while (*p == ' ' || *p == '\t') p++;
319
+ yylineno = (atoi(p));
320
+ out_loc.begin.line = out_loc.end.line = atoi(p);
321
+ while (*p && *p != ' ' && *p != '\t') p++;
322
+ while (*p == ' ' || *p == '\t') p++;
323
+ const char *q = *p ? p + 1 : p;
324
+ while (*q && *q != '"') q++;
325
+ current_filename = std::make_shared<std::string>(std::string(p).substr(1, q-p-1));
326
+ }
327
+
328
+ "`file_notfound "[^\n]* {
329
+ log_error("Can't open include file `%s'!\n", YYText() + 15);
330
+ }
331
+
332
+ "`timescale"[ \t]+[^ \t\r\n/]+[ \t]*"/"[ \t]*[^ \t\r\n]* /* ignore timescale directive */
333
+
334
+ "`celldefine"[^\n]* /* ignore `celldefine */
335
+ "`endcelldefine"[^\n]* /* ignore `endcelldefine */
336
+
337
+ "`default_nettype"[ \t]+[^ \t\r\n/]+ {
338
+ const char *p = YYText();
339
+ while (*p != 0 && *p != ' ' && *p != '\t') p++;
340
+ while (*p == ' ' || *p == '\t') p++;
341
+ if (!strcmp(p, "none"))
342
+ extra->default_nettype_wire = false;
343
+ else if (!strcmp(p, "wire"))
344
+ extra->default_nettype_wire = true;
345
+ else
346
+ err_at_loc(out_loc, "Unsupported default nettype: %s", p);
347
+ }
348
+
349
+ "`protect"[^\n]* /* ignore `protect*/
350
+ "`endprotect"[^\n]* /* ignore `endprotect*/
351
+
352
+ "`"[a-zA-Z_$][a-zA-Z0-9_$]* {
353
+ err_at_loc(out_loc, "Unimplemented compiler directive or undefined macro %s.", YYText());
354
+ }
355
+
356
+ "module" { return parser::make_TOK_MODULE(out_loc); }
357
+ "endmodule" { return parser::make_TOK_ENDMODULE(out_loc); }
358
+ "function" { return parser::make_TOK_FUNCTION(out_loc); }
359
+ "endfunction" { return parser::make_TOK_ENDFUNCTION(out_loc); }
360
+ "task" { return parser::make_TOK_TASK(out_loc); }
361
+ "endtask" { return parser::make_TOK_ENDTASK(out_loc); }
362
+ "specify" { return mode->specify ? parser::make_TOK_SPECIFY(out_loc) : parser::make_TOK_IGNORED_SPECIFY(out_loc); }
363
+ "endspecify" { return parser::make_TOK_ENDSPECIFY(out_loc); }
364
+ "specparam" { return parser::make_TOK_SPECPARAM(out_loc); }
365
+ "package" { SV_KEYWORD(parser::make_TOK_PACKAGE(out_loc)); }
366
+ "endpackage" { SV_KEYWORD(parser::make_TOK_ENDPACKAGE(out_loc)); }
367
+ "import" { SV_KEYWORD(parser::make_TOK_IMPORT(out_loc)); }
368
+ "interface" { SV_KEYWORD(parser::make_TOK_INTERFACE(out_loc)); }
369
+ "endinterface" { SV_KEYWORD(parser::make_TOK_ENDINTERFACE(out_loc)); }
370
+ "modport" { SV_KEYWORD(parser::make_TOK_MODPORT(out_loc)); }
371
+ "parameter" { return parser::make_TOK_PARAMETER(out_loc); }
372
+ "localparam" { return parser::make_TOK_LOCALPARAM(out_loc); }
373
+ "defparam" { return parser::make_TOK_DEFPARAM(out_loc); }
374
+ "assign" { return parser::make_TOK_ASSIGN(out_loc); }
375
+ "always" { return parser::make_TOK_ALWAYS(out_loc); }
376
+ "initial" { return parser::make_TOK_INITIAL(out_loc); }
377
+ "begin" { return parser::make_TOK_BEGIN(out_loc); }
378
+ "end" { return parser::make_TOK_END(out_loc); }
379
+ "if" { return parser::make_TOK_IF(out_loc); }
380
+ "ifnone" { return parser::make_TOK_IFNONE(out_loc); }
381
+ "else" { return parser::make_TOK_ELSE(out_loc); }
382
+ "for" { return parser::make_TOK_FOR(out_loc); }
383
+ "posedge" { return parser::make_TOK_POSEDGE(out_loc); }
384
+ "negedge" { return parser::make_TOK_NEGEDGE(out_loc); }
385
+ "or" { return parser::make_TOK_OR(out_loc); }
386
+ "case" { return parser::make_TOK_CASE(out_loc); }
387
+ "casex" { return parser::make_TOK_CASEX(out_loc); }
388
+ "casez" { return parser::make_TOK_CASEZ(out_loc); }
389
+ "endcase" { return parser::make_TOK_ENDCASE(out_loc); }
390
+ "default" { return parser::make_TOK_DEFAULT(out_loc); }
391
+ "generate" { return parser::make_TOK_GENERATE(out_loc); }
392
+ "endgenerate" { return parser::make_TOK_ENDGENERATE(out_loc); }
393
+ "while" { return parser::make_TOK_WHILE(out_loc); }
394
+ "repeat" { return parser::make_TOK_REPEAT(out_loc); }
395
+ "automatic" { return parser::make_TOK_AUTOMATIC(out_loc); }
396
+
397
+ "unique" { SV_KEYWORD(parser::make_TOK_UNIQUE(out_loc)); }
398
+ "unique0" { SV_KEYWORD(parser::make_TOK_UNIQUE0(out_loc)); }
399
+ "priority" { SV_KEYWORD(parser::make_TOK_PRIORITY(out_loc)); }
400
+
401
+ "always_comb" { SV_KEYWORD(parser::make_TOK_ALWAYS_COMB(out_loc)); }
402
+ "always_ff" { SV_KEYWORD(parser::make_TOK_ALWAYS_FF(out_loc)); }
403
+ "always_latch" { SV_KEYWORD(parser::make_TOK_ALWAYS_LATCH(out_loc)); }
404
+
405
+ /* use special token for labels on assert, assume, cover, and restrict because it's insanley complex
406
+ to fix parsing of cells otherwise. (the current cell parser forces a reduce very early to update some
407
+ global state.. its a mess) */
408
+ [a-zA-Z_$][a-zA-Z0-9_$]*/[ \t\r\n]*:[ \t\r\n]*(assert|assume|cover|restrict)[^a-zA-Z0-9_$\.] {
409
+ if (!strcmp(YYText(), "default"))
410
+ return parser::make_TOK_DEFAULT(out_loc);
411
+ string_t val = std::make_unique<std::string>(std::string("\\") + YYText());
412
+ return parser::make_TOK_SVA_LABEL(std::move(val), out_loc);
413
+ }
414
+
415
+ "assert" { if (mode->formal) return parser::make_TOK_ASSERT(out_loc); SV_KEYWORD(parser::make_TOK_ASSERT(out_loc)); }
416
+ "assume" { if (mode->formal) return parser::make_TOK_ASSUME(out_loc); SV_KEYWORD(parser::make_TOK_ASSUME(out_loc)); }
417
+ "cover" { if (mode->formal) return parser::make_TOK_COVER(out_loc); SV_KEYWORD(parser::make_TOK_COVER(out_loc)); }
418
+ "restrict" { if (mode->formal) return parser::make_TOK_RESTRICT(out_loc); SV_KEYWORD(parser::make_TOK_RESTRICT(out_loc)); }
419
+ "property" { if (mode->formal) return parser::make_TOK_PROPERTY(out_loc); SV_KEYWORD(parser::make_TOK_PROPERTY(out_loc)); }
420
+ "rand" { if (mode->formal) return parser::make_TOK_RAND(out_loc); SV_KEYWORD(parser::make_TOK_RAND(out_loc)); }
421
+ "const" { if (mode->formal) return parser::make_TOK_CONST(out_loc); SV_KEYWORD(parser::make_TOK_CONST(out_loc)); }
422
+ "checker" { if (mode->formal) return parser::make_TOK_CHECKER(out_loc); SV_KEYWORD(parser::make_TOK_CHECKER(out_loc)); }
423
+ "endchecker" { if (mode->formal) return parser::make_TOK_ENDCHECKER(out_loc); SV_KEYWORD(parser::make_TOK_ENDCHECKER(out_loc)); }
424
+ "final" { SV_KEYWORD(parser::make_TOK_FINAL(out_loc)); }
425
+ "logic" { SV_KEYWORD(parser::make_TOK_LOGIC(out_loc)); }
426
+ "var" { SV_KEYWORD(parser::make_TOK_VAR(out_loc)); }
427
+ "bit" { SV_KEYWORD(parser::make_TOK_LOGIC(out_loc)); }
428
+ "int" { SV_KEYWORD(parser::make_TOK_INT(out_loc)); }
429
+ "byte" { SV_KEYWORD(parser::make_TOK_BYTE(out_loc)); }
430
+ "shortint" { SV_KEYWORD(parser::make_TOK_SHORTINT(out_loc)); }
431
+ "longint" { SV_KEYWORD(parser::make_TOK_LONGINT(out_loc)); }
432
+ "void" { SV_KEYWORD(parser::make_TOK_VOID(out_loc)); }
433
+
434
+ "eventually" { if (mode->formal) return parser::make_TOK_EVENTUALLY(out_loc); SV_KEYWORD(parser::make_TOK_EVENTUALLY(out_loc)); }
435
+ "s_eventually" { if (mode->formal) return parser::make_TOK_EVENTUALLY(out_loc); SV_KEYWORD(parser::make_TOK_EVENTUALLY(out_loc)); }
436
+
437
+ "input" { return parser::make_TOK_INPUT(out_loc); }
438
+ "output" { return parser::make_TOK_OUTPUT(out_loc); }
439
+ "inout" { return parser::make_TOK_INOUT(out_loc); }
440
+ "wire" { return parser::make_TOK_WIRE(out_loc); }
441
+ "tri" { return parser::make_TOK_WIRE(out_loc); }
442
+ "wor" { return parser::make_TOK_WOR(out_loc); }
443
+ "trior" { return parser::make_TOK_WOR(out_loc); }
444
+ "wand" { return parser::make_TOK_WAND(out_loc); }
445
+ "triand" { return parser::make_TOK_WAND(out_loc); }
446
+ "reg" { return parser::make_TOK_REG(out_loc); }
447
+ "integer" { return parser::make_TOK_INTEGER(out_loc); }
448
+ "signed" { return parser::make_TOK_SIGNED(out_loc); }
449
+ "unsigned" { SV_KEYWORD(parser::make_TOK_UNSIGNED(out_loc)); }
450
+ "genvar" { return parser::make_TOK_GENVAR(out_loc); }
451
+ "real" { return parser::make_TOK_REAL(out_loc); }
452
+
453
+ "enum" { SV_KEYWORD(parser::make_TOK_ENUM(out_loc)); }
454
+ "typedef" { SV_KEYWORD(parser::make_TOK_TYPEDEF(out_loc)); }
455
+ "struct" { SV_KEYWORD(parser::make_TOK_STRUCT(out_loc)); }
456
+ "union" { SV_KEYWORD(parser::make_TOK_UNION(out_loc)); }
457
+ "packed" { SV_KEYWORD(parser::make_TOK_PACKED(out_loc)); }
458
+
459
+ {UNSIGNED_NUMBER} {
460
+ string_t val = std::make_unique<std::string>(YYText());
461
+ return parser::make_TOK_CONSTVAL(std::move(val), out_loc);
462
+ }
463
+
464
+ \'[01zxZX] {
465
+ string_t val = std::make_unique<std::string>(YYText());
466
+ return parser::make_TOK_UNBASED_UNSIZED_CONSTVAL(std::move(val), out_loc);
467
+ }
468
+
469
+ \'[sS]?[bodhBODH] {
470
+ BEGIN(BASED_CONST);
471
+ string_t val = std::make_unique<std::string>(YYText());
472
+ return parser::make_TOK_BASE(std::move(val), out_loc);
473
+ }
474
+
475
+ <BASED_CONST>[0-9a-fA-FzxZX?][0-9a-fA-FzxZX?_]* {
476
+ BEGIN(0);
477
+ string_t val = std::make_unique<std::string>(YYText());
478
+ return parser::make_TOK_BASED_CONSTVAL(std::move(val), out_loc);
479
+ }
480
+
481
+ {FIXED_POINT_NUMBER_DEC} {
482
+ string_t val = std::make_unique<std::string>(YYText());
483
+ return parser::make_TOK_REALVAL(std::move(val), out_loc);
484
+ }
485
+
486
+ {FIXED_POINT_NUMBER_NO_DEC} {
487
+ string_t val = std::make_unique<std::string>(YYText());
488
+ return parser::make_TOK_REALVAL(std::move(val), out_loc);
489
+ }
490
+
491
+ \"([^\\"]|\\.|\\\n)*\" { return process_str(yytext + 1, yyleng - 2, false, out_loc); }
492
+
493
+ \"{3}(\"{0,2}([^\\"]|\\.|\\\n))*\"{3} { return process_str(yytext + 3, yyleng - 6, true, out_loc); }
494
+
495
+ and|nand|or|nor|xor|xnor|not|buf|bufif0|bufif1|notif0|notif1|tran {
496
+ auto val = std::make_unique<std::string>(YYText());
497
+ return parser::make_TOK_PRIMITIVE(std::move(val), out_loc);
498
+ }
499
+
500
+ supply0 { return parser::make_TOK_SUPPLY0(out_loc); }
501
+ supply1 { return parser::make_TOK_SUPPLY1(out_loc); }
502
+
503
+ "$"(display[bho]?|write[bho]?|strobe|monitor|time|realtime|stop|finish|dumpfile|dumpvars|dumpon|dumpoff|dumpall) {
504
+ auto val = std::make_unique<std::string>(YYText());
505
+ return parser::make_TOK_ID(std::move(val), out_loc);
506
+ }
507
+
508
+ "$"(setup|hold|setuphold|removal|recovery|recrem|skew|timeskew|fullskew|nochange) {
509
+ if (!mode->specify) REJECT;
510
+ auto val = std::make_unique<std::string>(YYText());
511
+ return parser::make_TOK_ID(std::move(val), out_loc);
512
+ }
513
+
514
+ "$"(info|warning|error|fatal) {
515
+ auto val = std::make_unique<std::string>(YYText());
516
+ return parser::make_TOK_MSG_TASKS(std::move(val), out_loc);
517
+ }
518
+
519
+ "$signed" { return parser::make_TOK_TO_SIGNED(out_loc); }
520
+ "$unsigned" { return parser::make_TOK_TO_UNSIGNED(out_loc); }
521
+
522
+ [a-zA-Z_][a-zA-Z0-9_]*::[a-zA-Z_$][a-zA-Z0-9_$]* {
523
+ // package qualifier
524
+ auto s = std::string("\\") + YYText();
525
+ if (extra->pkg_user_types.count(s) > 0) {
526
+ // package qualified typedefed name
527
+ auto val = std::make_unique<std::string>(s);
528
+ return parser::make_TOK_PKG_USER_TYPE(std::move(val), out_loc);
529
+ }
530
+ else {
531
+ // backup before :: just return first part
532
+ size_t len = strchr(YYText(), ':') - YYText();
533
+ yyless(len);
534
+ auto val = std::make_unique<std::string>(std::string("\\") + YYText());
535
+ return parser::make_TOK_ID(std::move(val), out_loc);
536
+ }
537
+ }
538
+
539
+ [a-zA-Z_$][a-zA-Z0-9_$]* {
540
+ auto s = std::string("\\") + YYText();
541
+ if (isUserType(extra, s)) {
542
+ // previously typedefed name
543
+ auto val = std::make_unique<std::string>(s);
544
+ return parser::make_TOK_USER_TYPE(std::move(val), out_loc);
545
+ }
546
+ else {
547
+ auto val = std::make_unique<std::string>(std::string("\\") + YYText());
548
+ return parser::make_TOK_ID(std::move(val), out_loc);
549
+ }
550
+ }
551
+
552
+ [a-zA-Z_$][a-zA-Z0-9_$\.]* {
553
+ auto val = std::make_unique<std::string>(std::string("\\") + YYText());
554
+ return parser::make_TOK_ID(std::move(val), out_loc);
555
+ }
556
+
557
+ "/*"[ \t]*(synopsys|synthesis)[ \t]*translate_off[ \t]*"*/" {
558
+ static bool printed_warning = false;
559
+ if (!printed_warning) {
560
+ log_warning(
561
+ "Encountered `translate_off' comment! Such legacy hot "
562
+ "comments are supported by Yosys, but are not part of "
563
+ "any formal language specification. Using a portable "
564
+ "and standards-compliant construct such as `ifdef is "
565
+ "recommended!\n"
566
+ );
567
+ printed_warning = true;
568
+ }
569
+ BEGIN(SYNOPSYS_TRANSLATE_OFF);
570
+ }
571
+ <SYNOPSYS_TRANSLATE_OFF>. /* ignore synopsys translate_off body */
572
+ <SYNOPSYS_TRANSLATE_OFF>\n /* ignore synopsys translate_off body */
573
+ <SYNOPSYS_TRANSLATE_OFF>"/*"[ \t]*(synopsys|synthesis)[ \t]*"translate_on"[ \t]*"*/" { BEGIN(0); }
574
+
575
+ "/*"[ \t]*(synopsys|synthesis)[ \t]+ {
576
+ BEGIN(SYNOPSYS_FLAGS);
577
+ }
578
+ <SYNOPSYS_FLAGS>full_case {
579
+ static bool printed_warning = false;
580
+ if (!printed_warning) {
581
+ log_warning(
582
+ "Encountered `full_case' comment! Such legacy hot "
583
+ "comments are supported by Yosys, but are not part of "
584
+ "any formal language specification. Using the Verilog "
585
+ "`full_case' attribute or the SystemVerilog `unique' "
586
+ "or `unique0' keywords is recommended!\n"
587
+ );
588
+ printed_warning = true;
589
+ }
590
+ return parser::make_TOK_SYNOPSYS_FULL_CASE(out_loc);
591
+ }
592
+ <SYNOPSYS_FLAGS>parallel_case {
593
+ static bool printed_warning = false;
594
+ if (!printed_warning) {
595
+ log_warning(
596
+ "Encountered `parallel_case' comment! Such legacy hot "
597
+ "comments are supported by Yosys, but are not part of "
598
+ "any formal language specification. Using the Verilog "
599
+ "`parallel_case' attribute or the SystemVerilog "
600
+ "`unique' or `priority' keywords is recommended!\n"
601
+ );
602
+ printed_warning = true;
603
+ }
604
+ return parser::make_TOK_SYNOPSYS_PARALLEL_CASE(out_loc);
605
+ }
606
+ <SYNOPSYS_FLAGS>. /* ignore everything else */
607
+ <SYNOPSYS_FLAGS>"*/" { BEGIN(0); }
608
+
609
+ import[ \t\r\n]+\"(DPI|DPI-C)\"[ \t\r\n]+function[ \t\r\n]+ {
610
+ BEGIN(IMPORT_DPI);
611
+ return parser::make_TOK_DPI_FUNCTION(out_loc);
612
+ }
613
+
614
+ <IMPORT_DPI>[a-zA-Z_$][a-zA-Z0-9_$]* {
615
+ auto val = std::make_unique<std::string>(std::string("\\") + YYText());
616
+ return parser::make_TOK_ID(std::move(val), out_loc);
617
+ }
618
+
619
+ <IMPORT_DPI>[ \t\r\n] /* ignore whitespaces */
620
+
621
+ <IMPORT_DPI>";" {
622
+ BEGIN(0);
623
+ return char_tok(*YYText(), out_loc);
624
+ }
625
+
626
+ <IMPORT_DPI>. {
627
+ return char_tok(*YYText(), out_loc);
628
+ }
629
+
630
+ "\\"[^ \t\r\n]+ {
631
+ auto val = std::make_unique<std::string>(YYText());
632
+ return parser::make_TOK_ID(std::move(val), out_loc);
633
+ }
634
+
635
+ "(*" { return parser::make_ATTR_BEGIN(out_loc); }
636
+ "*)" { return parser::make_ATTR_END(out_loc); }
637
+
638
+ "{*" { return parser::make_DEFATTR_BEGIN(out_loc); }
639
+ "*}" { return parser::make_DEFATTR_END(out_loc); }
640
+
641
+ "**" { return parser::make_OP_POW(out_loc); }
642
+ "||" { return parser::make_OP_LOR(out_loc); }
643
+ "&&" { return parser::make_OP_LAND(out_loc); }
644
+ "==" { return parser::make_OP_EQ(out_loc); }
645
+ "!=" { return parser::make_OP_NE(out_loc); }
646
+ "<=" { return parser::make_OP_LE(out_loc); }
647
+ ">=" { return parser::make_OP_GE(out_loc); }
648
+
649
+ "===" { return parser::make_OP_EQX(out_loc); }
650
+ "!==" { return parser::make_OP_NEX(out_loc); }
651
+
652
+ "~&" { return parser::make_OP_NAND(out_loc); }
653
+ "~|" { return parser::make_OP_NOR(out_loc); }
654
+ "~^" { return parser::make_OP_XNOR(out_loc); }
655
+ "^~" { return parser::make_OP_XNOR(out_loc); }
656
+
657
+ "<<" { return parser::make_OP_SHL(out_loc); }
658
+ ">>" { return parser::make_OP_SHR(out_loc); }
659
+ "<<<" { return parser::make_OP_SSHL(out_loc); }
660
+ ">>>" { return parser::make_OP_SSHR(out_loc); }
661
+
662
+ "'" { return parser::make_OP_CAST(out_loc); }
663
+
664
+ "::" { return parser::make_TOK_PACKAGESEP(out_loc); }
665
+ "++" { return parser::make_TOK_INCREMENT(out_loc); }
666
+ "--" { return parser::make_TOK_DECREMENT(out_loc); }
667
+
668
+ "+:" { return parser::make_TOK_POS_INDEXED(out_loc); }
669
+ "-:" { return parser::make_TOK_NEG_INDEXED(out_loc); }
670
+
671
+ ".*" { return parser::make_TOK_WILDCARD_CONNECT(out_loc); }
672
+
673
+ "|=" { SV_KEYWORD(parser::make_TOK_BIT_OR_ASSIGN(out_loc)); }
674
+ "&=" { SV_KEYWORD(parser::make_TOK_BIT_AND_ASSIGN(out_loc)); }
675
+ "+=" { SV_KEYWORD(parser::make_TOK_ADD_ASSIGN(out_loc)); }
676
+ "-=" { SV_KEYWORD(parser::make_TOK_SUB_ASSIGN(out_loc)); }
677
+ "^=" { SV_KEYWORD(parser::make_TOK_BIT_XOR_ASSIGN(out_loc)); }
678
+ "/=" { SV_KEYWORD(parser::make_TOK_DIV_ASSIGN(out_loc)); }
679
+ "%=" { SV_KEYWORD(parser::make_TOK_MOD_ASSIGN(out_loc)); }
680
+ "*=" { SV_KEYWORD(parser::make_TOK_MUL_ASSIGN(out_loc)); }
681
+ "<<=" { SV_KEYWORD(parser::make_TOK_SHL_ASSIGN(out_loc)); }
682
+ ">>=" { SV_KEYWORD(parser::make_TOK_SHR_ASSIGN(out_loc)); }
683
+ "<<<=" { SV_KEYWORD(parser::make_TOK_SSHL_ASSIGN(out_loc)); }
684
+ ">>>=" { SV_KEYWORD(parser::make_TOK_SSHR_ASSIGN(out_loc)); }
685
+
686
+ [-+]?[=*]> {
687
+ if (!mode->specify) REJECT;
688
+ auto val = std::make_unique<std::string>(YYText());
689
+ return parser::make_TOK_SPECIFY_OPER(std::move(val), out_loc);
690
+ }
691
+
692
+ "&&&" {
693
+ if (!mode->specify) return parser::make_TOK_IGNORED_SPECIFY_AND(out_loc);
694
+ return parser::make_TOK_SPECIFY_AND(out_loc);
695
+ }
696
+
697
+ {UNSIGNED_NUMBER}{TIME_SCALE_SUFFIX} { return parser::make_TOK_TIME_SCALE(out_loc); }
698
+ {FIXED_POINT_NUMBER_DEC}{TIME_SCALE_SUFFIX} { return parser::make_TOK_TIME_SCALE(out_loc); }
699
+ {FIXED_POINT_NUMBER_NO_DEC}{TIME_SCALE_SUFFIX} { return parser::make_TOK_TIME_SCALE(out_loc); }
700
+
701
+ <INITIAL,BASED_CONST>"/*" { comment_caller=YY_START; BEGIN(COMMENT); }
702
+ <COMMENT>. /* ignore comment body */
703
+ <COMMENT>\n /* ignore comment body */
704
+ <COMMENT>"*/" { BEGIN(comment_caller); }
705
+
706
+
707
+ <INITIAL,BASED_CONST>[ \t\r\n] /* ignore whitespaces */
708
+ <INITIAL,BASED_CONST>\\[\r\n] /* ignore continuation sequence */
709
+ <INITIAL,BASED_CONST>"//"[^\r\n]* /* ignore one-line comments */
710
+
711
+ <INITIAL>. { return char_tok(*YYText(), out_loc); }
712
+ <*>. { BEGIN(0); return char_tok(*YYText(), out_loc); }
713
+
714
+ %%
chips/yosys/frontends/verilog/verilog_location.h ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef VERILOG_LOCATION_H
2
+ #define VERILOG_LOCATION_H
3
+
4
+ #include <memory>
5
+ #include <string>
6
+ #include <stack>
7
+ #include <string>
8
+ #include <sstream>
9
+
10
+ /**
11
+ * Provide frontend-wide location tracking like what bison generates
12
+ * but using shared_ptr for filename
13
+ */
14
+
15
+ struct Position {
16
+ std::shared_ptr<std::string> filename;
17
+ int line;
18
+ int column;
19
+
20
+ Position(std::shared_ptr<std::string> filename, int line = 1, int column = 1)
21
+ : filename(filename), line(line), column(column) {}
22
+ Position() = default;
23
+ Position(const Position& other) = default;
24
+ Position& operator=(const Position& other) = default;
25
+
26
+ void advance() { ++column; }
27
+ void columns(int count = 1) {
28
+ column += count;
29
+ }
30
+
31
+ void lines(int count = 1) {
32
+ line += count;
33
+ column = 1;
34
+ }
35
+ std::string to_string() const {
36
+ std::ostringstream oss;
37
+ if (filename && !filename->empty()) {
38
+ oss << *filename << ":";
39
+ }
40
+ oss << line << ":" << column;
41
+ return oss.str();
42
+ }
43
+ };
44
+
45
+ struct Location {
46
+ Position begin;
47
+ Position end;
48
+
49
+ Location() = default;
50
+ Location(const Position& b, const Position& e)
51
+ : begin(b), end(e) {}
52
+ Location(const Location& other) = default;
53
+ Location& operator=(const Location& other) = default;
54
+
55
+ void step() { begin = end; }
56
+
57
+ void columns(int count = 1) {
58
+ end.columns(count);
59
+ }
60
+
61
+ void lines(int count = 1) {
62
+ end.lines(count);
63
+ }
64
+ std::string to_string() const {
65
+ std::ostringstream oss;
66
+ bool same_file = (!begin.filename && !end.filename) ||
67
+ (begin.filename && end.filename &&
68
+ *begin.filename == *end.filename);
69
+
70
+ if (same_file) {
71
+ if (begin.filename && !begin.filename->empty())
72
+ oss << *begin.filename << ":";
73
+
74
+ if (begin.line == end.line) {
75
+ if (begin.column == end.column) {
76
+ oss << begin.line << ":" << begin.column;
77
+ } else {
78
+ oss << begin.line << ":" << begin.column
79
+ << "-" << end.column;
80
+ }
81
+ } else {
82
+ oss << begin.line << ":" << begin.column
83
+ << "-" << end.line << ":" << end.column;
84
+ }
85
+ } else {
86
+ oss << begin.to_string() << "-" << end.to_string();
87
+ }
88
+
89
+ return oss.str();
90
+ }
91
+
92
+ YOSYS_NAMESPACE_PREFIX LogSourceLocation to_loc() const {
93
+ return YOSYS_NAMESPACE_PREFIX LogSourceLocation(begin.filename ? *(begin.filename) : "UNKNOWN", begin.line, begin.column, end.line, end.column);
94
+ }
95
+ };
96
+
97
+ static inline std::ostream& operator<<(std::ostream& os, const Location& loc) {
98
+ return os << loc.to_string();
99
+ }
100
+
101
+ #endif
chips/yosys/frontends/verilog/verilog_parser.y ADDED
The diff for this file is too large to render. See raw diff
 
chips/yosys/guidelines/GettingStarted ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Getting Started
2
+ ===============
3
+
4
+
5
+ Outline of a Yosys command
6
+ --------------------------
7
+
8
+ Here is the C++ code for a "hello_world" Yosys command (hello.cc):
9
+
10
+ #include "kernel/yosys.h"
11
+
12
+ USING_YOSYS_NAMESPACE
13
+ PRIVATE_NAMESPACE_BEGIN
14
+
15
+ struct HelloWorldPass : public Pass {
16
+ HelloWorldPass() : Pass("hello_world") { }
17
+ void execute(vector<string>, Design*) override {
18
+ log("Hello World!\n");
19
+ }
20
+ } HelloWorldPass;
21
+
22
+ PRIVATE_NAMESPACE_END
23
+
24
+ This can be built into a Yosys module using the following command:
25
+
26
+ yosys-config --exec --cxx --cxxflags --ldflags -o hello.so -shared hello.cc --ldlibs
27
+
28
+ Or short:
29
+
30
+ yosys-config --build hello.so hello.cc
31
+
32
+ And then executed using the following command:
33
+
34
+ yosys -m hello.so -p hello_world
35
+
36
+
37
+ Yosys Data Structures
38
+ ---------------------
39
+
40
+ 1. Container classes based on hashing
41
+
42
+ Yosys heavily relies on custom container data structures such as dict or pool
43
+ defined in kernel/hashlib.h.
44
+ dict<K, T> is essentially a replacement for std::unordered_map<K, T>
45
+ and pool<T> is a replacement for std::unordered_set<T>. Please refer to
46
+ docs/source/yosys_internals/hashing.rst for more information on those.
47
+
48
+ Otherwise, Yosys makes use of the following:
49
+
50
+ 2. Standard STL data types
51
+
52
+ In Yosys we use std::vector<T> and std::string whenever applicable. When
53
+ dict<K, T> and pool<T> are not suitable then std::map<K, T> and std::set<T>
54
+ are used instead.
55
+
56
+ The types std::vector<T> and std::string are also available as vector<T>
57
+ and string in the Yosys namespace.
58
+
59
+ 3. RTLIL objects
60
+
61
+ The current design (essentially a collection of modules, each defined by a
62
+ netlist) is stored in memory using RTLIL object (declared in kernel/rtlil.h,
63
+ automatically included by kernel/yosys.h). You should glance over at least
64
+ the declarations for the following types in kernel/rtlil.h:
65
+
66
+ RTLIL::IdString
67
+ This is a handle for an identifier (e.g. cell or wire name).
68
+ It feels a lot like a std::string, but is only a single int
69
+ in size. (The actual string is stored in a global lookup
70
+ table.)
71
+
72
+ RTLIL::SigBit
73
+ A single signal bit. I.e. either a constant state (0, 1,
74
+ x, z) or a single bit from a wire.
75
+
76
+ RTLIL::SigSpec
77
+ Essentially a vector of SigBits.
78
+
79
+ RTLIL::Wire
80
+ RTLIL::Cell
81
+ The building blocks of the netlist in a module.
82
+
83
+ RTLIL::Module
84
+ RTLIL::Design
85
+ The module is a container with connected cells and wires
86
+ in it. The design is a container with modules in it.
87
+
88
+ All these types are also available without the RTLIL:: prefix in the Yosys
89
+ namespace.
90
+
91
+ 4. SigMap and other Helper Classes
92
+
93
+ There are a couple of additional helper classes that are in wide use
94
+ in Yosys. Most importantly there is SigMap (declared in kernel/sigtools.h).
95
+
96
+ When a design has many wires in it that are connected to each other, then a
97
+ single signal bit can have multiple valid names. The SigMap object can be used
98
+ to map SigSpecs or SigBits to unique SigSpecs and SigBits that consistently
99
+ only use one wire from such a group of connected wires. For example:
100
+
101
+ SigBit a = module->addWire(NEW_ID);
102
+ SigBit b = module->addWire(NEW_ID);
103
+ module->connect(a, b);
104
+
105
+ log("%d\n", a == b); // will print 0
106
+
107
+ SigMap sigmap(module);
108
+ log("%d\n", sigmap(a) == sigmap(b)); // will print 1
109
+
110
+
111
+ Using the RTLIL Netlist Format
112
+ ------------------------------
113
+
114
+ In the RTLIL netlist format the cell ports contain SigSpecs that point to the
115
+ Wires. There are no references in the other direction. This has two direct
116
+ consequences:
117
+
118
+ (1) It is very easy to go from cells to wires but hard to go in the other way.
119
+
120
+ (2) There is no danger in removing cells from the netlists, but removing wires
121
+ can break the netlist format when there are still references to the wire
122
+ somewhere in the netlist.
123
+
124
+ The solution to (1) is easy: Create custom indexes that allow you to make fast
125
+ lookups for the wire-to-cell direction. You can either use existing generic
126
+ index structures to do that (such as the ModIndex class) or write your own
127
+ index. For many application it is simplest to construct a custom index. For
128
+ example:
129
+
130
+ SigMap sigmap(module);
131
+ dict<SigBit, Cell*> sigbit_to_driver_index;
132
+
133
+ for (auto cell : module->cells())
134
+ for (auto &conn : cell->connections())
135
+ if (cell->output(conn.first))
136
+ for (auto bit : sigmap(conn.second))
137
+ sigbit_to_driver_index[bit] = cell;
138
+
139
+ Regarding (2): There is a general theme in Yosys that you don't remove wires
140
+ from the design. You can rename them, unconnect them, but you do not actually remove
141
+ the Wire object from the module. Instead you let the "clean" command take care
142
+ of the dangling wires. On the other hand it is safe to remove cells (as long as
143
+ you make sure this does not invalidate a custom index you are using in your code).
144
+
145
+
146
+ Example Code
147
+ ------------
148
+
149
+ The following yosys commands are a good starting point if you are looking for examples
150
+ of how to use the Yosys API:
151
+
152
+ docs/source/code_examples/stubnets/stubnets.cc
153
+ docs/resources/PRESENTATION_Prog/my_cmd.cc
154
+
155
+
156
+ Script Passes
157
+ -------------
158
+
159
+ The ScriptPass base class can be used to implement passes that just call other passes,
160
+ like a script. Examples for such passes are:
161
+
162
+ techlibs/common/prep.cc
163
+ techlibs/common/synth.cc
164
+
165
+ In some cases it is easier to implement such a pass as regular pass, for example when
166
+ ScriptPass doesn't provide the type of flow control desired. (But many of the
167
+ script passes in Yosys that don't use ScriptPass simply predate the ScriptPass base
168
+ class.) Examples for such passes are:
169
+
170
+ passes/opt/opt.cc
171
+ passes/proc/proc.cc
172
+
173
+ Whether they use the ScriptPass base-class or not, a pass should always either
174
+ call other passes without doing any non-trivial work itself, or should implement
175
+ a non-trivial algorithm but not call any other passes. The reason for this is that
176
+ this helps containing complexity in individual passes and simplifies debugging the
177
+ entire system.
178
+
179
+ Exceptions to this rule should be rare and limited to cases where calling other
180
+ passes is optional and only happens when requested by the user (such as for
181
+ example `techmap -autoproc`), or where it is about commands that are "top-level
182
+ commands" in their own right, not components to be used in regular synthesis
183
+ flows (such as the `bugpoint` command).
184
+
185
+ A pass that would "naturally" call other passes and also do some work itself
186
+ should be re-written in one of two ways:
187
+
188
+ 1) It could be re-written as script pass with the parts that are not calls
189
+ to other passes factored out into individual new passes. Usually in those
190
+ cases the new sub passes share the same prefix as the top-level script pass.
191
+
192
+ 2) It could be re-written so that it already expects the design in a certain
193
+ state, expecting the calling script to set up this state before calling the
194
+ pass in questions.
195
+
196
+ Many back-ends are examples for the 2nd approach. For example, `write_aiger`
197
+ does not convert the design into AIG representation, but expects the design
198
+ to be already in this form, and prints an `Unsupported cell type` error
199
+ message otherwise.
200
+
201
+
202
+ Notes on the existing codebase
203
+ ------------------------------
204
+
205
+ For historical reasons not all parts of Yosys adhere to the current coding
206
+ style. When adding code to existing parts of the system, adhere to this guide
207
+ for the new code instead of trying to mimic the style of the surrounding code.
chips/yosys/kernel/CMakeLists.txt ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ yosys_version_file(version.cc.in version.cc)
2
+ configure_file(yosys_config.h.in yosys_config.h @ONLY)
3
+
4
+ set(cellhelp_sources)
5
+ foreach (library simlib simcells)
6
+ add_custom_command(
7
+ DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/cellhelp.py ${YOSYS_CMAKE_SOURCE_DIR}/techlibs/common/${library}.v
8
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${library}_help.inc
9
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/cellhelp.py
10
+ ${YOSYS_CMAKE_SOURCE_DIR}/techlibs/common/${library}.v
11
+ > ${CMAKE_CURRENT_BINARY_DIR}/${library}_help.inc
12
+ VERBATIM
13
+ )
14
+ list(APPEND cellhelp_sources ${CMAKE_CURRENT_BINARY_DIR}/${library}_help.inc)
15
+ endforeach()
16
+
17
+ yosys_core(kernel
18
+ bitpattern.cc
19
+ bitpattern.h
20
+ calc.cc
21
+ cellaigs.cc
22
+ cellaigs.h
23
+ celledges.cc
24
+ celledges.h
25
+ celltypes.h
26
+ compute_graph.h
27
+ compressor_tree.cc
28
+ compressor_tree.h
29
+ consteval.h
30
+ constids.inc
31
+ cost.cc
32
+ cost.h
33
+ drivertools.cc
34
+ drivertools.h
35
+ ff.cc
36
+ ff.h
37
+ ffinit.h
38
+ ffmerge.cc
39
+ ffmerge.h
40
+ fmt.cc
41
+ fmt.h
42
+ functional.cc
43
+ functional.h
44
+ gzip.cc
45
+ gzip.h
46
+ hashcons.h
47
+ hashcons_impl.h
48
+ hashlib.h
49
+ io.cc
50
+ io.h
51
+ json.cc
52
+ json.h
53
+ log.cc
54
+ log.h
55
+ $<${YOSYS_ENABLE_VERIFIC}:log_compat.cc>
56
+ log_help.cc
57
+ log_help.h
58
+ macc.h
59
+ mem.cc
60
+ mem.h
61
+ modtools.h
62
+ newcelltypes.cc
63
+ newcelltypes.h
64
+ pattern.h
65
+ qcsat.cc
66
+ qcsat.h
67
+ register.cc
68
+ register.h
69
+ ${cellhelp_sources}
70
+ rtlil_bufnorm.cc
71
+ rtlil.cc
72
+ rtlil.h
73
+ rtlil_twine_compat.h
74
+ rtlil_twine_compat_impl.h
75
+ satgen.cc
76
+ satgen.h
77
+ scopeinfo.cc
78
+ scopeinfo.h
79
+ sexpr.cc
80
+ sexpr.h
81
+ sigtools.h
82
+ tclapi.cc
83
+ threading.cc
84
+ threading.h
85
+ timinginfo.h
86
+ topo_scc.h
87
+ twine.cc
88
+ twine.h
89
+ unused_bits.h
90
+ utils.h
91
+ version.cc
92
+ yosys.cc
93
+ yosys_common.h
94
+ yosys_config.h
95
+ yosys.h
96
+ yw.cc
97
+ yw.h
98
+ INCLUDE_DIRS
99
+ ${pybind11_INCLUDE_DIR}
100
+ LIBRARIES
101
+ cxxopts
102
+ $<${YOSYS_ENABLE_PLUGINS}:${Dlfcn_LIBRARIES}>
103
+ $<${YOSYS_ENABLE_ZLIB}:PkgConfig::zlib>
104
+ $<${YOSYS_ENABLE_READLINE}:PkgConfig::readline>
105
+ $<${YOSYS_ENABLE_EDITLINE}:PkgConfig::editline>
106
+ $<${YOSYS_ENABLE_TCL}:PkgConfig::tcl>
107
+ $<${YOSYS_ENABLE_PYTHON}:Python3::Module>
108
+ REQUIRES
109
+ bigint
110
+ ezsat
111
+ json11
112
+ sha1
113
+ PROVIDES
114
+ help
115
+ echo
116
+ license
117
+ tcl
118
+ shell
119
+ history
120
+ script
121
+ DATA_DIR
122
+ include/kernel
123
+ DATA_FILES
124
+ bitpattern.h
125
+ cellaigs.h
126
+ celledges.h
127
+ celltypes.h
128
+ newcelltypes.h
129
+ consteval.h
130
+ constids.inc
131
+ cost.h
132
+ drivertools.h
133
+ ff.h
134
+ ffinit.h
135
+ ffmerge.h
136
+ fmt.h
137
+ gzip.h
138
+ hashcons.h
139
+ hashcons_impl.h
140
+ hashlib.h
141
+ io.h
142
+ json.h
143
+ log.h
144
+ macc.h
145
+ modtools.h
146
+ mem.h
147
+ qcsat.h
148
+ register.h
149
+ rtlil.h
150
+ rtlil_twine_compat.h
151
+ rtlil_twine_compat_impl.h
152
+ satgen.h
153
+ scopeinfo.h
154
+ sexpr.h
155
+ sigtools.h
156
+ threading.h
157
+ timinginfo.h
158
+ twine.h
159
+ unused_bits.h
160
+ utils.h
161
+ yosys.h
162
+ yosys_common.h
163
+ yw.h
164
+ DATA_EXPLICIT
165
+ yosys_config.h ${CMAKE_CURRENT_BINARY_DIR}/yosys_config.h
166
+ ESSENTIAL
167
+ )
168
+
169
+ set(yosys_cc_definitions
170
+ "$<$<BOOL:${YOSYS_ABC_EXECUTABLE}>:ABCEXTERNAL=\"${YOSYS_ABC_EXECUTABLE}\">"
171
+ $<$<BOOL:${MINGW}>:YOSYS_WIN32_UNIX_DIR>
172
+ )
173
+ set_source_files_properties(yosys.cc PROPERTIES
174
+ COMPILE_DEFINITIONS "${yosys_cc_definitions}"
175
+ )
176
+
177
+ yosys_core(fstdata
178
+ fstdata.cc
179
+ fstdata.h
180
+ REQUIRES
181
+ fst
182
+ DATA_DIR
183
+ include/kernel
184
+ DATA_FILES
185
+ fstdata.h
186
+ )
187
+
188
+ if (NOT YOSYS_BUILD_PYTHON_ONLY)
189
+ yosys_core(driver
190
+ driver.cc
191
+ INCLUDE_DIRS
192
+ ${pybind11_INCLUDE_DIR}
193
+ LIBRARIES
194
+ fmt::fmt
195
+ $<${YOSYS_ENABLE_READLINE}:PkgConfig::readline>
196
+ $<${YOSYS_ENABLE_EDITLINE}:PkgConfig::editline>
197
+ $<${YOSYS_ENABLE_TCL}:PkgConfig::tcl>
198
+ $<${YOSYS_ENABLE_PYTHON}:Python3::Python>
199
+ REQUIRES
200
+ essentials
201
+ BOOTSTRAP
202
+ )
203
+ endif()
chips/yosys/kernel/bitpattern.cc ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/bitpattern.h"
21
+
22
+ YOSYS_NAMESPACE_BEGIN
23
+
24
+ BitPatternPool::BitPatternPool(RTLIL::SigSpec sig) : width(GetSize(sig))
25
+ {
26
+ gave_up = width > MAX_WIDTH;
27
+ if (gave_up)
28
+ return;
29
+ universe.assign(width, RTLIL::State::Sa);
30
+ for (int i = 0; i < width; i++)
31
+ if (sig[i].wire == nullptr && sig[i].data <= RTLIL::State::S1)
32
+ universe[i] = sig[i].data;
33
+ rebuild();
34
+ }
35
+
36
+ BitPatternPool::BitPatternPool(int width) : BitPatternPool(RTLIL::SigSpec(RTLIL::State::Sa, width)) {}
37
+
38
+ bool BitPatternPool::covers_nothing(RTLIL::SigSpec sig)
39
+ {
40
+ for (auto bit : sig)
41
+ if (bit.wire == nullptr && (bit.data == RTLIL::State::Sx || bit.data == RTLIL::State::Sz))
42
+ return true;
43
+ return false;
44
+ }
45
+
46
+ int BitPatternPool::budget() { return max_nodes >> (3 * ((MAX_ATTEMPTS - 1 - attempt) / 2)); }
47
+
48
+ int BitPatternPool::bit_index(int level) { return attempt % 2 ? level : width - 1 - level; }
49
+
50
+ int BitPatternPool::make_node(int level, int low, int high)
51
+ {
52
+ if (low == high)
53
+ return low;
54
+ return nodes(std::make_tuple(level, low, high));
55
+ }
56
+
57
+ bool BitPatternPool::reaches(int node, const std::vector<RTLIL::State> &bits, int terminal, pool<int> &misses)
58
+ {
59
+ if (node == int(Terminal::Empty) || node == int(Terminal::Full))
60
+ return node == terminal;
61
+ if (misses.count(node))
62
+ return false;
63
+ auto [level, low, high] = nodes[node];
64
+ RTLIL::State bit = bits[bit_index(level)];
65
+ if (bit != RTLIL::State::S1 && reaches(low, bits, terminal, misses))
66
+ return true;
67
+ if (bit != RTLIL::State::S0 && reaches(high, bits, terminal, misses))
68
+ return true;
69
+ misses.insert(node);
70
+ return false;
71
+ }
72
+
73
+ // node minus cube
74
+ int BitPatternPool::remove_cube(int node, int level, const std::vector<RTLIL::State> &bits, dict<std::pair<int, int>, int> &cache)
75
+ {
76
+ if (node == int(Terminal::Empty))
77
+ return int(Terminal::Empty);
78
+ while (level < width && bits[bit_index(level)] > RTLIL::State::S1)
79
+ level++;
80
+ if (level == width || GetSize(nodes) >= budget())
81
+ return int(Terminal::Empty);
82
+ auto it = cache.find({node, level});
83
+ if (it != cache.end())
84
+ return it->second;
85
+
86
+ auto [node_level, low, high] = nodes[node];
87
+ int result;
88
+ if (node_level < level) {
89
+ low = remove_cube(low, level, bits, cache);
90
+ high = remove_cube(high, level, bits, cache);
91
+ result = make_node(node_level, low, high);
92
+ } else {
93
+ if (node_level > level)
94
+ low = high = node;
95
+ if (bits[bit_index(level)] == RTLIL::State::S0)
96
+ low = remove_cube(low, level + 1, bits, cache);
97
+ else
98
+ high = remove_cube(high, level + 1, bits, cache);
99
+ result = make_node(level, low, high);
100
+ }
101
+ cache[{node, level}] = result;
102
+ return result;
103
+ }
104
+
105
+ // false if over budget
106
+ bool BitPatternPool::remove(const std::vector<RTLIL::State> &bits)
107
+ {
108
+ log_assert(GetSize(bits) == width);
109
+ dict<std::pair<int, int>, int> cache;
110
+ int new_root = remove_cube(root, 0, bits, cache);
111
+ if (GetSize(nodes) >= budget())
112
+ return false;
113
+ root = new_root;
114
+ return true;
115
+ }
116
+
117
+ bool BitPatternPool::rebuild()
118
+ {
119
+ nodes.clear();
120
+ nodes(std::make_tuple(width, int(Terminal::Empty), int(Terminal::Empty)));
121
+ nodes(std::make_tuple(width, int(Terminal::Full), int(Terminal::Full)));
122
+ root = width > 0 ? int(Terminal::Full) : int(Terminal::Empty);
123
+ for (int level = width - 1; level >= 0; level--) {
124
+ RTLIL::State bit = universe[bit_index(level)];
125
+ if (bit == RTLIL::State::S1)
126
+ root = make_node(level, int(Terminal::Empty), root);
127
+ else if (bit == RTLIL::State::S0)
128
+ root = make_node(level, root, int(Terminal::Empty));
129
+ }
130
+ for (auto &bits : taken)
131
+ if (!remove(bits))
132
+ return false;
133
+ return true;
134
+ }
135
+
136
+ bool BitPatternPool::has_any(RTLIL::SigSpec sig)
137
+ {
138
+ if (covers_nothing(sig))
139
+ return false;
140
+ if (gave_up)
141
+ return true;
142
+ log_assert(GetSize(sig) == width);
143
+ pool<int> misses;
144
+ return reaches(root, sig.as_const().to_bits(), int(Terminal::Full), misses);
145
+ }
146
+
147
+ bool BitPatternPool::has_all(RTLIL::SigSpec sig)
148
+ {
149
+ if (covers_nothing(sig))
150
+ return true;
151
+ if (gave_up)
152
+ return false;
153
+ log_assert(GetSize(sig) == width);
154
+ pool<int> misses;
155
+ return !reaches(root, sig.as_const().to_bits(), int(Terminal::Empty), misses);
156
+ }
157
+
158
+ bool BitPatternPool::take(RTLIL::SigSpec sig)
159
+ {
160
+ if (covers_nothing(sig))
161
+ return false;
162
+ if (gave_up)
163
+ return true;
164
+ if (root == int(Terminal::Empty))
165
+ return false;
166
+ std::vector<RTLIL::State> bits = sig.as_const().to_bits();
167
+ int old_root = root;
168
+ bool removed = remove(bits);
169
+ while (!removed && attempt + 1 < MAX_ATTEMPTS) {
170
+ attempt++;
171
+ if (rebuild()) {
172
+ old_root = root;
173
+ removed = remove(bits);
174
+ }
175
+ }
176
+ if (!removed) {
177
+ gave_up = true;
178
+ nodes = {};
179
+ taken = {};
180
+ return true;
181
+ }
182
+ // hash-consed, same root means no overlap
183
+ if (root == old_root)
184
+ return false;
185
+ if (attempt + 1 < MAX_ATTEMPTS)
186
+ taken.push_back(bits);
187
+ return true;
188
+ }
189
+
190
+ bool BitPatternPool::take_all()
191
+ {
192
+ if (empty())
193
+ return false;
194
+ root = int(Terminal::Empty);
195
+ gave_up = false;
196
+ return true;
197
+ }
198
+
199
+ bool BitPatternPool::empty() { return !gave_up && root == int(Terminal::Empty); }
200
+
201
+ YOSYS_NAMESPACE_END
chips/yosys/kernel/bitpattern.h ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef BITPATTERN_H
21
+ #define BITPATTERN_H
22
+
23
+ #include "kernel/log.h"
24
+ #include "kernel/rtlil.h"
25
+
26
+ YOSYS_NAMESPACE_BEGIN
27
+
28
+ /**
29
+ * This file implements BitPatternPool for efficiently storing and querying
30
+ * sets of fixed-width 2-valued logic constants.
31
+ * A pattern (cube) can have don't cares on one or more bit positions (State::Sa).
32
+ *
33
+ * The pool is a reduced ordered BDD, see https://github.com/YosysHQ/yosys/issues/6359.
34
+ * Past max_nodes it gives up and answers conservatively.
35
+ *
36
+ * BitPatternPool does not permit adding new patterns, only removing.
37
+ * Its intended use case is in analysing cases in case/match constructs in HDL.
38
+ */
39
+ struct BitPatternPool
40
+ {
41
+ enum class Terminal : int {
42
+ Empty = 0,
43
+ Full = 1
44
+ };
45
+
46
+ // bounds recursion depth
47
+ static constexpr int MAX_WIDTH = 4096;
48
+ // MSB then LSB first per budget, budgets grow 8x
49
+ static constexpr int MAX_ATTEMPTS = 8;
50
+
51
+ int width;
52
+ int max_nodes = 1 << 17;
53
+ bool gave_up = false;
54
+
55
+ BitPatternPool(RTLIL::SigSpec sig);
56
+
57
+ /**
58
+ * Constructs a pool of all possible patterns (all don't-care bits)
59
+ */
60
+ BitPatternPool(int width);
61
+
62
+ /**
63
+ * A literal x/z bit can never match a 2-valued selector, so a pattern containing
64
+ * one covers nothing.
65
+ */
66
+ static bool covers_nothing(RTLIL::SigSpec sig);
67
+
68
+ /**
69
+ * Does cube sig overlap the pool?
70
+ * For example:
71
+ * pool({aaa}).has_any(01a) == true
72
+ * pool({01a}).has_any(01a) == true
73
+ * pool({011}).has_any(01a) == true
74
+ * pool({01a}).has_any(011) == true
75
+ * pool({111}).has_any(01a) == false
76
+ */
77
+ bool has_any(RTLIL::SigSpec sig);
78
+
79
+ /**
80
+ * Is cube sig covered by the pool?
81
+ * For example:
82
+ * pool({aaa}).has_all(01a) == true
83
+ * pool({01a}).has_all(01a) == true
84
+ * pool({01a}).has_all(011) == true
85
+ * pool({011}).has_all(01a) == false
86
+ * pool({111}).has_all(01a) == false
87
+ */
88
+ bool has_all(RTLIL::SigSpec sig);
89
+
90
+ /**
91
+ * Remove cube sig from the pool. True if the pool overlapped sig.
92
+ * For example:
93
+ * Taking 011 out of pool({01a}) -> pool({010}), returns true.
94
+ * Taking 011 out of pool({010}) does nothing, returns false.
95
+ */
96
+ bool take(RTLIL::SigSpec sig);
97
+
98
+ /**
99
+ * Remove all patterns. Returns false if already empty.
100
+ */
101
+ bool take_all();
102
+
103
+ bool empty();
104
+ private:
105
+ int budget();
106
+ int bit_index(int level);
107
+ int make_node(int level, int low, int high);
108
+ bool reaches(int node, const std::vector<RTLIL::State> &bits, int terminal, pool<int> &misses);
109
+ int remove_cube(int node, int level, const std::vector<RTLIL::State> &bits, dict<std::pair<int, int>, int> &cache);
110
+ bool remove(const std::vector<RTLIL::State> &bits);
111
+ bool rebuild();
112
+
113
+ int attempt = 0;
114
+
115
+ // (level, low, high)
116
+ idict<std::tuple<int, int, int>> nodes;
117
+ int root = int(Terminal::Empty);
118
+
119
+ std::vector<RTLIL::State> universe;
120
+ std::vector<std::vector<RTLIL::State>> taken;
121
+ };
122
+
123
+ YOSYS_NAMESPACE_END
124
+
125
+ #endif
chips/yosys/kernel/calc.cc ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ // [[CITE]] Power-Modulus Algorithm
21
+ // Schneier, Bruce (1996). Applied Cryptography: Protocols, Algorithms, and Source Code in C,
22
+ // Second Edition (2nd ed.). Wiley. ISBN 978-0-471-11709-4, page 244
23
+
24
+ #include "kernel/yosys.h"
25
+ #include "libs/bigint/BigIntegerLibrary.hh"
26
+
27
+ YOSYS_NAMESPACE_BEGIN
28
+
29
+ static void extend_u0(RTLIL::Const &arg, int width, bool is_signed)
30
+ {
31
+ RTLIL::State padding = RTLIL::State::S0;
32
+
33
+ if (arg.size() > 0 && is_signed)
34
+ padding = arg.back();
35
+
36
+ arg.resize(width, padding);
37
+ }
38
+
39
+ static BigInteger const2big(const RTLIL::Const &val, bool as_signed, int &undef_bit_pos)
40
+ {
41
+ BigUnsigned mag;
42
+
43
+ BigInteger::Sign sign = BigInteger::positive;
44
+ State inv_sign_bit = RTLIL::State::S1;
45
+ auto num_bits = val.size();
46
+
47
+ if (as_signed && num_bits && val[num_bits-1] == RTLIL::State::S1) {
48
+ inv_sign_bit = RTLIL::State::S0;
49
+ sign = BigInteger::negative;
50
+ num_bits--;
51
+ }
52
+
53
+ for (auto i = 0; i < num_bits; i++)
54
+ if (val[i] == RTLIL::State::S0 || val[i] == RTLIL::State::S1)
55
+ mag.setBit(i, val[i] == inv_sign_bit);
56
+ else if (undef_bit_pos < 0)
57
+ undef_bit_pos = i;
58
+
59
+ if (sign == BigInteger::negative)
60
+ mag += 1;
61
+
62
+ return BigInteger(mag, sign);
63
+ }
64
+
65
+ static RTLIL::Const big2const(const BigInteger &val, int result_len, int undef_bit_pos)
66
+ {
67
+ if (undef_bit_pos >= 0)
68
+ return RTLIL::Const(RTLIL::State::Sx, result_len);
69
+
70
+ BigUnsigned mag = val.getMagnitude();
71
+ RTLIL::Const result(0, result_len);
72
+
73
+ if (!mag.isZero())
74
+ {
75
+ if (val.getSign() < 0)
76
+ {
77
+ mag--;
78
+ for (auto i = 0; i < result_len; i++)
79
+ result.set(i, mag.getBit(i) ? RTLIL::State::S0 : RTLIL::State::S1);
80
+ }
81
+ else
82
+ {
83
+ for (auto i = 0; i < result_len; i++)
84
+ result.set(i, mag.getBit(i) ? RTLIL::State::S1 : RTLIL::State::S0);
85
+ }
86
+ }
87
+
88
+ #if 0
89
+ if (undef_bit_pos >= 0)
90
+ for (int i = undef_bit_pos; i < result_len; i++)
91
+ result[i] = RTLIL::State::Sx;
92
+ #endif
93
+
94
+ return result;
95
+ }
96
+
97
+ static RTLIL::State logic_and(RTLIL::State a, RTLIL::State b)
98
+ {
99
+ if (a == RTLIL::State::S0) return RTLIL::State::S0;
100
+ if (b == RTLIL::State::S0) return RTLIL::State::S0;
101
+ if (a != RTLIL::State::S1) return RTLIL::State::Sx;
102
+ if (b != RTLIL::State::S1) return RTLIL::State::Sx;
103
+ return RTLIL::State::S1;
104
+ }
105
+
106
+ static RTLIL::State logic_or(RTLIL::State a, RTLIL::State b)
107
+ {
108
+ if (a == RTLIL::State::S1) return RTLIL::State::S1;
109
+ if (b == RTLIL::State::S1) return RTLIL::State::S1;
110
+ if (a != RTLIL::State::S0) return RTLIL::State::Sx;
111
+ if (b != RTLIL::State::S0) return RTLIL::State::Sx;
112
+ return RTLIL::State::S0;
113
+ }
114
+
115
+ static RTLIL::State logic_xor(RTLIL::State a, RTLIL::State b)
116
+ {
117
+ if (a != RTLIL::State::S0 && a != RTLIL::State::S1) return RTLIL::State::Sx;
118
+ if (b != RTLIL::State::S0 && b != RTLIL::State::S1) return RTLIL::State::Sx;
119
+ return a != b ? RTLIL::State::S1 : RTLIL::State::S0;
120
+ }
121
+
122
+ static RTLIL::State logic_xnor(RTLIL::State a, RTLIL::State b)
123
+ {
124
+ if (a != RTLIL::State::S0 && a != RTLIL::State::S1) return RTLIL::State::Sx;
125
+ if (b != RTLIL::State::S0 && b != RTLIL::State::S1) return RTLIL::State::Sx;
126
+ return a == b ? RTLIL::State::S1 : RTLIL::State::S0;
127
+ }
128
+
129
+ RTLIL::Const RTLIL::const_not(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len)
130
+ {
131
+ if (result_len < 0)
132
+ result_len = GetSize(arg1);
133
+
134
+ RTLIL::Const arg1_ext = arg1;
135
+ extend_u0(arg1_ext, result_len, signed1);
136
+
137
+ RTLIL::Const result(RTLIL::State::Sx, result_len);
138
+ for (auto i = 0; i < result_len; i++) {
139
+ if (i >= GetSize(arg1_ext))
140
+ result.set(i, RTLIL::State::S0);
141
+ else if (arg1_ext[i] == RTLIL::State::S0)
142
+ result.set(i, RTLIL::State::S1);
143
+ else if (arg1_ext[i] == RTLIL::State::S1)
144
+ result.set(i, RTLIL::State::S0);
145
+ }
146
+
147
+ return result;
148
+ }
149
+
150
+ static RTLIL::Const logic_wrapper(RTLIL::State(*logic_func)(RTLIL::State, RTLIL::State),
151
+ RTLIL::Const arg1, RTLIL::Const arg2, bool signed1, bool signed2, int result_len = -1)
152
+ {
153
+ if (result_len < 0)
154
+ result_len = max(GetSize(arg1), GetSize(arg2));
155
+
156
+ extend_u0(arg1, result_len, signed1);
157
+ extend_u0(arg2, result_len, signed2);
158
+
159
+ RTLIL::Const result(RTLIL::State::Sx, result_len);
160
+ for (auto i = 0; i < result_len; i++) {
161
+ RTLIL::State a = i < GetSize(arg1) ? arg1[i] : RTLIL::State::S0;
162
+ RTLIL::State b = i < GetSize(arg2) ? arg2[i] : RTLIL::State::S0;
163
+ result.set(i, logic_func(a, b));
164
+ }
165
+
166
+ return result;
167
+ }
168
+
169
+ RTLIL::Const RTLIL::const_and(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
170
+ {
171
+ return logic_wrapper(logic_and, arg1, arg2, signed1, signed2, result_len);
172
+ }
173
+
174
+ RTLIL::Const RTLIL::const_or(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
175
+ {
176
+ return logic_wrapper(logic_or, arg1, arg2, signed1, signed2, result_len);
177
+ }
178
+
179
+ RTLIL::Const RTLIL::const_xor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
180
+ {
181
+ return logic_wrapper(logic_xor, arg1, arg2, signed1, signed2, result_len);
182
+ }
183
+
184
+ RTLIL::Const RTLIL::const_xnor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
185
+ {
186
+ return logic_wrapper(logic_xnor, arg1, arg2, signed1, signed2, result_len);
187
+ }
188
+
189
+ static RTLIL::Const logic_reduce_wrapper(RTLIL::State initial, RTLIL::State(*logic_func)(RTLIL::State, RTLIL::State), const RTLIL::Const &arg1, int result_len)
190
+ {
191
+ RTLIL::State temp = initial;
192
+
193
+ for (auto i = 0; i < arg1.size(); i++)
194
+ temp = logic_func(temp, arg1[i]);
195
+
196
+ RTLIL::Const result(temp);
197
+ if (GetSize(result) < result_len)
198
+ result.resize(result_len, RTLIL::State::S0);
199
+ return result;
200
+ }
201
+
202
+ RTLIL::Const RTLIL::const_reduce_and(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len)
203
+ {
204
+ return logic_reduce_wrapper(RTLIL::State::S1, logic_and, arg1, result_len);
205
+ }
206
+
207
+ RTLIL::Const RTLIL::const_reduce_or(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len)
208
+ {
209
+ return logic_reduce_wrapper(RTLIL::State::S0, logic_or, arg1, result_len);
210
+ }
211
+
212
+ RTLIL::Const RTLIL::const_reduce_xor(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len)
213
+ {
214
+ return logic_reduce_wrapper(RTLIL::State::S0, logic_xor, arg1, result_len);
215
+ }
216
+
217
+ RTLIL::Const RTLIL::const_reduce_xnor(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len)
218
+ {
219
+ RTLIL::Const buffer = logic_reduce_wrapper(RTLIL::State::S0, logic_xor, arg1, result_len);
220
+ if (!buffer.empty()) {
221
+ if (buffer.front() == RTLIL::State::S0)
222
+ buffer.set(0, RTLIL::State::S1);
223
+ else if (buffer.front() == RTLIL::State::S1)
224
+ buffer.set(0, RTLIL::State::S0);
225
+ }
226
+ return buffer;
227
+ }
228
+
229
+ RTLIL::Const RTLIL::const_reduce_bool(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len)
230
+ {
231
+ return logic_reduce_wrapper(RTLIL::State::S0, logic_or, arg1, result_len);
232
+ }
233
+
234
+ RTLIL::Const RTLIL::const_logic_not(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len)
235
+ {
236
+ int undef_bit_pos_a = -1;
237
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos_a);
238
+ RTLIL::Const result(a.isZero() ? undef_bit_pos_a >= 0 ? RTLIL::State::Sx : RTLIL::State::S1 : RTLIL::State::S0);
239
+ if (GetSize(result) < result_len)
240
+ result.resize(result_len, RTLIL::State::S0);
241
+ return result;
242
+ }
243
+
244
+ RTLIL::Const RTLIL::const_logic_and(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
245
+ {
246
+ int undef_bit_pos_a = -1, undef_bit_pos_b = -1;
247
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos_a);
248
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos_b);
249
+
250
+ RTLIL::State bit_a = a.isZero() ? undef_bit_pos_a >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1;
251
+ RTLIL::State bit_b = b.isZero() ? undef_bit_pos_b >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1;
252
+ RTLIL::Const result(logic_and(bit_a, bit_b));
253
+ if (GetSize(result) < result_len)
254
+ result.resize(result_len, RTLIL::State::S0);
255
+ return result;
256
+ }
257
+
258
+ RTLIL::Const RTLIL::const_logic_or(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
259
+ {
260
+ int undef_bit_pos_a = -1, undef_bit_pos_b = -1;
261
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos_a);
262
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos_b);
263
+
264
+ RTLIL::State bit_a = a.isZero() ? undef_bit_pos_a >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1;
265
+ RTLIL::State bit_b = b.isZero() ? undef_bit_pos_b >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1;
266
+ RTLIL::Const result(logic_or(bit_a, bit_b));
267
+ if (GetSize(result) < result_len)
268
+ result.resize(result_len, RTLIL::State::S0);
269
+ return result;
270
+ }
271
+
272
+ // Shift `arg1` by `arg2` bits.
273
+ // If `direction` is +1, `arg1` is shifted right by `arg2` bits; if `direction` is -1, `arg1` is shifted left by `arg2` bits.
274
+ // If `signed2` is true, `arg2` is interpreted as a signed integer; a negative `arg2` will cause a shift in the opposite direction.
275
+ // Any required bits outside the bounds of `arg1` are padded with `vacant_bits` unless `sign_ext` is true, in which case any bits outside the left
276
+ // bounds are filled with the leftmost bit of `arg1` (arithmetic shift).
277
+ static RTLIL::Const const_shift_worker(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool sign_ext, bool signed2, int direction, int result_len, RTLIL::State vacant_bits = RTLIL::State::S0)
278
+ {
279
+ int undef_bit_pos = -1;
280
+ BigInteger offset = const2big(arg2, signed2, undef_bit_pos) * direction;
281
+
282
+ if (result_len < 0)
283
+ result_len = GetSize(arg1);
284
+
285
+ RTLIL::Const result(RTLIL::State::Sx, result_len);
286
+ if (undef_bit_pos >= 0)
287
+ return result;
288
+
289
+ for (int i = 0; i < result_len; i++) {
290
+ BigInteger pos = BigInteger(i) + offset;
291
+ if (pos < 0)
292
+ result.set(i, vacant_bits);
293
+ else if (pos >= BigInteger(GetSize(arg1)))
294
+ result.set(i, sign_ext && !arg1.empty() ? arg1.back() : vacant_bits);
295
+ else
296
+ result.set(i, arg1[pos.toInt()]);
297
+ }
298
+
299
+ return result;
300
+ }
301
+
302
+ RTLIL::Const RTLIL::const_shl(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len)
303
+ {
304
+ RTLIL::Const arg1_ext = arg1;
305
+ extend_u0(arg1_ext, result_len, signed1);
306
+ return const_shift_worker(arg1_ext, arg2, false, false, -1, result_len);
307
+ }
308
+
309
+ RTLIL::Const RTLIL::const_shr(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len)
310
+ {
311
+ RTLIL::Const arg1_ext = arg1;
312
+ extend_u0(arg1_ext, max(result_len, GetSize(arg1)), signed1);
313
+ return const_shift_worker(arg1_ext, arg2, false, false, +1, result_len);
314
+ }
315
+
316
+ RTLIL::Const RTLIL::const_sshl(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len)
317
+ {
318
+ return const_shift_worker(arg1, arg2, signed1, false, -1, result_len);
319
+ }
320
+
321
+ RTLIL::Const RTLIL::const_sshr(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len)
322
+ {
323
+ return const_shift_worker(arg1, arg2, signed1, false, +1, result_len);
324
+ }
325
+
326
+ RTLIL::Const RTLIL::const_shift(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
327
+ {
328
+ RTLIL::Const arg1_ext = arg1;
329
+ extend_u0(arg1_ext, max(result_len, GetSize(arg1)), signed1);
330
+ return const_shift_worker(arg1_ext, arg2, false, signed2, +1, result_len);
331
+ }
332
+
333
+ RTLIL::Const RTLIL::const_shiftx(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool, bool signed2, int result_len)
334
+ {
335
+ return const_shift_worker(arg1, arg2, false, signed2, +1, result_len, RTLIL::State::Sx);
336
+ }
337
+
338
+ RTLIL::Const RTLIL::const_lt(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
339
+ {
340
+ int undef_bit_pos = -1;
341
+ bool y = const2big(arg1, signed1, undef_bit_pos) < const2big(arg2, signed2, undef_bit_pos);
342
+ RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0);
343
+ if (GetSize(result) < result_len)
344
+ result.resize(result_len, RTLIL::State::S0);
345
+ return result;
346
+ }
347
+
348
+ RTLIL::Const RTLIL::const_le(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
349
+ {
350
+ int undef_bit_pos = -1;
351
+ bool y = const2big(arg1, signed1, undef_bit_pos) <= const2big(arg2, signed2, undef_bit_pos);
352
+ RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0);
353
+ if (GetSize(result) < result_len)
354
+ result.resize(result_len, RTLIL::State::S0);
355
+ return result;
356
+ }
357
+
358
+ RTLIL::Const RTLIL::const_eq(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
359
+ {
360
+ RTLIL::Const arg1_ext = arg1;
361
+ RTLIL::Const arg2_ext = arg2;
362
+ RTLIL::Const result(RTLIL::State::S0, result_len);
363
+
364
+ int width = max(GetSize(arg1_ext), GetSize(arg2_ext));
365
+ extend_u0(arg1_ext, width, signed1 && signed2);
366
+ extend_u0(arg2_ext, width, signed1 && signed2);
367
+
368
+ RTLIL::State matched_status = RTLIL::State::S1;
369
+ for (auto i = 0; i < arg1_ext.size(); i++) {
370
+ if (arg1_ext.at(i) == RTLIL::State::S0 && arg2_ext.at(i) == RTLIL::State::S1)
371
+ return result;
372
+ if (arg1_ext.at(i) == RTLIL::State::S1 && arg2_ext.at(i) == RTLIL::State::S0)
373
+ return result;
374
+ if (arg1_ext.at(i) > RTLIL::State::S1 || arg2_ext.at(i) > RTLIL::State::S1)
375
+ matched_status = RTLIL::State::Sx;
376
+ }
377
+
378
+ result.set(0, matched_status);
379
+ return result;
380
+ }
381
+
382
+ RTLIL::Const RTLIL::const_ne(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
383
+ {
384
+ RTLIL::Const result = RTLIL::const_eq(arg1, arg2, signed1, signed2, result_len);
385
+ if (result.front() == RTLIL::State::S0)
386
+ result.set(0, RTLIL::State::S1);
387
+ else if (result.front() == RTLIL::State::S1)
388
+ result.set(0, RTLIL::State::S0);
389
+ return result;
390
+ }
391
+
392
+ RTLIL::Const RTLIL::const_eqx(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
393
+ {
394
+ RTLIL::Const arg1_ext = arg1;
395
+ RTLIL::Const arg2_ext = arg2;
396
+ RTLIL::Const result(RTLIL::State::S0, result_len);
397
+
398
+ int width = max(GetSize(arg1_ext), GetSize(arg2_ext));
399
+ extend_u0(arg1_ext, width, signed1 && signed2);
400
+ extend_u0(arg2_ext, width, signed1 && signed2);
401
+
402
+ for (auto i = 0; i < arg1_ext.size(); i++) {
403
+ if (arg1_ext.at(i) != arg2_ext.at(i))
404
+ return result;
405
+ }
406
+
407
+ result.set(0, RTLIL::State::S1);
408
+ return result;
409
+ }
410
+
411
+ RTLIL::Const RTLIL::const_nex(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
412
+ {
413
+ RTLIL::Const result = RTLIL::const_eqx(arg1, arg2, signed1, signed2, result_len);
414
+ if (result.front() == RTLIL::State::S0)
415
+ result.set(0, RTLIL::State::S1);
416
+ else if (result.front() == RTLIL::State::S1)
417
+ result.set(0, RTLIL::State::S0);
418
+ return result;
419
+ }
420
+
421
+ RTLIL::Const RTLIL::const_ge(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
422
+ {
423
+ int undef_bit_pos = -1;
424
+ bool y = const2big(arg1, signed1, undef_bit_pos) >= const2big(arg2, signed2, undef_bit_pos);
425
+ RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0);
426
+ if (GetSize(result) < result_len)
427
+ result.resize(result_len, RTLIL::State::S0);
428
+ return result;
429
+ }
430
+
431
+ RTLIL::Const RTLIL::const_gt(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
432
+ {
433
+ int undef_bit_pos = -1;
434
+ bool y = const2big(arg1, signed1, undef_bit_pos) > const2big(arg2, signed2, undef_bit_pos);
435
+ RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0);
436
+ if (GetSize(result) < result_len)
437
+ result.resize(result_len, RTLIL::State::S0);
438
+ return result;
439
+ }
440
+
441
+ RTLIL::Const RTLIL::const_add(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
442
+ {
443
+ int undef_bit_pos = -1;
444
+ BigInteger y = const2big(arg1, signed1, undef_bit_pos) + const2big(arg2, signed2, undef_bit_pos);
445
+ return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), undef_bit_pos);
446
+ }
447
+
448
+ RTLIL::Const RTLIL::const_sub(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
449
+ {
450
+ int undef_bit_pos = -1;
451
+ BigInteger y = const2big(arg1, signed1, undef_bit_pos) - const2big(arg2, signed2, undef_bit_pos);
452
+ return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), undef_bit_pos);
453
+ }
454
+
455
+ RTLIL::Const RTLIL::const_mul(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
456
+ {
457
+ int undef_bit_pos = -1;
458
+ BigInteger y = const2big(arg1, signed1, undef_bit_pos) * const2big(arg2, signed2, undef_bit_pos);
459
+ return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0));
460
+ }
461
+
462
+ // truncating division
463
+ RTLIL::Const RTLIL::const_div(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
464
+ {
465
+ int undef_bit_pos = -1;
466
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos);
467
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos);
468
+ if (b.isZero())
469
+ return RTLIL::Const(RTLIL::State::Sx, result_len);
470
+ bool result_neg = (a.getSign() == BigInteger::negative) != (b.getSign() == BigInteger::negative);
471
+ a = a.getSign() == BigInteger::negative ? -a : a;
472
+ b = b.getSign() == BigInteger::negative ? -b : b;
473
+ return big2const(result_neg ? -(a / b) : (a / b), result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0));
474
+ }
475
+
476
+ // truncating modulo
477
+ RTLIL::Const RTLIL::const_mod(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
478
+ {
479
+ int undef_bit_pos = -1;
480
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos);
481
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos);
482
+ if (b.isZero())
483
+ return RTLIL::Const(RTLIL::State::Sx, result_len);
484
+ bool result_neg = a.getSign() == BigInteger::negative;
485
+ a = a.getSign() == BigInteger::negative ? -a : a;
486
+ b = b.getSign() == BigInteger::negative ? -b : b;
487
+ return big2const(result_neg ? -(a % b) : (a % b), result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0));
488
+ }
489
+
490
+ RTLIL::Const RTLIL::const_divfloor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
491
+ {
492
+ int undef_bit_pos = -1;
493
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos);
494
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos);
495
+ if (b.isZero())
496
+ return RTLIL::Const(RTLIL::State::Sx, result_len);
497
+
498
+ bool result_pos = (a.getSign() == BigInteger::negative) == (b.getSign() == BigInteger::negative);
499
+ a = a.getSign() == BigInteger::negative ? -a : a;
500
+ b = b.getSign() == BigInteger::negative ? -b : b;
501
+ BigInteger result;
502
+
503
+ if (result_pos || a == 0) {
504
+ result = a / b;
505
+ } else {
506
+ // bigint division with negative numbers is wonky, make sure we only negate at the very end
507
+ result = -((a + b - 1) / b);
508
+ }
509
+ return big2const(result, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0));
510
+ }
511
+
512
+ RTLIL::Const RTLIL::const_modfloor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
513
+ {
514
+ int undef_bit_pos = -1;
515
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos);
516
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos);
517
+ if (b.isZero())
518
+ return RTLIL::Const(RTLIL::State::Sx, result_len);
519
+
520
+ BigInteger::Sign a_sign = a.getSign();
521
+ BigInteger::Sign b_sign = b.getSign();
522
+ a = a_sign == BigInteger::negative ? -a : a;
523
+ b = b_sign == BigInteger::negative ? -b : b;
524
+ BigInteger truncated = a_sign == BigInteger::negative ? -(a % b) : (a % b);
525
+ BigInteger modulo;
526
+
527
+ if (truncated == 0 || (a_sign == b_sign)) {
528
+ modulo = truncated;
529
+ } else {
530
+ modulo = b_sign == BigInteger::negative ? truncated - b : truncated + b;
531
+ }
532
+ return big2const(modulo, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0));
533
+ }
534
+
535
+ RTLIL::Const RTLIL::const_pow(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len)
536
+ {
537
+ int undef_bit_pos = -1;
538
+
539
+ BigInteger a = const2big(arg1, signed1, undef_bit_pos);
540
+ BigInteger b = const2big(arg2, signed2, undef_bit_pos);
541
+ BigInteger y = 1;
542
+
543
+ if (a == 0 && b < 0)
544
+ return RTLIL::Const(RTLIL::State::Sx, result_len);
545
+
546
+ if (a == 0 && b > 0)
547
+ return RTLIL::Const(RTLIL::State::S0, result_len);
548
+
549
+ if (b < 0)
550
+ {
551
+ if (a < -1 || a > 1)
552
+ y = 0;
553
+ if (a == -1)
554
+ y = (-b % 2) == 0 ? 1 : -1;
555
+ }
556
+
557
+ if (b > 0)
558
+ {
559
+ // Power-modulo with 2^result_len as modulus
560
+ BigInteger modulus = 1;
561
+ int modulus_bits = (result_len >= 0 ? result_len : 1024);
562
+ for (int i = 0; i < modulus_bits; i++)
563
+ modulus *= 2;
564
+
565
+ bool flip_result_sign = false;
566
+ if (a < 0) {
567
+ a *= -1;
568
+ if (b % 2 == 1)
569
+ flip_result_sign = true;
570
+ }
571
+
572
+ while (b > 0) {
573
+ if (b % 2 == 1)
574
+ y = (y * a) % modulus;
575
+ b = b / 2;
576
+ a = (a * a) % modulus;
577
+ }
578
+
579
+ if (flip_result_sign)
580
+ y *= -1;
581
+ }
582
+
583
+ return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0));
584
+ }
585
+
586
+ RTLIL::Const RTLIL::const_pos(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len)
587
+ {
588
+ RTLIL::Const arg1_ext = arg1;
589
+ extend_u0(arg1_ext, result_len, signed1);
590
+
591
+ return arg1_ext;
592
+ }
593
+
594
+ RTLIL::Const RTLIL::const_buf(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len)
595
+ {
596
+ RTLIL::Const arg1_ext = arg1;
597
+ extend_u0(arg1_ext, result_len, signed1);
598
+
599
+ return arg1_ext;
600
+ }
601
+
602
+ RTLIL::Const RTLIL::const_neg(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len)
603
+ {
604
+ RTLIL::Const arg1_ext = arg1;
605
+ RTLIL::Const zero(RTLIL::State::S0, 1);
606
+
607
+ return RTLIL::const_sub(zero, arg1_ext, true, signed1, result_len);
608
+ }
609
+
610
+ RTLIL::Const RTLIL::const_mux(const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3)
611
+ {
612
+ log_assert(arg2.size() == arg1.size());
613
+ if (arg3[0] == State::S0)
614
+ return arg1;
615
+ else if (arg3[0] == State::S1)
616
+ return arg2;
617
+
618
+ RTLIL::Const ret = arg1;
619
+ for (auto i = 0; i < ret.size(); i++)
620
+ if (ret[i] != arg2[i])
621
+ ret.set(i, State::Sx);
622
+ return ret;
623
+ }
624
+
625
+ RTLIL::Const RTLIL::const_pmux(const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3)
626
+ {
627
+ if (arg3.is_fully_zero())
628
+ return arg1;
629
+
630
+ if (!arg3.is_onehot())
631
+ return RTLIL::Const(State::Sx, arg1.size());
632
+
633
+ for (auto i = 0; i < arg3.size(); i++)
634
+ if (arg3[i] == State::S1)
635
+ return RTLIL::Const(std::vector<RTLIL::State>(arg2.begin() + i*arg1.size(), arg2.begin() + (i+1)*arg1.size()));
636
+
637
+ log_abort(); // unreachable
638
+ }
639
+
640
+ RTLIL::Const RTLIL::const_bmux(const RTLIL::Const &arg1, const RTLIL::Const &arg2)
641
+ {
642
+ std::vector<State> t = arg1.to_bits();
643
+
644
+ for (int i = GetSize(arg2)-1; i >= 0; i--)
645
+ {
646
+ RTLIL::State sel = arg2.at(i);
647
+ std::vector<RTLIL::State> new_t;
648
+ if (sel == State::S0)
649
+ new_t = std::vector<RTLIL::State>(t.begin(), t.begin() + GetSize(t)/2);
650
+ else if (sel == State::S1)
651
+ new_t = std::vector<RTLIL::State>(t.begin() + GetSize(t)/2, t.end());
652
+ else
653
+ for (int j = 0; j < GetSize(t)/2; j++)
654
+ new_t.push_back(t[j] == t[j + GetSize(t)/2] ? t[j] : RTLIL::Sx);
655
+ t.swap(new_t);
656
+ }
657
+
658
+ return t;
659
+ }
660
+
661
+ RTLIL::Const RTLIL::const_demux(const RTLIL::Const &arg1, const RTLIL::Const &arg2)
662
+ {
663
+ int width = GetSize(arg1);
664
+ int s_width = GetSize(arg2);
665
+ std::vector<RTLIL::State> res;
666
+ for (int i = 0; i < (1 << s_width); i++)
667
+ {
668
+ bool ne = false;
669
+ bool x = false;
670
+ for (int j = 0; j < s_width; j++) {
671
+ bool bit = i & 1 << j;
672
+ if (arg2[j] == (bit ? RTLIL::S0 : RTLIL::S1))
673
+ ne = true;
674
+ else if (arg2[j] != RTLIL::S0 && arg2[j] != RTLIL::S1)
675
+ x = true;
676
+ }
677
+ if (ne) {
678
+ for (int j = 0; j < width; j++)
679
+ res.push_back(State::S0);
680
+ } else if (x) {
681
+ for (int j = 0; j < width; j++)
682
+ res.push_back(arg1[j] == State::S0 ? State::S0 : State::Sx);
683
+ } else {
684
+ for (int j = 0; j < width; j++)
685
+ res.push_back(arg1[j]);
686
+ }
687
+ }
688
+ return res;
689
+ }
690
+
691
+ RTLIL::Const RTLIL::const_bweqx(const RTLIL::Const &arg1, const RTLIL::Const &arg2)
692
+ {
693
+ log_assert(arg2.size() == arg1.size());
694
+ RTLIL::Const result(RTLIL::State::S0, arg1.size());
695
+ for (auto i = 0; i < arg1.size(); i++)
696
+ result.set(i, arg1[i] == arg2[i] ? State::S1 : State::S0);
697
+
698
+ return result;
699
+ }
700
+
701
+ RTLIL::Const RTLIL::const_bwmux(const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3)
702
+ {
703
+ log_assert(arg2.size() == arg1.size());
704
+ log_assert(arg3.size() == arg1.size());
705
+ RTLIL::Const result(RTLIL::State::Sx, arg1.size());
706
+ for (auto i = 0; i < arg1.size(); i++) {
707
+ if (arg3[i] != State::Sx || arg1[i] == arg2[i])
708
+ result.set(i, arg3[i] == State::S1 ? arg2[i] : arg1[i]);
709
+ }
710
+
711
+ return result;
712
+ }
713
+
714
+ YOSYS_NAMESPACE_END
chips/yosys/kernel/cellaigs.cc ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/cellaigs.h"
21
+
22
+ YOSYS_NAMESPACE_BEGIN
23
+
24
+ AigNode::AigNode()
25
+ {
26
+ portbit = -1;
27
+ inverter = false;
28
+ left_parent = -1;
29
+ right_parent = -1;
30
+ }
31
+
32
+ bool AigNode::operator==(const AigNode &other) const
33
+ {
34
+ if (portname != other.portname) return false;
35
+ if (portbit != other.portbit) return false;
36
+ if (inverter != other.inverter) return false;
37
+ if (left_parent != other.left_parent) return false;
38
+ if (right_parent != other.right_parent) return false;
39
+ return true;
40
+ }
41
+
42
+ Hasher AigNode::hash_into(Hasher h) const
43
+ {
44
+ h.eat(portname);
45
+ h.eat(portbit);
46
+ h.eat(inverter);
47
+ h.eat(left_parent);
48
+ h.eat(right_parent);
49
+ return h;
50
+ }
51
+
52
+ bool Aig::operator==(const Aig &other) const
53
+ {
54
+ return name == other.name;
55
+ }
56
+
57
+ Hasher Aig::hash_into(Hasher h) const
58
+ {
59
+ h.eat(name);
60
+ return h;
61
+ }
62
+
63
+ struct AigMaker
64
+ {
65
+ Aig *aig;
66
+ Cell *cell;
67
+ idict<AigNode> aig_indices;
68
+
69
+ AigMaker(Aig *aig, Cell *cell) : aig(aig), cell(cell) {}
70
+
71
+ int node2index(const AigNode &node)
72
+ {
73
+ if (node.left_parent > node.right_parent) {
74
+ AigNode n(node);
75
+ std::swap(n.left_parent, n.right_parent);
76
+ return node2index(n);
77
+ }
78
+
79
+ if (!aig_indices.count(node)) {
80
+ aig_indices.expect(node, GetSize(aig->nodes));
81
+ aig->nodes.push_back(node);
82
+ }
83
+
84
+ return aig_indices.at(node);
85
+ }
86
+
87
+ int bool_node(bool value)
88
+ {
89
+ AigNode node;
90
+ node.inverter = value;
91
+ return node2index(node);
92
+ }
93
+
94
+ int inport(IdString portname, int portbit = 0, bool inverter = false)
95
+ {
96
+ if (portbit >= GetSize(cell->getPort(portname))) {
97
+ IdString signed_param = cell->twines().find(
98
+ cell->twines().str(portname) + "_SIGNED");
99
+ if (signed_param != IdString::Null && cell->parameters.count(signed_param) && cell->getParam(signed_param).as_bool())
100
+ return inport(portname, GetSize(cell->getPort(portname))-1, inverter);
101
+ return bool_node(inverter);
102
+ }
103
+
104
+ AigNode node;
105
+ node.portname = portname;
106
+ node.portbit = portbit;
107
+ node.inverter = inverter;
108
+ return node2index(node);
109
+ }
110
+
111
+ vector<int> inport_vec(IdString portname, int width)
112
+ {
113
+ vector<int> vec;
114
+ for (int i = 0; i < width; i++)
115
+ vec.push_back(inport(portname, i));
116
+ return vec;
117
+ }
118
+
119
+ int not_inport(IdString portname, int portbit = 0)
120
+ {
121
+ return inport(portname, portbit, true);
122
+ }
123
+
124
+ int not_gate(int A)
125
+ {
126
+ AigNode node(aig_indices[A]);
127
+ node.outports.clear();
128
+ node.inverter = !node.inverter;
129
+ return node2index(node);
130
+ }
131
+
132
+ int and_gate(int A, int B, bool inverter = false)
133
+ {
134
+ if (A == B)
135
+ return inverter ? not_gate(A) : A;
136
+
137
+ const AigNode &nA = aig_indices[A];
138
+ const AigNode &nB = aig_indices[B];
139
+
140
+ AigNode nB_inv(nB);
141
+ nB_inv.inverter = !nB_inv.inverter;
142
+
143
+ if (nA == nB_inv)
144
+ return bool_node(inverter);
145
+
146
+ bool nA_bool = nA.portbit < 0 && nA.left_parent < 0 && nA.right_parent < 0;
147
+ bool nB_bool = nB.portbit < 0 && nB.left_parent < 0 && nB.right_parent < 0;
148
+
149
+ if (nA_bool && nB_bool) {
150
+ bool bA = nA.inverter;
151
+ bool bB = nB.inverter;
152
+ return bool_node(inverter != (bA && bB));
153
+ }
154
+
155
+ if (nA_bool) {
156
+ bool bA = nA.inverter;
157
+ if (inverter)
158
+ return bA ? not_gate(B) : bool_node(true);
159
+ return bA ? B : bool_node(false);
160
+ }
161
+
162
+ if (nB_bool) {
163
+ bool bB = nB.inverter;
164
+ if (inverter)
165
+ return bB ? not_gate(A) : bool_node(true);
166
+ return bB ? A : bool_node(false);
167
+ }
168
+
169
+ AigNode node;
170
+ node.inverter = inverter;
171
+ node.left_parent = A;
172
+ node.right_parent = B;
173
+ return node2index(node);
174
+ }
175
+
176
+ int nand_gate(int A, int B)
177
+ {
178
+ return and_gate(A, B, true);
179
+ }
180
+
181
+ int or_gate(int A, int B)
182
+ {
183
+ int not_a = not_gate(A);
184
+ int not_b = not_gate(B);
185
+ return nand_gate(not_a, not_b);
186
+ }
187
+
188
+ int nor_gate(int A, int B)
189
+ {
190
+ int not_a = not_gate(A);
191
+ int not_b = not_gate(B);
192
+ return and_gate(not_a, not_b);
193
+ }
194
+
195
+ int xor_gate(int A, int B)
196
+ {
197
+ int a_and_b = and_gate(A, B);
198
+ int a_nor_b = nor_gate(A, B);
199
+ return nor_gate(a_and_b, a_nor_b);
200
+ }
201
+
202
+ int xnor_gate(int A, int B)
203
+ {
204
+ int a_and_b = and_gate(A, B);
205
+ int a_nor_b = nor_gate(A, B);
206
+ return or_gate(a_and_b, a_nor_b);
207
+ }
208
+
209
+ int andnot_gate(int A, int B)
210
+ {
211
+ int not_b = not_gate(B);
212
+ return and_gate(A, not_b);
213
+ }
214
+
215
+ int ornot_gate(int A, int B)
216
+ {
217
+ int not_b = not_gate(B);
218
+ return or_gate(A, not_b);
219
+ }
220
+
221
+ int mux_gate(int A, int B, int S)
222
+ {
223
+ int not_s = not_gate(S);
224
+ int a_active = and_gate(A, not_s);
225
+ int b_active = and_gate(B, S);
226
+ return or_gate(a_active, b_active);
227
+ }
228
+
229
+ vector<int> adder(const vector<int> &A, const vector<int> &B, int carry_in, vector<int> *X = nullptr, vector<int> *CO = nullptr)
230
+ {
231
+ vector<int> Y(GetSize(A));
232
+ log_assert(GetSize(A) == GetSize(B));
233
+ for (int i = 0; i < GetSize(A); i++) {
234
+ int a_xor_b = xor_gate(A[i], B[i]);
235
+ int a_or_b = or_gate(A[i], B[i]);
236
+ int a_and_b = and_gate(A[i], B[i]);
237
+ Y[i] = xor_gate(a_xor_b, carry_in);
238
+ int tmp = and_gate(a_or_b, carry_in);
239
+ int carry_out = or_gate(a_and_b, tmp);
240
+ if (X != nullptr)
241
+ X->at(i) = a_xor_b;
242
+ if (CO != nullptr)
243
+ CO->at(i) = carry_out;
244
+ carry_in = carry_out;
245
+ }
246
+ return Y;
247
+ }
248
+
249
+ void outport(int node, IdString portname, int portbit = 0)
250
+ {
251
+ if (portbit < GetSize(cell->getPort(portname)))
252
+ aig->nodes.at(node).outports.push_back(pair<IdString, int>(portname, portbit));
253
+ }
254
+
255
+ void outport_bool(int node, IdString portname)
256
+ {
257
+ outport(node, portname);
258
+ for (int i = 1; i < GetSize(cell->getPort(portname)); i++)
259
+ outport(bool_node(false), portname, i);
260
+ }
261
+
262
+ void outport_vec(const vector<int> &vec, IdString portname)
263
+ {
264
+ for (int i = 0; i < GetSize(vec); i++)
265
+ outport(vec.at(i), portname, i);
266
+ }
267
+ };
268
+
269
+ Aig::Aig(Cell *cell)
270
+ {
271
+ if (cell->type.isPublic())
272
+ return;
273
+
274
+ AigMaker mk(this, cell);
275
+ name = cell->type.str();
276
+
277
+ string mkname_last;
278
+ bool mkname_a_signed = false;
279
+ bool mkname_b_signed = false;
280
+ bool mkname_is_signed = false;
281
+
282
+ cell->parameters.sort();
283
+ for (auto p : cell->parameters)
284
+ {
285
+ if (p.first == ID::A_WIDTH && mkname_a_signed) {
286
+ name = mkname_last + stringf(":%d%c", p.second.as_int(), mkname_is_signed ? 'S' : 'U');
287
+ } else if (p.first == ID::B_WIDTH && mkname_b_signed) {
288
+ name = mkname_last + stringf(":%d%c", p.second.as_int(), mkname_is_signed ? 'S' : 'U');
289
+ } else {
290
+ mkname_last = name;
291
+ name += stringf(":%d", p.second.as_int());
292
+ }
293
+
294
+ mkname_a_signed = false;
295
+ mkname_b_signed = false;
296
+ mkname_is_signed = false;
297
+ if (p.first == ID::A_SIGNED) {
298
+ mkname_a_signed = true;
299
+ mkname_is_signed = p.second.as_bool();
300
+ }
301
+ if (p.first == ID::B_SIGNED) {
302
+ mkname_b_signed = true;
303
+ mkname_is_signed = p.second.as_bool();
304
+ }
305
+ }
306
+
307
+ if (cell->type.in(ID($not), ID($_NOT_), ID($pos), ID($buf), ID($_BUF_)))
308
+ {
309
+ for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) {
310
+ int A = mk.inport(ID::A, i);
311
+ int Y = cell->type.in(ID($not), ID($_NOT_)) ? mk.not_gate(A) : A;
312
+ mk.outport(Y, ID::Y, i);
313
+ }
314
+ goto optimize;
315
+ }
316
+
317
+ if (cell->type.in(ID($and), ID($_AND_), ID($_NAND_), ID($or), ID($_OR_), ID($_NOR_), ID($xor), ID($xnor), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_)))
318
+ {
319
+ for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) {
320
+ int A = mk.inport(ID::A, i);
321
+ int B = mk.inport(ID::B, i);
322
+ int Y = cell->type.in(ID($and), ID($_AND_)) ? mk.and_gate(A, B) :
323
+ cell->type.in(ID($_NAND_)) ? mk.nand_gate(A, B) :
324
+ cell->type.in(ID($or), ID($_OR_)) ? mk.or_gate(A, B) :
325
+ cell->type.in(ID($_NOR_)) ? mk.nor_gate(A, B) :
326
+ cell->type.in(ID($xor), ID($_XOR_)) ? mk.xor_gate(A, B) :
327
+ cell->type.in(ID($xnor), ID($_XNOR_)) ? mk.xnor_gate(A, B) :
328
+ cell->type.in(ID($_ANDNOT_)) ? mk.andnot_gate(A, B) :
329
+ cell->type.in(ID($_ORNOT_)) ? mk.ornot_gate(A, B) : -1;
330
+ mk.outport(Y, ID::Y, i);
331
+ }
332
+ goto optimize;
333
+ }
334
+
335
+ if (cell->type.in(ID($mux), ID($_MUX_), ID($_NMUX_)))
336
+ {
337
+ int S = mk.inport(ID::S);
338
+ for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) {
339
+ int A = mk.inport(ID::A, i);
340
+ int B = mk.inport(ID::B, i);
341
+ int Y = mk.mux_gate(A, B, S);
342
+ if (cell->type == ID($_NMUX_))
343
+ Y = mk.not_gate(Y);
344
+ mk.outport(Y, ID::Y, i);
345
+ }
346
+ goto optimize;
347
+ }
348
+
349
+ if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool)))
350
+ {
351
+ int Y = mk.inport(ID::A, 0);
352
+ for (int i = 1; i < GetSize(cell->getPort(ID::A)); i++) {
353
+ int A = mk.inport(ID::A, i);
354
+ if (cell->type == ID($reduce_and)) Y = mk.and_gate(A, Y);
355
+ if (cell->type == ID($reduce_or)) Y = mk.or_gate(A, Y);
356
+ if (cell->type == ID($reduce_bool)) Y = mk.or_gate(A, Y);
357
+ if (cell->type == ID($reduce_xor)) Y = mk.xor_gate(A, Y);
358
+ if (cell->type == ID($reduce_xnor)) Y = mk.xor_gate(A, Y);
359
+ }
360
+ if (cell->type == ID($reduce_xnor))
361
+ Y = mk.not_gate(Y);
362
+ mk.outport(Y, ID::Y, 0);
363
+ for (int i = 1; i < GetSize(cell->getPort(ID::Y)); i++)
364
+ mk.outport(mk.bool_node(false), ID::Y, i);
365
+ goto optimize;
366
+ }
367
+
368
+ if (cell->type.in(ID($logic_not), ID($logic_and), ID($logic_or)))
369
+ {
370
+ int A = mk.inport(ID::A, 0), Y = -1;
371
+ for (int i = 1; i < GetSize(cell->getPort(ID::A)); i++)
372
+ A = mk.or_gate(mk.inport(ID::A, i), A);
373
+ if (cell->type.in(ID($logic_and), ID($logic_or))) {
374
+ int B = mk.inport(ID::B, 0);
375
+ for (int i = 1; i < GetSize(cell->getPort(ID::B)); i++)
376
+ B = mk.or_gate(mk.inport(ID::B, i), B);
377
+ if (cell->type == ID($logic_and)) Y = mk.and_gate(A, B);
378
+ if (cell->type == ID($logic_or)) Y = mk.or_gate(A, B);
379
+ } else {
380
+ if (cell->type == ID($logic_not)) Y = mk.not_gate(A);
381
+ }
382
+ mk.outport_bool(Y, ID::Y);
383
+ goto optimize;
384
+ }
385
+
386
+ if (cell->type.in(ID($add), ID($sub)))
387
+ {
388
+ int width = GetSize(cell->getPort(ID::Y));
389
+ vector<int> A = mk.inport_vec(ID::A, width);
390
+ vector<int> B = mk.inport_vec(ID::B, width);
391
+ int carry = mk.bool_node(false);
392
+ if (cell->type == ID($sub)) {
393
+ for (auto &n : B)
394
+ n = mk.not_gate(n);
395
+ carry = mk.not_gate(carry);
396
+ }
397
+ vector<int> Y = mk.adder(A, B, carry);
398
+ mk.outport_vec(Y, ID::Y);
399
+ goto optimize;
400
+ }
401
+
402
+ if (cell->type.in(ID($lt), ID($gt), ID($le), ID($ge)))
403
+ {
404
+ int width = std::max(GetSize(cell->getPort(ID::A)),
405
+ GetSize(cell->getPort(ID::B))) + 1;
406
+ vector<int> A = mk.inport_vec(ID::A, width);
407
+ vector<int> B = mk.inport_vec(ID::B, width);
408
+
409
+ if (cell->type.in(ID($gt), ID($ge)))
410
+ std::swap(A, B);
411
+
412
+ int carry = mk.bool_node(!cell->type.in(ID($le), ID($ge)));
413
+ for (auto &n : B)
414
+ n = mk.not_gate(n);
415
+ vector<int> Y = mk.adder(A, B, carry);
416
+ mk.outport(Y.back(), ID::Y);
417
+ for (int i = 1; i < GetSize(cell->getPort(ID::Y)); i++)
418
+ mk.outport(mk.bool_node(false), ID::Y, i);
419
+ goto optimize;
420
+ }
421
+
422
+ if (cell->type == ID($alu))
423
+ {
424
+ int width = GetSize(cell->getPort(ID::Y));
425
+ vector<int> A = mk.inport_vec(ID::A, width);
426
+ vector<int> B = mk.inport_vec(ID::B, width);
427
+ int carry = mk.inport(ID::CI);
428
+ int binv = mk.inport(ID::BI);
429
+ for (auto &n : B)
430
+ n = mk.xor_gate(n, binv);
431
+ vector<int> X(width), CO(width);
432
+ vector<int> Y = mk.adder(A, B, carry, &X, &CO);
433
+ for (int i = 0; i < width; i++)
434
+ X[i] = mk.xor_gate(A[i], B[i]);
435
+ mk.outport_vec(Y, ID::Y);
436
+ mk.outport_vec(X, ID::X);
437
+ mk.outport_vec(CO, ID::CO);
438
+ goto optimize;
439
+ }
440
+
441
+ if (cell->type.in(ID($eq), ID($ne)))
442
+ {
443
+ int width = max(GetSize(cell->getPort(ID::A)), GetSize(cell->getPort(ID::B)));
444
+ vector<int> A = mk.inport_vec(ID::A, width);
445
+ vector<int> B = mk.inport_vec(ID::B, width);
446
+ int Y = mk.bool_node(false);
447
+ for (int i = 0; i < width; i++)
448
+ Y = mk.or_gate(Y, mk.xor_gate(A[i], B[i]));
449
+ if (cell->type == ID($eq))
450
+ Y = mk.not_gate(Y);
451
+ mk.outport_bool(Y, ID::Y);
452
+ goto optimize;
453
+ }
454
+
455
+ if (cell->type == ID($_AOI3_))
456
+ {
457
+ int A = mk.inport(ID::A);
458
+ int B = mk.inport(ID::B);
459
+ int C = mk.inport(ID::C);
460
+ int Y = mk.nor_gate(mk.and_gate(A, B), C);
461
+ mk.outport(Y, ID::Y);
462
+ goto optimize;
463
+ }
464
+
465
+ if (cell->type == ID($_OAI3_))
466
+ {
467
+ int A = mk.inport(ID::A);
468
+ int B = mk.inport(ID::B);
469
+ int C = mk.inport(ID::C);
470
+ int Y = mk.nand_gate(mk.or_gate(A, B), C);
471
+ mk.outport(Y, ID::Y);
472
+ goto optimize;
473
+ }
474
+
475
+ if (cell->type == ID($_AOI4_))
476
+ {
477
+ int A = mk.inport(ID::A);
478
+ int B = mk.inport(ID::B);
479
+ int C = mk.inport(ID::C);
480
+ int D = mk.inport(ID::D);
481
+ int a_and_b = mk.and_gate(A, B);
482
+ int Y = mk.nor_gate(a_and_b, mk.and_gate(C, D));
483
+ mk.outport(Y, ID::Y);
484
+ goto optimize;
485
+ }
486
+
487
+ if (cell->type == ID($_OAI4_))
488
+ {
489
+ int A = mk.inport(ID::A);
490
+ int B = mk.inport(ID::B);
491
+ int C = mk.inport(ID::C);
492
+ int D = mk.inport(ID::D);
493
+ int a_or_b = mk.or_gate(A, B);
494
+ int Y = mk.nand_gate(a_or_b, mk.or_gate(C, D));
495
+ mk.outport(Y, ID::Y);
496
+ goto optimize;
497
+ }
498
+
499
+ name.clear();
500
+ return;
501
+
502
+ optimize:;
503
+ pool<int> used_old_ids;
504
+ vector<AigNode> new_nodes;
505
+ dict<int, int> old_to_new_ids;
506
+ old_to_new_ids[-1] = -1;
507
+
508
+ for (int i = GetSize(nodes)-1; i >= 0; i--) {
509
+ if (!nodes[i].outports.empty())
510
+ used_old_ids.insert(i);
511
+ if (!used_old_ids.count(i))
512
+ continue;
513
+ if (nodes[i].left_parent >= 0)
514
+ used_old_ids.insert(nodes[i].left_parent);
515
+ if (nodes[i].right_parent >= 0)
516
+ used_old_ids.insert(nodes[i].right_parent);
517
+ }
518
+
519
+ for (int i = 0; i < GetSize(nodes); i++) {
520
+ if (!used_old_ids.count(i))
521
+ continue;
522
+ nodes[i].left_parent = old_to_new_ids.at(nodes[i].left_parent);
523
+ nodes[i].right_parent = old_to_new_ids.at(nodes[i].right_parent);
524
+ old_to_new_ids[i] = GetSize(new_nodes);
525
+ new_nodes.push_back(nodes[i]);
526
+ }
527
+
528
+ new_nodes.swap(nodes);
529
+ }
530
+
531
+ YOSYS_NAMESPACE_END
chips/yosys/kernel/cellaigs.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef CELLAIGS_H
21
+ #define CELLAIGS_H
22
+
23
+ #include "kernel/yosys.h"
24
+
25
+ YOSYS_NAMESPACE_BEGIN
26
+
27
+ struct AigNode
28
+ {
29
+ IdString portname;
30
+ int portbit;
31
+ bool inverter;
32
+ int left_parent, right_parent;
33
+ vector<pair<IdString, int>> outports;
34
+
35
+ AigNode();
36
+ bool operator==(const AigNode &other) const;
37
+ [[nodiscard]] Hasher hash_into(Hasher h) const;
38
+ };
39
+
40
+ struct Aig
41
+ {
42
+ string name;
43
+ vector<AigNode> nodes;
44
+ Aig(Cell *cell);
45
+
46
+ bool operator==(const Aig &other) const;
47
+ [[nodiscard]] Hasher hash_into(Hasher h) const;
48
+ };
49
+
50
+ YOSYS_NAMESPACE_END
51
+
52
+ #endif
chips/yosys/kernel/celledges.cc ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #include "kernel/celledges.h"
21
+
22
+ USING_YOSYS_NAMESPACE
23
+ PRIVATE_NAMESPACE_BEGIN
24
+
25
+ void bitwise_unary_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
26
+ {
27
+ bool is_signed = !cell->type.in(ID($buf), ID($barrier)) && cell->getParam(ID::A_SIGNED).as_bool();
28
+ int a_width = GetSize(cell->getPort(ID::A));
29
+ int y_width = GetSize(cell->getPort(ID::Y));
30
+
31
+ for (int i = 0; i < y_width; i++)
32
+ {
33
+ if (i < a_width)
34
+ db->add_edge(cell, ID::A, i, ID::Y, i, -1);
35
+ else if (is_signed && a_width > 0)
36
+ db->add_edge(cell, ID::A, a_width-1, ID::Y, i, -1);
37
+ }
38
+ }
39
+
40
+ void bitwise_binary_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
41
+ {
42
+ bool is_signed = cell->getParam(ID::A_SIGNED).as_bool();
43
+ int a_width = GetSize(cell->getPort(ID::A));
44
+ int b_width = GetSize(cell->getPort(ID::B));
45
+ int y_width = GetSize(cell->getPort(ID::Y));
46
+
47
+ if (cell->type == ID($and) && !is_signed) {
48
+ if (a_width > b_width)
49
+ a_width = b_width;
50
+ else
51
+ b_width = a_width;
52
+ }
53
+
54
+ for (int i = 0; i < y_width; i++)
55
+ {
56
+ if (i < a_width)
57
+ db->add_edge(cell, ID::A, i, ID::Y, i, -1);
58
+ else if (is_signed && a_width > 0)
59
+ db->add_edge(cell, ID::A, a_width-1, ID::Y, i, -1);
60
+
61
+ if (i < b_width)
62
+ db->add_edge(cell, ID::B, i, ID::Y, i, -1);
63
+ else if (is_signed && b_width > 0)
64
+ db->add_edge(cell, ID::B, b_width-1, ID::Y, i, -1);
65
+ }
66
+ }
67
+
68
+ void arith_neg_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
69
+ {
70
+ bool is_signed = cell->getParam(ID::A_SIGNED).as_bool();
71
+ int a_width = GetSize(cell->getPort(ID::A));
72
+ int y_width = GetSize(cell->getPort(ID::Y));
73
+
74
+ if (is_signed && a_width == 1)
75
+ y_width = std::min(y_width, 1);
76
+
77
+ for (int i = 0; i < y_width; i++)
78
+ for (int k = 0; k <= i && k < a_width; k++)
79
+ db->add_edge(cell, ID::A, k, ID::Y, i, -1);
80
+ }
81
+
82
+ void arith_binary_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
83
+ {
84
+ bool is_signed = cell->getParam(ID::A_SIGNED).as_bool();
85
+ int a_width = GetSize(cell->getPort(ID::A));
86
+ int b_width = GetSize(cell->getPort(ID::B));
87
+ int y_width = GetSize(cell->getPort(ID::Y));
88
+
89
+ if (!is_signed && cell->type != ID($sub)) {
90
+ int ab_width = std::max(a_width, b_width);
91
+ y_width = std::min(y_width, ab_width+1);
92
+ }
93
+
94
+ for (int i = 0; i < y_width; i++)
95
+ {
96
+ for (int k = 0; k <= i; k++)
97
+ {
98
+ if (k < a_width)
99
+ db->add_edge(cell, ID::A, k, ID::Y, i, -1);
100
+
101
+ if (k < b_width)
102
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
103
+ }
104
+ }
105
+ }
106
+
107
+ void reduce_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
108
+ {
109
+ int a_width = GetSize(cell->getPort(ID::A));
110
+
111
+ for (int i = 0; i < a_width; i++)
112
+ db->add_edge(cell, ID::A, i, ID::Y, 0, -1);
113
+ }
114
+
115
+ void logic_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
116
+ {
117
+ int a_width = GetSize(cell->getPort(ID::A));
118
+ int b_width = GetSize(cell->getPort(ID::B));
119
+
120
+ for (int i = 0; i < a_width; i++)
121
+ db->add_edge(cell, ID::A, i, ID::Y, 0, -1);
122
+ for (int i = 0; i < b_width; i++)
123
+ db->add_edge(cell, ID::B, i, ID::Y, 0, -1);
124
+ }
125
+
126
+ void concat_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
127
+ {
128
+ int a_width = GetSize(cell->getPort(ID::A));
129
+ int b_width = GetSize(cell->getPort(ID::B));
130
+
131
+ for (int i = 0; i < a_width; i++)
132
+ db->add_edge(cell, ID::A, i, ID::Y, i, -1);
133
+ for (int i = 0; i < b_width; i++)
134
+ db->add_edge(cell, ID::B, i, ID::Y, a_width + i, -1);
135
+ }
136
+
137
+ void slice_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
138
+ {
139
+ int offset = cell->getParam(ID::OFFSET).as_int();
140
+ int a_width = GetSize(cell->getPort(ID::A));
141
+ int y_width = GetSize(cell->getPort(ID::Y));
142
+
143
+ for (int i = 0; i < y_width; i++) {
144
+ int a_bit = offset + i;
145
+ if (a_bit >= 0 && a_bit < a_width)
146
+ db->add_edge(cell, ID::A, a_bit, ID::Y, i, -1);
147
+ }
148
+ }
149
+
150
+ void compare_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
151
+ {
152
+ int a_width = GetSize(cell->getPort(ID::A));
153
+ int b_width = GetSize(cell->getPort(ID::B));
154
+
155
+ for (int i = 0; i < a_width; i++)
156
+ db->add_edge(cell, ID::A, i, ID::Y, 0, -1);
157
+
158
+ for (int i = 0; i < b_width; i++)
159
+ db->add_edge(cell, ID::B, i, ID::Y, 0, -1);
160
+ }
161
+
162
+ void mux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
163
+ {
164
+ int a_width = GetSize(cell->getPort(ID::A));
165
+ int b_width = GetSize(cell->getPort(ID::B));
166
+ int s_width = GetSize(cell->getPort(ID::S));
167
+
168
+ for (int i = 0; i < a_width; i++)
169
+ {
170
+ db->add_edge(cell, ID::A, i, ID::Y, i, -1);
171
+
172
+ for (int k = i; k < b_width; k += a_width)
173
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
174
+
175
+ for (int k = 0; k < s_width; k++)
176
+ db->add_edge(cell, ID::S, k, ID::Y, i, -1);
177
+ }
178
+ }
179
+
180
+ void bmux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
181
+ {
182
+ int width = GetSize(cell->getPort(ID::Y));
183
+ int a_width = GetSize(cell->getPort(ID::A));
184
+ int s_width = GetSize(cell->getPort(ID::S));
185
+
186
+ for (int i = 0; i < width; i++)
187
+ {
188
+ for (int k = i; k < a_width; k += width)
189
+ db->add_edge(cell, ID::A, k, ID::Y, i, -1);
190
+
191
+ for (int k = 0; k < s_width; k++)
192
+ db->add_edge(cell, ID::S, k, ID::Y, i, -1);
193
+ }
194
+ }
195
+
196
+ void demux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
197
+ {
198
+ int width = GetSize(cell->getPort(ID::Y));
199
+ int a_width = GetSize(cell->getPort(ID::A));
200
+ int s_width = GetSize(cell->getPort(ID::S));
201
+
202
+ for (int i = 0; i < width; i++)
203
+ {
204
+ db->add_edge(cell, ID::A, i % a_width, ID::Y, i, -1);
205
+ for (int k = 0; k < s_width; k++)
206
+ db->add_edge(cell, ID::S, k, ID::Y, i, -1);
207
+ }
208
+ }
209
+
210
+ void shift_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
211
+ {
212
+ bool is_signed = cell->getParam(ID::A_SIGNED).as_bool();
213
+ bool is_b_signed = cell->getParam(ID::B_SIGNED).as_bool();
214
+ int a_width = GetSize(cell->getPort(ID::A));
215
+ int b_width = GetSize(cell->getPort(ID::B));
216
+ int y_width = GetSize(cell->getPort(ID::Y));
217
+
218
+ // Behavior of the different shift cells:
219
+ //
220
+ // $shl, $sshl -- shifts left by the amount on B port, B always unsigned
221
+ // $shr, $sshr -- ditto right
222
+ // $shift, $shiftx -- shifts right by the amount on B port, B optionally signed
223
+ //
224
+ // Sign extension (if A signed):
225
+ //
226
+ // $shl, $shr, $shift -- only sign-extends up to size of Y, then shifts in zeroes
227
+ // $sshl, $sshr -- fully sign-extends
228
+ // $shiftx -- no sign extension
229
+ //
230
+ // Because $shl, $sshl only shift left, and $shl sign-extens up to size of Y, they
231
+ // are effectively the same.
232
+
233
+ // the cap below makes sure we don't overflow in the arithmetic further down, though
234
+ // it makes the edge data invalid once a_width approaches the order of 2**30
235
+ // (that ever happening is considered improbable)
236
+ int b_width_capped = min(b_width, 30);
237
+
238
+ int b_high, b_low;
239
+ if (!is_b_signed) {
240
+ b_high = (1 << b_width_capped) - 1;
241
+ b_low = 0;
242
+ } else {
243
+ b_high = (1 << (b_width_capped - 1)) - 1;
244
+ b_low = -(1 << (b_width_capped - 1));
245
+ }
246
+
247
+ for (int i = 0; i < y_width; i++){
248
+ // highest position of Y that can change with the value of B
249
+ int b_range_upper = 0;
250
+ // 1 + highest position of A that can be moved to Y[i]
251
+ int a_range_upper;
252
+ // lowest position of A that can be moved to Y[i]
253
+ int a_range_lower;
254
+
255
+ if (cell->type.in(ID($shl), ID($sshl))) {
256
+ b_range_upper = a_width + b_high;
257
+ if (is_signed) b_range_upper -= 1;
258
+ a_range_lower = max(0, i - b_high);
259
+ a_range_upper = min(i+1, a_width);
260
+ } else if (cell->type.in(ID($shr), ID($sshr)) || (cell->type.in(ID($shift), ID($shiftx)) && !is_b_signed)) {
261
+ b_range_upper = a_width;
262
+ a_range_lower = min(i, a_width - 1);
263
+ a_range_upper = min(i+1 + b_high, a_width);
264
+ } else if (cell->type.in(ID($shift), ID($shiftx)) && is_b_signed) {
265
+ // can go both ways depending on sign of B
266
+ // 2's complement range is different depending on direction
267
+ b_range_upper = a_width - b_low;
268
+ a_range_lower = max(0, i + b_low);
269
+ if (is_signed)
270
+ a_range_lower = min(a_range_lower, a_width - 1);
271
+ a_range_upper = min(i+1 + b_high, a_width);
272
+ } else {
273
+ log_assert(false && "unreachable");
274
+ }
275
+
276
+ if (i < b_range_upper) {
277
+ for (int k = a_range_lower; k < a_range_upper; k++)
278
+ db->add_edge(cell, ID::A, k, ID::Y, i, -1);
279
+ } else {
280
+ // only influence is through sign extension
281
+ if (is_signed)
282
+ db->add_edge(cell, ID::A, a_width - 1, ID::Y, i, -1);
283
+ }
284
+
285
+ for (int k = 0; k < b_width_capped; k++) {
286
+ // left shifts
287
+ if (cell->type.in(ID($shl), ID($sshl))) {
288
+ if (a_width == 1 && is_signed) {
289
+ int skip = 1 << (k + 1);
290
+ int base = skip -1;
291
+ if (i % skip != base && i - a_width + 2 < 1 << b_width_capped)
292
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
293
+ } else if (is_signed) {
294
+ if (i - a_width + 2 < 1 << b_width_capped)
295
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
296
+ } else {
297
+ if (i - a_width + 1 < 1 << b_width_capped)
298
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
299
+ }
300
+ // right shifts
301
+ } else if (cell->type.in(ID($shr), ID($sshr)) || (cell->type.in(ID($shift), ID($shiftx)) && !is_b_signed)) {
302
+ if (is_signed) {
303
+ bool shift_in_bulk = i < a_width - 1;
304
+ // can we jump into the zero-padding by toggling B[k]?
305
+ bool zpad_jump = (((y_width - i) & ((1 << (k + 1)) - 1)) != 0 \
306
+ && (((y_width - i) & ~(1 << k)) < (1 << b_width_capped)));
307
+
308
+ if (shift_in_bulk || (cell->type.in(ID($shr), ID($shift), ID($shiftx)) && zpad_jump))
309
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
310
+ } else {
311
+ if (i < a_width)
312
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
313
+ }
314
+ // bidirectional shifts (positive B shifts right, negative left)
315
+ } else if (cell->type.in(ID($shift), ID($shiftx)) && is_b_signed) {
316
+ if (is_signed) {
317
+ if (k != b_width_capped - 1) {
318
+ bool r_shift_in_bulk = i < a_width - 1;
319
+ // assuming B is positive, can we jump into the upper zero-padding by toggling B[k]?
320
+ bool r_zpad_jump = (((y_width - i) & ((1 << (k + 1)) - 1)) != 0 \
321
+ && (((y_width - i) & ~(1 << k)) <= b_high));
322
+ // assuming B is negative, can we influence Y[i] by toggling B[k]?
323
+ bool l = a_width - 2 - i >= b_low;
324
+ if (a_width == 1) {
325
+ // in case of a_width==1 we go into more detailed reasoning
326
+ l = l && (~(i - a_width) & ((1 << (k + 1)) - 1)) != 0;
327
+ }
328
+ if (r_shift_in_bulk || r_zpad_jump || l)
329
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
330
+ } else {
331
+ if (y_width - i <= b_high || a_width - 2 - i >= b_low)
332
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
333
+ }
334
+ } else {
335
+ if (a_width - 1 - i >= b_low)
336
+ db->add_edge(cell, ID::B, k, ID::Y, i, -1);
337
+ }
338
+ } else {
339
+ log_assert(false && "unreachable");
340
+ }
341
+ }
342
+ }
343
+ }
344
+
345
+ void packed_mem_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
346
+ {
347
+ log_assert(cell->type == ID($mem_v2));
348
+ Const rd_clk_enable = cell->getParam(ID::RD_CLK_ENABLE);
349
+ int n_rd_ports = cell->getParam(ID::RD_PORTS).as_int();
350
+ int abits = cell->getParam(ID::ABITS).as_int();
351
+ int width = cell->getParam(ID::WIDTH).as_int();
352
+
353
+ for (int i = 0; i < n_rd_ports; i++) {
354
+ if (rd_clk_enable[i] != State::S0) {
355
+ for (int k = 0; k < width; k++)
356
+ db->add_edge(cell, ID::RD_ARST, i, ID::RD_DATA, i * width + k, -1);
357
+ continue;
358
+ }
359
+
360
+ for (int j = 0; j < abits; j++)
361
+ for (int k = 0; k < width; k++)
362
+ db->add_edge(cell, ID::RD_ADDR, i * abits + j,
363
+ ID::RD_DATA, i * width + k, -1);
364
+ }
365
+ }
366
+
367
+ void memrd_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
368
+ {
369
+ log_assert(cell->type.in(ID($memrd), ID($memrd_v2)));
370
+ int abits = cell->getParam(ID::ABITS).as_int();
371
+ int width = cell->getParam(ID::WIDTH).as_int();
372
+
373
+ if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
374
+ if (cell->type == ID($memrd_v2)) {
375
+ for (int k = 0; k < width; k++)
376
+ db->add_edge(cell, ID::ARST, 0, ID::DATA, k, -1);
377
+ }
378
+ return;
379
+ }
380
+
381
+ for (int j = 0; j < abits; j++)
382
+ for (int k = 0; k < width; k++)
383
+ db->add_edge(cell, ID::ADDR, j, ID::DATA, k, -1);
384
+ }
385
+
386
+ void mem_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
387
+ {
388
+ if (cell->type == ID($mem_v2))
389
+ packed_mem_op(db, cell);
390
+ else if (cell->type.in(ID($memrd), ID($memrd_v2)))
391
+ memrd_op(db, cell);
392
+ else if (cell->type.in(ID($memwr), ID($memwr_v2), ID($meminit)))
393
+ return; /* no edges here */
394
+ else
395
+ log_abort();
396
+ }
397
+
398
+ void ff_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
399
+ {
400
+ int width = cell->getPort(ID::Q).size();
401
+
402
+ if (cell->type.in(ID($dlatch), ID($adlatch), ID($dlatchsr))) {
403
+ for (int k = 0; k < width; k++) {
404
+ db->add_edge(cell, ID::D, k, ID::Q, k, -1);
405
+ db->add_edge(cell, ID::EN, 0, ID::Q, k, -1);
406
+ }
407
+ }
408
+
409
+ if (cell->hasPort(ID::CLR))
410
+ for (int k = 0; k < width; k++)
411
+ db->add_edge(cell, ID::CLR, 0, ID::Q, k, -1);
412
+ if (cell->hasPort(ID::SET))
413
+ for (int k = 0; k < width; k++)
414
+ db->add_edge(cell, ID::SET, 0, ID::Q, k, -1);
415
+ if (cell->hasPort(ID::ALOAD))
416
+ for (int k = 0; k < width; k++)
417
+ db->add_edge(cell, ID::ALOAD, 0, ID::Q, k, -1);
418
+ if (cell->hasPort(ID::AD))
419
+ for (int k = 0; k < width; k++)
420
+ db->add_edge(cell, ID::AD, k, ID::Q, k, -1);
421
+ if (cell->hasPort(ID::ARST))
422
+ for (int k = 0; k < width; k++)
423
+ db->add_edge(cell, ID::ARST, 0, ID::Q, k, -1);
424
+ }
425
+
426
+ void full_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
427
+ {
428
+ std::vector<RTLIL::IdString> input_ports;
429
+ std::vector<RTLIL::IdString> output_ports;
430
+
431
+ for (auto &conn : cell->connections())
432
+ {
433
+ RTLIL::IdString port = conn.first;
434
+ RTLIL::PortDir dir = cell->port_dir(port);
435
+ if (cell->input(port) || dir == RTLIL::PortDir::PD_INOUT)
436
+ input_ports.push_back(port);
437
+ if (cell->output(port) || dir == RTLIL::PortDir::PD_INOUT)
438
+ output_ports.push_back(port);
439
+ }
440
+
441
+ for (auto out_port : output_ports)
442
+ {
443
+ int out_width = GetSize(cell->getPort(out_port));
444
+ for (int out_bit = 0; out_bit < out_width; out_bit++)
445
+ {
446
+ for (auto in_port : input_ports)
447
+ {
448
+ int in_width = GetSize(cell->getPort(in_port));
449
+ for (int in_bit = 0; in_bit < in_width; in_bit++)
450
+ db->add_edge(cell, in_port, in_bit, out_port, out_bit, -1);
451
+ }
452
+ }
453
+ }
454
+ }
455
+
456
+ void bweqx_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
457
+ {
458
+ int width = GetSize(cell->getPort(ID::Y));
459
+ int a_width = GetSize(cell->getPort(ID::A));
460
+ int b_width = GetSize(cell->getPort(ID::B));
461
+ int max_width = std::min(width, std::min(a_width, b_width));
462
+
463
+ for (int i = 0; i < max_width; i++) {
464
+ db->add_edge(cell, ID::A, i, ID::Y, i, -1);
465
+ db->add_edge(cell, ID::B, i, ID::Y, i, -1);
466
+ }
467
+ }
468
+
469
+ void bwmux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell)
470
+ {
471
+ int width = GetSize(cell->getPort(ID::Y));
472
+ int a_width = GetSize(cell->getPort(ID::A));
473
+ int b_width = GetSize(cell->getPort(ID::B));
474
+ int s_width = GetSize(cell->getPort(ID::S));
475
+ int max_width = std::min(width, std::min(a_width, std::min(b_width, s_width)));
476
+
477
+ for (int i = 0; i < max_width; i++) {
478
+ db->add_edge(cell, ID::A, i, ID::Y, i, -1);
479
+ db->add_edge(cell, ID::B, i, ID::Y, i, -1);
480
+ db->add_edge(cell, ID::S, i, ID::Y, i, -1);
481
+ }
482
+ }
483
+
484
+ PRIVATE_NAMESPACE_END
485
+
486
+ bool YOSYS_NAMESPACE_PREFIX AbstractCellEdgesDatabase::add_edges_from_cell(RTLIL::Cell *cell)
487
+ {
488
+ if (cell->type.in(ID($not), ID($pos), ID($buf), ID($barrier))) {
489
+ bitwise_unary_op(this, cell);
490
+ return true;
491
+ }
492
+
493
+ if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor))) {
494
+ bitwise_binary_op(this, cell);
495
+ return true;
496
+ }
497
+
498
+ if (cell->type == ID($neg)) {
499
+ arith_neg_op(this, cell);
500
+ return true;
501
+ }
502
+
503
+ if (cell->type.in(ID($add), ID($sub))) {
504
+ arith_binary_op(this, cell);
505
+ return true;
506
+ }
507
+
508
+ if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool), ID($logic_not))) {
509
+ reduce_op(this, cell);
510
+ return true;
511
+ }
512
+
513
+ if (cell->type.in(ID($logic_and), ID($logic_or))) {
514
+ logic_op(this, cell);
515
+ return true;
516
+ }
517
+
518
+ if (cell->type == ID($slice)) {
519
+ slice_op(this, cell);
520
+ return true;
521
+ }
522
+
523
+ if (cell->type == ID($concat)) {
524
+ concat_op(this, cell);
525
+ return true;
526
+ }
527
+
528
+ if (cell->type.in(ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx))) {
529
+ shift_op(this, cell);
530
+ return true;
531
+ }
532
+
533
+ if (cell->type.in(ID($lt), ID($le), ID($eq), ID($ne), ID($eqx), ID($nex), ID($ge), ID($gt))) {
534
+ compare_op(this, cell);
535
+ return true;
536
+ }
537
+
538
+ if (cell->type.in(ID($mux), ID($pmux))) {
539
+ mux_op(this, cell);
540
+ return true;
541
+ }
542
+
543
+ if (cell->type == ID($bmux)) {
544
+ bmux_op(this, cell);
545
+ return true;
546
+ }
547
+
548
+ if (cell->type == ID($demux)) {
549
+ demux_op(this, cell);
550
+ return true;
551
+ }
552
+
553
+ if (cell->type == ID($bweqx)) {
554
+ bweqx_op(this, cell);
555
+ return true;
556
+ }
557
+
558
+ if (cell->type == ID($bwmux)) {
559
+ bwmux_op(this, cell);
560
+ return true;
561
+ }
562
+
563
+ if (cell->type.in(ID($mem_v2), ID($memrd), ID($memrd_v2), ID($memwr), ID($memwr_v2), ID($meminit))) {
564
+ mem_op(this, cell);
565
+ return true;
566
+ }
567
+
568
+ if (cell->is_builtin_ff()) {
569
+ ff_op(this, cell);
570
+ return true;
571
+ }
572
+
573
+ if (cell->type.in(ID($mul), ID($div), ID($mod), ID($divfloor), ID($modfloor), ID($pow))) {
574
+ full_op(this, cell);
575
+ return true;
576
+ }
577
+
578
+ if (cell->type.in(ID($lut), ID($sop), ID($alu), ID($lcu), ID($macc), ID($macc_v2))) {
579
+ full_op(this, cell);
580
+ return true;
581
+ }
582
+
583
+ if (cell->type.in(
584
+ ID($_BUF_), ID($_NOT_), ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_),
585
+ ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_), ID($_MUX_), ID($_NMUX_),
586
+ ID($_MUX4_), ID($_MUX8_), ID($_MUX16_), ID($_AOI3_), ID($_OAI3_), ID($_AOI4_),
587
+ ID($_OAI4_), ID($_TBUF_))) {
588
+ full_op(this, cell);
589
+ return true;
590
+ }
591
+
592
+ // FIXME: $specify2 $specify3 $specrule ???
593
+ // FIXME: $equiv $set_tag $get_tag $overwrite_tag $original_tag
594
+
595
+ if (cell->type.in(ID($assert), ID($assume), ID($live), ID($fair), ID($cover), ID($initstate), ID($anyconst), ID($anyseq), ID($allconst), ID($allseq)))
596
+ return true; // no-op: these have either no inputs or no outputs
597
+
598
+ return false;
599
+ }
chips/yosys/kernel/celledges.h ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- c++ -*-
2
+ * yosys -- Yosys Open SYnthesis Suite
3
+ *
4
+ * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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
+ #ifndef CELLEDGES_H
21
+ #define CELLEDGES_H
22
+
23
+ #include "kernel/yosys.h"
24
+ #include "kernel/sigtools.h"
25
+
26
+ YOSYS_NAMESPACE_BEGIN
27
+
28
+ struct AbstractCellEdgesDatabase
29
+ {
30
+ virtual ~AbstractCellEdgesDatabase() { }
31
+ virtual void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, RTLIL::IdString to_port, int to_bit, int delay) = 0;
32
+ bool add_edges_from_cell(RTLIL::Cell *cell);
33
+ };
34
+
35
+ struct FwdCellEdgesDatabase : AbstractCellEdgesDatabase
36
+ {
37
+ SigMap &sigmap;
38
+ dict<SigBit, pool<SigBit>> db;
39
+ FwdCellEdgesDatabase(SigMap &sigmap) : sigmap(sigmap) { }
40
+
41
+ void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, RTLIL::IdString to_port, int to_bit, int) override {
42
+ SigBit from_sigbit = sigmap(cell->getPort(from_port)[from_bit]);
43
+ SigBit to_sigbit = sigmap(cell->getPort(to_port)[to_bit]);
44
+ db[from_sigbit].insert(to_sigbit);
45
+ }
46
+ };
47
+
48
+ struct RevCellEdgesDatabase : AbstractCellEdgesDatabase
49
+ {
50
+ SigMap &sigmap;
51
+ dict<SigBit, pool<SigBit>> db;
52
+ RevCellEdgesDatabase(SigMap &sigmap) : sigmap(sigmap) { }
53
+
54
+ void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, RTLIL::IdString to_port, int to_bit, int) override {
55
+ SigBit from_sigbit = sigmap(cell->getPort(from_port)[from_bit]);
56
+ SigBit to_sigbit = sigmap(cell->getPort(to_port)[to_bit]);
57
+ db[to_sigbit].insert(from_sigbit);
58
+ }
59
+ };
60
+
61
+ YOSYS_NAMESPACE_END
62
+
63
+ #endif
chips/yosys/kernel/cellhelp.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from __future__ import annotations
4
+ import fileinput
5
+ import json
6
+ from pathlib import Path
7
+
8
+ class SimHelper:
9
+ name: str = ""
10
+ title: str = ""
11
+ ports: str = ""
12
+ source: str = ""
13
+ desc: list[str]
14
+ code: list[str]
15
+ group: str = ""
16
+ ver: str = "1"
17
+ tags: list[str]
18
+
19
+ def __init__(self) -> None:
20
+ self.desc = []
21
+ self.tags = []
22
+
23
+ def __str__(self) -> str:
24
+ printed_fields = [
25
+ "name", "title", "ports", "source", "desc", "code", "group", "ver",
26
+ "tags",
27
+ ]
28
+ # generate C++ struct
29
+ val = f"cell_help[{json.dumps(self.name)}] = "
30
+ val += "{\n"
31
+ for field in printed_fields:
32
+ field_val = getattr(self, field)
33
+ if isinstance(field_val, list):
34
+ field_val = "\n".join(field_val)
35
+ field_val = field_val.strip()
36
+ val += f' {json.dumps(field_val)},\n'
37
+ val += "};\n"
38
+ return val
39
+
40
+ def simcells_reparse(cell: SimHelper):
41
+ # cut manual signature
42
+ cell.desc = cell.desc[3:]
43
+
44
+ # code-block truth table
45
+ new_desc = []
46
+ indent = ""
47
+ for line in cell.desc:
48
+ if line.startswith("Truth table:"):
49
+ indent = " "
50
+ new_desc.pop()
51
+ new_desc.extend(["::", ""])
52
+ new_desc.append(indent + line)
53
+ cell.desc = new_desc
54
+
55
+ # set version
56
+ cell.ver = "2a"
57
+
58
+ simHelper = SimHelper()
59
+
60
+ for line in fileinput.input():
61
+ line = line.rstrip()
62
+ # special comments
63
+ if line.startswith("//-"):
64
+ simHelper.desc.append(line[4:] if len(line) > 4 else "")
65
+ elif line.startswith("//* "):
66
+ _, key, val = line.split(maxsplit=2)
67
+ setattr(simHelper, key, val)
68
+
69
+ # code parsing
70
+ if line.startswith("module "):
71
+ clean_line = line[7:].replace("\\", "").replace(";", "")
72
+ simHelper.name, simHelper.ports = clean_line.split(maxsplit=1)
73
+ simHelper.code = []
74
+ short_filename = Path(fileinput.filename()).name
75
+ simHelper.source = f'{short_filename}:{fileinput.filelineno()}'
76
+ elif not line.startswith("endmodule"):
77
+ line = " " + line
78
+ try:
79
+ simHelper.code.append(line.replace("\t", " "))
80
+ except AttributeError:
81
+ # no module definition, ignore line
82
+ pass
83
+ if line.startswith("endmodule"):
84
+ short_filename = Path(fileinput.filename()).name
85
+ if simHelper.ver == "1" and short_filename == "simcells.v":
86
+ # default simcells parsing
87
+ simcells_reparse(simHelper)
88
+
89
+ # check help
90
+ if simHelper.desc and simHelper.ver == "1" and short_filename == "simlib.v" and simHelper.desc[1].startswith(' '):
91
+ simHelper.desc.pop(1)
92
+
93
+ # check group
94
+ assert simHelper.group, f"techlibs/common/{simHelper.source}: {simHelper.name} cell missing group"
95
+
96
+ # dump
97
+ print(simHelper)
98
+ # new
99
+ simHelper = SimHelper()