Preserve 'signed'-ness of a verilog wire through RTLIL
[yosys.git] / backends / json / json.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/cellaigs.h"
25 #include "kernel/log.h"
26 #include <string>
27
28 USING_YOSYS_NAMESPACE
29 PRIVATE_NAMESPACE_BEGIN
30
31 struct JsonWriter
32 {
33 std::ostream &f;
34 bool use_selection;
35 bool aig_mode;
36 bool compat_int_mode;
37
38 Design *design;
39 Module *module;
40
41 SigMap sigmap;
42 int sigidcounter;
43 dict<SigBit, string> sigids;
44 pool<Aig> aig_models;
45
46 JsonWriter(std::ostream &f, bool use_selection, bool aig_mode, bool compat_int_mode) :
47 f(f), use_selection(use_selection), aig_mode(aig_mode),
48 compat_int_mode(compat_int_mode) { }
49
50 string get_string(string str)
51 {
52 string newstr = "\"";
53 for (char c : str) {
54 if (c == '\\')
55 newstr += c;
56 newstr += c;
57 }
58 return newstr + "\"";
59 }
60
61 string get_name(IdString name)
62 {
63 return get_string(RTLIL::unescape_id(name));
64 }
65
66 string get_bits(SigSpec sig)
67 {
68 bool first = true;
69 string str = "[";
70 for (auto bit : sigmap(sig)) {
71 str += first ? " " : ", ";
72 first = false;
73 if (sigids.count(bit) == 0) {
74 string &s = sigids[bit];
75 if (bit.wire == nullptr) {
76 if (bit == State::S0) s = "\"0\"";
77 else if (bit == State::S1) s = "\"1\"";
78 else if (bit == State::Sz) s = "\"z\"";
79 else s = "\"x\"";
80 } else
81 s = stringf("%d", sigidcounter++);
82 }
83 str += sigids[bit];
84 }
85 return str + " ]";
86 }
87
88 void write_parameter_value(const Const &value)
89 {
90 if ((value.flags & RTLIL::ConstFlags::CONST_FLAG_STRING) != 0) {
91 string str = value.decode_string();
92 int state = 0;
93 for (char c : str) {
94 if (state == 0) {
95 if (c == '0' || c == '1' || c == 'x' || c == 'z')
96 state = 0;
97 else if (c == ' ')
98 state = 1;
99 else
100 state = 2;
101 } else if (state == 1 && c != ' ')
102 state = 2;
103 }
104 if (state < 2)
105 str += " ";
106 f << get_string(str);
107 } else if (compat_int_mode && GetSize(value) <= 32 && value.is_fully_def()) {
108 if ((value.flags & RTLIL::ConstFlags::CONST_FLAG_SIGNED) != 0)
109 f << stringf("%d", value.as_int());
110 else
111 f << stringf("%u", value.as_int());
112 } else {
113 f << get_string(value.as_string());
114 }
115 }
116
117 void write_parameters(const dict<IdString, Const> &parameters, bool for_module=false)
118 {
119 bool first = true;
120 for (auto &param : parameters) {
121 f << stringf("%s\n", first ? "" : ",");
122 f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first).c_str());
123 write_parameter_value(param.second);
124 first = false;
125 }
126 }
127
128 void write_module(Module *module_)
129 {
130 module = module_;
131 log_assert(module->design == design);
132 sigmap.set(module);
133 sigids.clear();
134
135 // reserve 0 and 1 to avoid confusion with "0" and "1"
136 sigidcounter = 2;
137
138 f << stringf(" %s: {\n", get_name(module->name).c_str());
139
140 f << stringf(" \"attributes\": {");
141 write_parameters(module->attributes, /*for_module=*/true);
142 f << stringf("\n },\n");
143
144 if (module->parameter_default_values.size()) {
145 f << stringf(" \"parameter_default_values\": {");
146 write_parameters(module->parameter_default_values, /*for_module=*/true);
147 f << stringf("\n },\n");
148 }
149
150 f << stringf(" \"ports\": {");
151 bool first = true;
152 for (auto n : module->ports) {
153 Wire *w = module->wire(n);
154 if (use_selection && !module->selected(w))
155 continue;
156 f << stringf("%s\n", first ? "" : ",");
157 f << stringf(" %s: {\n", get_name(n).c_str());
158 f << stringf(" \"direction\": \"%s\",\n", w->port_input ? w->port_output ? "inout" : "input" : "output");
159 if (w->start_offset)
160 f << stringf(" \"offset\": %d,\n", w->start_offset);
161 if (w->upto)
162 f << stringf(" \"upto\": 1,\n");
163 if (w->is_signed)
164 f << stringf(" \"signed\": %d,\n", w->is_signed);
165 f << stringf(" \"bits\": %s\n", get_bits(w).c_str());
166 f << stringf(" }");
167 first = false;
168 }
169 f << stringf("\n },\n");
170
171 f << stringf(" \"cells\": {");
172 first = true;
173 for (auto c : module->cells()) {
174 if (use_selection && !module->selected(c))
175 continue;
176 f << stringf("%s\n", first ? "" : ",");
177 f << stringf(" %s: {\n", get_name(c->name).c_str());
178 f << stringf(" \"hide_name\": %s,\n", c->name[0] == '$' ? "1" : "0");
179 f << stringf(" \"type\": %s,\n", get_name(c->type).c_str());
180 if (aig_mode) {
181 Aig aig(c);
182 if (!aig.name.empty()) {
183 f << stringf(" \"model\": \"%s\",\n", aig.name.c_str());
184 aig_models.insert(aig);
185 }
186 }
187 f << stringf(" \"parameters\": {");
188 write_parameters(c->parameters);
189 f << stringf("\n },\n");
190 f << stringf(" \"attributes\": {");
191 write_parameters(c->attributes);
192 f << stringf("\n },\n");
193 if (c->known()) {
194 f << stringf(" \"port_directions\": {");
195 bool first2 = true;
196 for (auto &conn : c->connections()) {
197 string direction = "output";
198 if (c->input(conn.first))
199 direction = c->output(conn.first) ? "inout" : "input";
200 f << stringf("%s\n", first2 ? "" : ",");
201 f << stringf(" %s: \"%s\"", get_name(conn.first).c_str(), direction.c_str());
202 first2 = false;
203 }
204 f << stringf("\n },\n");
205 }
206 f << stringf(" \"connections\": {");
207 bool first2 = true;
208 for (auto &conn : c->connections()) {
209 f << stringf("%s\n", first2 ? "" : ",");
210 f << stringf(" %s: %s", get_name(conn.first).c_str(), get_bits(conn.second).c_str());
211 first2 = false;
212 }
213 f << stringf("\n }\n");
214 f << stringf(" }");
215 first = false;
216 }
217 f << stringf("\n },\n");
218
219 f << stringf(" \"netnames\": {");
220 first = true;
221 for (auto w : module->wires()) {
222 if (use_selection && !module->selected(w))
223 continue;
224 f << stringf("%s\n", first ? "" : ",");
225 f << stringf(" %s: {\n", get_name(w->name).c_str());
226 f << stringf(" \"hide_name\": %s,\n", w->name[0] == '$' ? "1" : "0");
227 f << stringf(" \"bits\": %s,\n", get_bits(w).c_str());
228 if (w->start_offset)
229 f << stringf(" \"offset\": %d,\n", w->start_offset);
230 if (w->upto)
231 f << stringf(" \"upto\": 1,\n");
232 if (w->is_signed)
233 f << stringf(" \"signed\": %d,\n", w->is_signed);
234 f << stringf(" \"attributes\": {");
235 write_parameters(w->attributes);
236 f << stringf("\n }\n");
237 f << stringf(" }");
238 first = false;
239 }
240 f << stringf("\n }\n");
241
242 f << stringf(" }");
243 }
244
245 void write_design(Design *design_)
246 {
247 design = design_;
248 design->sort();
249
250 f << stringf("{\n");
251 f << stringf(" \"creator\": %s,\n", get_string(yosys_version_str).c_str());
252 f << stringf(" \"modules\": {\n");
253 vector<Module*> modules = use_selection ? design->selected_modules() : design->modules();
254 bool first_module = true;
255 for (auto mod : modules) {
256 if (!first_module)
257 f << stringf(",\n");
258 write_module(mod);
259 first_module = false;
260 }
261 f << stringf("\n }");
262 if (!aig_models.empty()) {
263 f << stringf(",\n \"models\": {\n");
264 bool first_model = true;
265 for (auto &aig : aig_models) {
266 if (!first_model)
267 f << stringf(",\n");
268 f << stringf(" \"%s\": [\n", aig.name.c_str());
269 int node_idx = 0;
270 for (auto &node : aig.nodes) {
271 if (node_idx != 0)
272 f << stringf(",\n");
273 f << stringf(" /* %3d */ [ ", node_idx);
274 if (node.portbit >= 0)
275 f << stringf("\"%sport\", \"%s\", %d", node.inverter ? "n" : "",
276 log_id(node.portname), node.portbit);
277 else if (node.left_parent < 0 && node.right_parent < 0)
278 f << stringf("\"%s\"", node.inverter ? "true" : "false");
279 else
280 f << stringf("\"%s\", %d, %d", node.inverter ? "nand" : "and", node.left_parent, node.right_parent);
281 for (auto &op : node.outports)
282 f << stringf(", \"%s\", %d", log_id(op.first), op.second);
283 f << stringf(" ]");
284 node_idx++;
285 }
286 f << stringf("\n ]");
287 first_model = false;
288 }
289 f << stringf("\n }");
290 }
291 f << stringf("\n}\n");
292 }
293 };
294
295 struct JsonBackend : public Backend {
296 JsonBackend() : Backend("json", "write design to a JSON file") { }
297 void help() YS_OVERRIDE
298 {
299 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
300 log("\n");
301 log(" write_json [options] [filename]\n");
302 log("\n");
303 log("Write a JSON netlist of the current design.\n");
304 log("\n");
305 log(" -aig\n");
306 log(" include AIG models for the different gate types\n");
307 log("\n");
308 log(" -compat-int\n");
309 log(" emit 32-bit or smaller fully-defined parameter values directly\n");
310 log(" as JSON numbers (for compatibility with old parsers)\n");
311 log("\n");
312 log("\n");
313 log("The general syntax of the JSON output created by this command is as follows:\n");
314 log("\n");
315 log(" {\n");
316 log(" \"creator\": \"Yosys <version info>\",\n");
317 log(" \"modules\": {\n");
318 log(" <module_name>: {\n");
319 log(" \"attributes\": {\n");
320 log(" <attribute_name>: <attribute_value>,\n");
321 log(" ...\n");
322 log(" },\n");
323 log(" \"parameter_default_values\": {\n");
324 log(" <parameter_name>: <parameter_value>,\n");
325 log(" ...\n");
326 log(" },\n");
327 log(" \"ports\": {\n");
328 log(" <port_name>: <port_details>,\n");
329 log(" ...\n");
330 log(" },\n");
331 log(" \"cells\": {\n");
332 log(" <cell_name>: <cell_details>,\n");
333 log(" ...\n");
334 log(" },\n");
335 log(" \"netnames\": {\n");
336 log(" <net_name>: <net_details>,\n");
337 log(" ...\n");
338 log(" }\n");
339 log(" }\n");
340 log(" },\n");
341 log(" \"models\": {\n");
342 log(" ...\n");
343 log(" },\n");
344 log(" }\n");
345 log("\n");
346 log("Where <port_details> is:\n");
347 log("\n");
348 log(" {\n");
349 log(" \"direction\": <\"input\" | \"output\" | \"inout\">,\n");
350 log(" \"bits\": <bit_vector>\n");
351 log(" \"offset\": <the lowest bit index in use, if non-0>\n");
352 log(" \"upto\": <1 if the port bit indexing is MSB-first>\n");
353 log(" }\n");
354 log("\n");
355 log("The \"offset\" and \"upto\" fields are skipped if their value would be 0.");
356 log("They don't affect connection semantics, and are only used to preserve original");
357 log("HDL bit indexing.");
358 log("And <cell_details> is:\n");
359 log("\n");
360 log(" {\n");
361 log(" \"hide_name\": <1 | 0>,\n");
362 log(" \"type\": <cell_type>,\n");
363 log(" \"model\": <AIG model name, if -aig option used>,\n");
364 log(" \"parameters\": {\n");
365 log(" <parameter_name>: <parameter_value>,\n");
366 log(" ...\n");
367 log(" },\n");
368 log(" \"attributes\": {\n");
369 log(" <attribute_name>: <attribute_value>,\n");
370 log(" ...\n");
371 log(" },\n");
372 log(" \"port_directions\": {\n");
373 log(" <port_name>: <\"input\" | \"output\" | \"inout\">,\n");
374 log(" ...\n");
375 log(" },\n");
376 log(" \"connections\": {\n");
377 log(" <port_name>: <bit_vector>,\n");
378 log(" ...\n");
379 log(" },\n");
380 log(" }\n");
381 log("\n");
382 log("And <net_details> is:\n");
383 log("\n");
384 log(" {\n");
385 log(" \"hide_name\": <1 | 0>,\n");
386 log(" \"bits\": <bit_vector>\n");
387 log(" \"offset\": <the lowest bit index in use, if non-0>\n");
388 log(" \"upto\": <1 if the port bit indexing is MSB-first>\n");
389 log(" }\n");
390 log("\n");
391 log("The \"hide_name\" fields are set to 1 when the name of this cell or net is\n");
392 log("automatically created and is likely not of interest for a regular user.\n");
393 log("\n");
394 log("The \"port_directions\" section is only included for cells for which the\n");
395 log("interface is known.\n");
396 log("\n");
397 log("Module and cell ports and nets can be single bit wide or vectors of multiple\n");
398 log("bits. Each individual signal bit is assigned a unique integer. The <bit_vector>\n");
399 log("values referenced above are vectors of this integers. Signal bits that are\n");
400 log("connected to a constant driver are denoted as string \"0\", \"1\", \"x\", or\n");
401 log("\"z\" instead of a number.\n");
402 log("\n");
403 log("Bit vectors (including integers) are written as string holding the binary");
404 log("representation of the value. Strings are written as strings, with an appended");
405 log("blank in cases of strings of the form /[01xz]* */.\n");
406 log("\n");
407 log("For example the following Verilog code:\n");
408 log("\n");
409 log(" module test(input x, y);\n");
410 log(" (* keep *) foo #(.P(42), .Q(1337))\n");
411 log(" foo_inst (.A({x, y}), .B({y, x}), .C({4'd10, {4{x}}}));\n");
412 log(" endmodule\n");
413 log("\n");
414 log("Translates to the following JSON output:\n");
415 log("\n");
416
417 log(" {\n");
418 log(" \"creator\": \"Yosys 0.9+2406 (git sha1 fb1168d8, clang 9.0.1 -fPIC -Os)\",\n");
419 log(" \"modules\": {\n");
420 log(" \"test\": {\n");
421 log(" \"attributes\": {\n");
422 log(" \"cells_not_processed\": \"00000000000000000000000000000001\",\n");
423 log(" \"src\": \"test.v:1.1-4.10\"\n");
424 log(" },\n");
425 log(" \"ports\": {\n");
426 log(" \"x\": {\n");
427 log(" \"direction\": \"input\",\n");
428 log(" \"bits\": [ 2 ]\n");
429 log(" },\n");
430 log(" \"y\": {\n");
431 log(" \"direction\": \"input\",\n");
432 log(" \"bits\": [ 3 ]\n");
433 log(" }\n");
434 log(" },\n");
435 log(" \"cells\": {\n");
436 log(" \"foo_inst\": {\n");
437 log(" \"hide_name\": 0,\n");
438 log(" \"type\": \"foo\",\n");
439 log(" \"parameters\": {\n");
440 log(" \"P\": \"00000000000000000000000000101010\",\n");
441 log(" \"Q\": \"00000000000000000000010100111001\"\n");
442 log(" },\n");
443 log(" \"attributes\": {\n");
444 log(" \"keep\": \"00000000000000000000000000000001\",\n");
445 log(" \"module_not_derived\": \"00000000000000000000000000000001\",\n");
446 log(" \"src\": \"test.v:3.1-3.55\"\n");
447 log(" },\n");
448 log(" \"connections\": {\n");
449 log(" \"A\": [ 3, 2 ],\n");
450 log(" \"B\": [ 2, 3 ],\n");
451 log(" \"C\": [ 2, 2, 2, 2, \"0\", \"1\", \"0\", \"1\" ]\n");
452 log(" }\n");
453 log(" }\n");
454 log(" },\n");
455 log(" \"netnames\": {\n");
456 log(" \"x\": {\n");
457 log(" \"hide_name\": 0,\n");
458 log(" \"bits\": [ 2 ],\n");
459 log(" \"attributes\": {\n");
460 log(" \"src\": \"test.v:1.19-1.20\"\n");
461 log(" }\n");
462 log(" },\n");
463 log(" \"y\": {\n");
464 log(" \"hide_name\": 0,\n");
465 log(" \"bits\": [ 3 ],\n");
466 log(" \"attributes\": {\n");
467 log(" \"src\": \"test.v:1.22-1.23\"\n");
468 log(" }\n");
469 log(" }\n");
470 log(" }\n");
471 log(" }\n");
472 log(" }\n");
473 log(" }\n");
474 log("\n");
475 log("The models are given as And-Inverter-Graphs (AIGs) in the following form:\n");
476 log("\n");
477 log(" \"models\": {\n");
478 log(" <model_name>: [\n");
479 log(" /* 0 */ [ <node-spec> ],\n");
480 log(" /* 1 */ [ <node-spec> ],\n");
481 log(" /* 2 */ [ <node-spec> ],\n");
482 log(" ...\n");
483 log(" ],\n");
484 log(" ...\n");
485 log(" },\n");
486 log("\n");
487 log("The following node-types may be used:\n");
488 log("\n");
489 log(" [ \"port\", <portname>, <bitindex>, <out-list> ]\n");
490 log(" - the value of the specified input port bit\n");
491 log("\n");
492 log(" [ \"nport\", <portname>, <bitindex>, <out-list> ]\n");
493 log(" - the inverted value of the specified input port bit\n");
494 log("\n");
495 log(" [ \"and\", <node-index>, <node-index>, <out-list> ]\n");
496 log(" - the ANDed value of the specified nodes\n");
497 log("\n");
498 log(" [ \"nand\", <node-index>, <node-index>, <out-list> ]\n");
499 log(" - the inverted ANDed value of the specified nodes\n");
500 log("\n");
501 log(" [ \"true\", <out-list> ]\n");
502 log(" - the constant value 1\n");
503 log("\n");
504 log(" [ \"false\", <out-list> ]\n");
505 log(" - the constant value 0\n");
506 log("\n");
507 log("All nodes appear in topological order. I.e. only nodes with smaller indices\n");
508 log("are referenced by \"and\" and \"nand\" nodes.\n");
509 log("\n");
510 log("The optional <out-list> at the end of a node specification is a list of\n");
511 log("output portname and bitindex pairs, specifying the outputs driven by this node.\n");
512 log("\n");
513 log("For example, the following is the model for a 3-input 3-output $reduce_and cell\n");
514 log("inferred by the following code:\n");
515 log("\n");
516 log(" module test(input [2:0] in, output [2:0] out);\n");
517 log(" assign in = &out;\n");
518 log(" endmodule\n");
519 log("\n");
520 log(" \"$reduce_and:3U:3\": [\n");
521 log(" /* 0 */ [ \"port\", \"A\", 0 ],\n");
522 log(" /* 1 */ [ \"port\", \"A\", 1 ],\n");
523 log(" /* 2 */ [ \"and\", 0, 1 ],\n");
524 log(" /* 3 */ [ \"port\", \"A\", 2 ],\n");
525 log(" /* 4 */ [ \"and\", 2, 3, \"Y\", 0 ],\n");
526 log(" /* 5 */ [ \"false\", \"Y\", 1, \"Y\", 2 ]\n");
527 log(" ]\n");
528 log("\n");
529 log("Future version of Yosys might add support for additional fields in the JSON\n");
530 log("format. A program processing this format must ignore all unknown fields.\n");
531 log("\n");
532 }
533 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
534 {
535 bool aig_mode = false;
536 bool compat_int_mode = false;
537
538 size_t argidx;
539 for (argidx = 1; argidx < args.size(); argidx++)
540 {
541 if (args[argidx] == "-aig") {
542 aig_mode = true;
543 continue;
544 }
545 if (args[argidx] == "-compat-int") {
546 compat_int_mode = true;
547 continue;
548 }
549 break;
550 }
551 extra_args(f, filename, args, argidx);
552
553 log_header(design, "Executing JSON backend.\n");
554
555 JsonWriter json_writer(*f, false, aig_mode, compat_int_mode);
556 json_writer.write_design(design);
557 }
558 } JsonBackend;
559
560 struct JsonPass : public Pass {
561 JsonPass() : Pass("json", "write design in JSON format") { }
562 void help() YS_OVERRIDE
563 {
564 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
565 log("\n");
566 log(" json [options] [selection]\n");
567 log("\n");
568 log("Write a JSON netlist of all selected objects.\n");
569 log("\n");
570 log(" -o <filename>\n");
571 log(" write to the specified file.\n");
572 log("\n");
573 log(" -aig\n");
574 log(" also include AIG models for the different gate types\n");
575 log("\n");
576 log(" -compat-int\n");
577 log(" emit 32-bit or smaller fully-defined parameter values directly\n");
578 log(" as JSON numbers (for compatibility with old parsers)\n");
579 log("\n");
580 log("See 'help write_json' for a description of the JSON format used.\n");
581 log("\n");
582 }
583 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
584 {
585 std::string filename;
586 bool aig_mode = false;
587 bool compat_int_mode = false;
588
589 size_t argidx;
590 for (argidx = 1; argidx < args.size(); argidx++)
591 {
592 if (args[argidx] == "-o" && argidx+1 < args.size()) {
593 filename = args[++argidx];
594 continue;
595 }
596 if (args[argidx] == "-aig") {
597 aig_mode = true;
598 continue;
599 }
600 if (args[argidx] == "-compat-int") {
601 compat_int_mode = true;
602 continue;
603 }
604 break;
605 }
606 extra_args(args, argidx, design);
607
608 std::ostream *f;
609 std::stringstream buf;
610
611 if (!filename.empty()) {
612 rewrite_filename(filename);
613 std::ofstream *ff = new std::ofstream;
614 ff->open(filename.c_str(), std::ofstream::trunc);
615 if (ff->fail()) {
616 delete ff;
617 log_error("Can't open file `%s' for writing: %s\n", filename.c_str(), strerror(errno));
618 }
619 f = ff;
620 } else {
621 f = &buf;
622 }
623
624 JsonWriter json_writer(*f, true, aig_mode, compat_int_mode);
625 json_writer.write_design(design);
626
627 if (!filename.empty()) {
628 delete f;
629 } else {
630 log("%s", buf.str().c_str());
631 }
632 }
633 } JsonPass;
634
635 PRIVATE_NAMESPACE_END