Merge remote-tracking branch 'origin/master' into eddie/muxpack
[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
37 Design *design;
38 Module *module;
39
40 SigMap sigmap;
41 int sigidcounter;
42 dict<SigBit, string> sigids;
43 pool<Aig> aig_models;
44
45 JsonWriter(std::ostream &f, bool use_selection, bool aig_mode) :
46 f(f), use_selection(use_selection), aig_mode(aig_mode) { }
47
48 string get_string(string str)
49 {
50 string newstr = "\"";
51 for (char c : str) {
52 if (c == '\\')
53 newstr += c;
54 newstr += c;
55 }
56 return newstr + "\"";
57 }
58
59 string get_name(IdString name)
60 {
61 return get_string(RTLIL::unescape_id(name));
62 }
63
64 string get_bits(SigSpec sig)
65 {
66 bool first = true;
67 string str = "[";
68 for (auto bit : sigmap(sig)) {
69 str += first ? " " : ", ";
70 first = false;
71 if (sigids.count(bit) == 0) {
72 string &s = sigids[bit];
73 if (bit.wire == nullptr) {
74 if (bit == State::S0) s = "\"0\"";
75 else if (bit == State::S1) s = "\"1\"";
76 else if (bit == State::Sz) s = "\"z\"";
77 else s = "\"x\"";
78 } else
79 s = stringf("%d", sigidcounter++);
80 }
81 str += sigids[bit];
82 }
83 return str + " ]";
84 }
85
86 void write_parameters(const dict<IdString, Const> &parameters, bool for_module=false)
87 {
88 bool first = true;
89 for (auto &param : parameters) {
90 f << stringf("%s\n", first ? "" : ",");
91 f << stringf(" %s%s: ", for_module ? "" : " ", get_name(param.first).c_str());
92 if ((param.second.flags & RTLIL::ConstFlags::CONST_FLAG_STRING) != 0)
93 f << get_string(param.second.decode_string());
94 else if (GetSize(param.second.bits) > 32)
95 f << get_string(param.second.as_string());
96 else if ((param.second.flags & RTLIL::ConstFlags::CONST_FLAG_SIGNED) != 0)
97 f << stringf("%d", param.second.as_int());
98 else
99 f << stringf("%u", param.second.as_int());
100 first = false;
101 }
102 }
103
104 void write_module(Module *module_)
105 {
106 module = module_;
107 log_assert(module->design == design);
108 sigmap.set(module);
109 sigids.clear();
110
111 // reserve 0 and 1 to avoid confusion with "0" and "1"
112 sigidcounter = 2;
113
114 f << stringf(" %s: {\n", get_name(module->name).c_str());
115
116 f << stringf(" \"attributes\": {");
117 write_parameters(module->attributes, /*for_module=*/true);
118 f << stringf("\n },\n");
119
120 f << stringf(" \"ports\": {");
121 bool first = true;
122 for (auto n : module->ports) {
123 Wire *w = module->wire(n);
124 if (use_selection && !module->selected(w))
125 continue;
126 f << stringf("%s\n", first ? "" : ",");
127 f << stringf(" %s: {\n", get_name(n).c_str());
128 f << stringf(" \"direction\": \"%s\",\n", w->port_input ? w->port_output ? "inout" : "input" : "output");
129 f << stringf(" \"bits\": %s\n", get_bits(w).c_str());
130 f << stringf(" }");
131 first = false;
132 }
133 f << stringf("\n },\n");
134
135 f << stringf(" \"cells\": {");
136 first = true;
137 for (auto c : module->cells()) {
138 if (use_selection && !module->selected(c))
139 continue;
140 f << stringf("%s\n", first ? "" : ",");
141 f << stringf(" %s: {\n", get_name(c->name).c_str());
142 f << stringf(" \"hide_name\": %s,\n", c->name[0] == '$' ? "1" : "0");
143 f << stringf(" \"type\": %s,\n", get_name(c->type).c_str());
144 if (aig_mode) {
145 Aig aig(c);
146 if (!aig.name.empty()) {
147 f << stringf(" \"model\": \"%s\",\n", aig.name.c_str());
148 aig_models.insert(aig);
149 }
150 }
151 f << stringf(" \"parameters\": {");
152 write_parameters(c->parameters);
153 f << stringf("\n },\n");
154 f << stringf(" \"attributes\": {");
155 write_parameters(c->attributes);
156 f << stringf("\n },\n");
157 if (c->known()) {
158 f << stringf(" \"port_directions\": {");
159 bool first2 = true;
160 for (auto &conn : c->connections()) {
161 string direction = "output";
162 if (c->input(conn.first))
163 direction = c->output(conn.first) ? "inout" : "input";
164 f << stringf("%s\n", first2 ? "" : ",");
165 f << stringf(" %s: \"%s\"", get_name(conn.first).c_str(), direction.c_str());
166 first2 = false;
167 }
168 f << stringf("\n },\n");
169 }
170 f << stringf(" \"connections\": {");
171 bool first2 = true;
172 for (auto &conn : c->connections()) {
173 f << stringf("%s\n", first2 ? "" : ",");
174 f << stringf(" %s: %s", get_name(conn.first).c_str(), get_bits(conn.second).c_str());
175 first2 = false;
176 }
177 f << stringf("\n }\n");
178 f << stringf(" }");
179 first = false;
180 }
181 f << stringf("\n },\n");
182
183 f << stringf(" \"netnames\": {");
184 first = true;
185 for (auto w : module->wires()) {
186 if (use_selection && !module->selected(w))
187 continue;
188 f << stringf("%s\n", first ? "" : ",");
189 f << stringf(" %s: {\n", get_name(w->name).c_str());
190 f << stringf(" \"hide_name\": %s,\n", w->name[0] == '$' ? "1" : "0");
191 f << stringf(" \"bits\": %s,\n", get_bits(w).c_str());
192 if (w->start_offset)
193 f << stringf(" \"offset\": %d,\n", w->start_offset);
194 if (w->upto)
195 f << stringf(" \"upto\": 1,\n");
196 f << stringf(" \"attributes\": {");
197 write_parameters(w->attributes);
198 f << stringf("\n }\n");
199 f << stringf(" }");
200 first = false;
201 }
202 f << stringf("\n }\n");
203
204 f << stringf(" }");
205 }
206
207 void write_design(Design *design_)
208 {
209 design = design_;
210 design->sort();
211
212 f << stringf("{\n");
213 f << stringf(" \"creator\": %s,\n", get_string(yosys_version_str).c_str());
214 f << stringf(" \"modules\": {\n");
215 vector<Module*> modules = use_selection ? design->selected_modules() : design->modules();
216 bool first_module = true;
217 for (auto mod : modules) {
218 if (!first_module)
219 f << stringf(",\n");
220 write_module(mod);
221 first_module = false;
222 }
223 f << stringf("\n }");
224 if (!aig_models.empty()) {
225 f << stringf(",\n \"models\": {\n");
226 bool first_model = true;
227 for (auto &aig : aig_models) {
228 if (!first_model)
229 f << stringf(",\n");
230 f << stringf(" \"%s\": [\n", aig.name.c_str());
231 int node_idx = 0;
232 for (auto &node : aig.nodes) {
233 if (node_idx != 0)
234 f << stringf(",\n");
235 f << stringf(" /* %3d */ [ ", node_idx);
236 if (node.portbit >= 0)
237 f << stringf("\"%sport\", \"%s\", %d", node.inverter ? "n" : "",
238 log_id(node.portname), node.portbit);
239 else if (node.left_parent < 0 && node.right_parent < 0)
240 f << stringf("\"%s\"", node.inverter ? "true" : "false");
241 else
242 f << stringf("\"%s\", %d, %d", node.inverter ? "nand" : "and", node.left_parent, node.right_parent);
243 for (auto &op : node.outports)
244 f << stringf(", \"%s\", %d", log_id(op.first), op.second);
245 f << stringf(" ]");
246 node_idx++;
247 }
248 f << stringf("\n ]");
249 first_model = false;
250 }
251 f << stringf("\n }");
252 }
253 f << stringf("\n}\n");
254 }
255 };
256
257 struct JsonBackend : public Backend {
258 JsonBackend() : Backend("json", "write design to a JSON file") { }
259 void help() YS_OVERRIDE
260 {
261 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
262 log("\n");
263 log(" write_json [options] [filename]\n");
264 log("\n");
265 log("Write a JSON netlist of the current design.\n");
266 log("\n");
267 log(" -aig\n");
268 log(" include AIG models for the different gate types\n");
269 log("\n");
270 log("\n");
271 log("The general syntax of the JSON output created by this command is as follows:\n");
272 log("\n");
273 log(" {\n");
274 log(" \"modules\": {\n");
275 log(" <module_name>: {\n");
276 log(" \"ports\": {\n");
277 log(" <port_name>: <port_details>,\n");
278 log(" ...\n");
279 log(" },\n");
280 log(" \"cells\": {\n");
281 log(" <cell_name>: <cell_details>,\n");
282 log(" ...\n");
283 log(" },\n");
284 log(" \"netnames\": {\n");
285 log(" <net_name>: <net_details>,\n");
286 log(" ...\n");
287 log(" }\n");
288 log(" }\n");
289 log(" },\n");
290 log(" \"models\": {\n");
291 log(" ...\n");
292 log(" },\n");
293 log(" }\n");
294 log("\n");
295 log("Where <port_details> is:\n");
296 log("\n");
297 log(" {\n");
298 log(" \"direction\": <\"input\" | \"output\" | \"inout\">,\n");
299 log(" \"bits\": <bit_vector>\n");
300 log(" }\n");
301 log("\n");
302 log("And <cell_details> is:\n");
303 log("\n");
304 log(" {\n");
305 log(" \"hide_name\": <1 | 0>,\n");
306 log(" \"type\": <cell_type>,\n");
307 log(" \"parameters\": {\n");
308 log(" <parameter_name>: <parameter_value>,\n");
309 log(" ...\n");
310 log(" },\n");
311 log(" \"attributes\": {\n");
312 log(" <attribute_name>: <attribute_value>,\n");
313 log(" ...\n");
314 log(" },\n");
315 log(" \"port_directions\": {\n");
316 log(" <port_name>: <\"input\" | \"output\" | \"inout\">,\n");
317 log(" ...\n");
318 log(" },\n");
319 log(" \"connections\": {\n");
320 log(" <port_name>: <bit_vector>,\n");
321 log(" ...\n");
322 log(" },\n");
323 log(" }\n");
324 log("\n");
325 log("And <net_details> is:\n");
326 log("\n");
327 log(" {\n");
328 log(" \"hide_name\": <1 | 0>,\n");
329 log(" \"bits\": <bit_vector>\n");
330 log(" }\n");
331 log("\n");
332 log("The \"hide_name\" fields are set to 1 when the name of this cell or net is\n");
333 log("automatically created and is likely not of interest for a regular user.\n");
334 log("\n");
335 log("The \"port_directions\" section is only included for cells for which the\n");
336 log("interface is known.\n");
337 log("\n");
338 log("Module and cell ports and nets can be single bit wide or vectors of multiple\n");
339 log("bits. Each individual signal bit is assigned a unique integer. The <bit_vector>\n");
340 log("values referenced above are vectors of this integers. Signal bits that are\n");
341 log("connected to a constant driver are denoted as string \"0\" or \"1\" instead of\n");
342 log("a number.\n");
343 log("\n");
344 log("Numeric parameter and attribute values up to 32 bits are written as decimal\n");
345 log("values. Numbers larger than that are written as string holding the binary\n");
346 log("representation of the value.\n");
347 log("\n");
348 log("For example the following Verilog code:\n");
349 log("\n");
350 log(" module test(input x, y);\n");
351 log(" (* keep *) foo #(.P(42), .Q(1337))\n");
352 log(" foo_inst (.A({x, y}), .B({y, x}), .C({4'd10, {4{x}}}));\n");
353 log(" endmodule\n");
354 log("\n");
355 log("Translates to the following JSON output:\n");
356 log("\n");
357 log(" {\n");
358 log(" \"modules\": {\n");
359 log(" \"test\": {\n");
360 log(" \"ports\": {\n");
361 log(" \"x\": {\n");
362 log(" \"direction\": \"input\",\n");
363 log(" \"bits\": [ 2 ]\n");
364 log(" },\n");
365 log(" \"y\": {\n");
366 log(" \"direction\": \"input\",\n");
367 log(" \"bits\": [ 3 ]\n");
368 log(" }\n");
369 log(" },\n");
370 log(" \"cells\": {\n");
371 log(" \"foo_inst\": {\n");
372 log(" \"hide_name\": 0,\n");
373 log(" \"type\": \"foo\",\n");
374 log(" \"parameters\": {\n");
375 log(" \"Q\": 1337,\n");
376 log(" \"P\": 42\n");
377 log(" },\n");
378 log(" \"attributes\": {\n");
379 log(" \"keep\": 1,\n");
380 log(" \"src\": \"test.v:2\"\n");
381 log(" },\n");
382 log(" \"connections\": {\n");
383 log(" \"C\": [ 2, 2, 2, 2, \"0\", \"1\", \"0\", \"1\" ],\n");
384 log(" \"B\": [ 2, 3 ],\n");
385 log(" \"A\": [ 3, 2 ]\n");
386 log(" }\n");
387 log(" }\n");
388 log(" },\n");
389 log(" \"netnames\": {\n");
390 log(" \"y\": {\n");
391 log(" \"hide_name\": 0,\n");
392 log(" \"bits\": [ 3 ],\n");
393 log(" \"attributes\": {\n");
394 log(" \"src\": \"test.v:1\"\n");
395 log(" }\n");
396 log(" },\n");
397 log(" \"x\": {\n");
398 log(" \"hide_name\": 0,\n");
399 log(" \"bits\": [ 2 ],\n");
400 log(" \"attributes\": {\n");
401 log(" \"src\": \"test.v:1\"\n");
402 log(" }\n");
403 log(" }\n");
404 log(" }\n");
405 log(" }\n");
406 log(" }\n");
407 log(" }\n");
408 log("\n");
409 log("The models are given as And-Inverter-Graphs (AIGs) in the following form:\n");
410 log("\n");
411 log(" \"models\": {\n");
412 log(" <model_name>: [\n");
413 log(" /* 0 */ [ <node-spec> ],\n");
414 log(" /* 1 */ [ <node-spec> ],\n");
415 log(" /* 2 */ [ <node-spec> ],\n");
416 log(" ...\n");
417 log(" ],\n");
418 log(" ...\n");
419 log(" },\n");
420 log("\n");
421 log("The following node-types may be used:\n");
422 log("\n");
423 log(" [ \"port\", <portname>, <bitindex>, <out-list> ]\n");
424 log(" - the value of the specified input port bit\n");
425 log("\n");
426 log(" [ \"nport\", <portname>, <bitindex>, <out-list> ]\n");
427 log(" - the inverted value of the specified input port bit\n");
428 log("\n");
429 log(" [ \"and\", <node-index>, <node-index>, <out-list> ]\n");
430 log(" - the ANDed value of the specified nodes\n");
431 log("\n");
432 log(" [ \"nand\", <node-index>, <node-index>, <out-list> ]\n");
433 log(" - the inverted ANDed value of the specified nodes\n");
434 log("\n");
435 log(" [ \"true\", <out-list> ]\n");
436 log(" - the constant value 1\n");
437 log("\n");
438 log(" [ \"false\", <out-list> ]\n");
439 log(" - the constant value 0\n");
440 log("\n");
441 log("All nodes appear in topological order. I.e. only nodes with smaller indices\n");
442 log("are referenced by \"and\" and \"nand\" nodes.\n");
443 log("\n");
444 log("The optional <out-list> at the end of a node specification is a list of\n");
445 log("output portname and bitindex pairs, specifying the outputs driven by this node.\n");
446 log("\n");
447 log("For example, the following is the model for a 3-input 3-output $reduce_and cell\n");
448 log("inferred by the following code:\n");
449 log("\n");
450 log(" module test(input [2:0] in, output [2:0] out);\n");
451 log(" assign in = &out;\n");
452 log(" endmodule\n");
453 log("\n");
454 log(" \"$reduce_and:3U:3\": [\n");
455 log(" /* 0 */ [ \"port\", \"A\", 0 ],\n");
456 log(" /* 1 */ [ \"port\", \"A\", 1 ],\n");
457 log(" /* 2 */ [ \"and\", 0, 1 ],\n");
458 log(" /* 3 */ [ \"port\", \"A\", 2 ],\n");
459 log(" /* 4 */ [ \"and\", 2, 3, \"Y\", 0 ],\n");
460 log(" /* 5 */ [ \"false\", \"Y\", 1, \"Y\", 2 ]\n");
461 log(" ]\n");
462 log("\n");
463 log("Future version of Yosys might add support for additional fields in the JSON\n");
464 log("format. A program processing this format must ignore all unknown fields.\n");
465 log("\n");
466 }
467 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
468 {
469 bool aig_mode = false;
470
471 size_t argidx;
472 for (argidx = 1; argidx < args.size(); argidx++)
473 {
474 if (args[argidx] == "-aig") {
475 aig_mode = true;
476 continue;
477 }
478 break;
479 }
480 extra_args(f, filename, args, argidx);
481
482 log_header(design, "Executing JSON backend.\n");
483
484 JsonWriter json_writer(*f, false, aig_mode);
485 json_writer.write_design(design);
486 }
487 } JsonBackend;
488
489 struct JsonPass : public Pass {
490 JsonPass() : Pass("json", "write design in JSON format") { }
491 void help() YS_OVERRIDE
492 {
493 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
494 log("\n");
495 log(" json [options] [selection]\n");
496 log("\n");
497 log("Write a JSON netlist of all selected objects.\n");
498 log("\n");
499 log(" -o <filename>\n");
500 log(" write to the specified file.\n");
501 log("\n");
502 log(" -aig\n");
503 log(" also include AIG models for the different gate types\n");
504 log("\n");
505 log("See 'help write_json' for a description of the JSON format used.\n");
506 log("\n");
507 }
508 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
509 {
510 std::string filename;
511 bool aig_mode = false;
512
513 size_t argidx;
514 for (argidx = 1; argidx < args.size(); argidx++)
515 {
516 if (args[argidx] == "-o" && argidx+1 < args.size()) {
517 filename = args[++argidx];
518 continue;
519 }
520 if (args[argidx] == "-aig") {
521 aig_mode = true;
522 continue;
523 }
524 break;
525 }
526 extra_args(args, argidx, design);
527
528 std::ostream *f;
529 std::stringstream buf;
530
531 if (!filename.empty()) {
532 rewrite_filename(filename);
533 std::ofstream *ff = new std::ofstream;
534 ff->open(filename.c_str(), std::ofstream::trunc);
535 if (ff->fail()) {
536 delete ff;
537 log_error("Can't open file `%s' for writing: %s\n", filename.c_str(), strerror(errno));
538 }
539 f = ff;
540 } else {
541 f = &buf;
542 }
543
544 JsonWriter json_writer(*f, true, aig_mode);
545 json_writer.write_design(design);
546
547 if (!filename.empty()) {
548 delete f;
549 } else {
550 log("%s", buf.str().c_str());
551 }
552 }
553 } JsonPass;
554
555 PRIVATE_NAMESPACE_END