Merge remote-tracking branch 'origin/xc7mux' into xaig
[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 f << stringf(" \"attributes\": {");
193 write_parameters(w->attributes);
194 f << stringf("\n }\n");
195 f << stringf(" }");
196 first = false;
197 }
198 f << stringf("\n }\n");
199
200 f << stringf(" }");
201 }
202
203 void write_design(Design *design_)
204 {
205 design = design_;
206 design->sort();
207
208 f << stringf("{\n");
209 f << stringf(" \"creator\": %s,\n", get_string(yosys_version_str).c_str());
210 f << stringf(" \"modules\": {\n");
211 vector<Module*> modules = use_selection ? design->selected_modules() : design->modules();
212 bool first_module = true;
213 for (auto mod : modules) {
214 if (!first_module)
215 f << stringf(",\n");
216 write_module(mod);
217 first_module = false;
218 }
219 f << stringf("\n }");
220 if (!aig_models.empty()) {
221 f << stringf(",\n \"models\": {\n");
222 bool first_model = true;
223 for (auto &aig : aig_models) {
224 if (!first_model)
225 f << stringf(",\n");
226 f << stringf(" \"%s\": [\n", aig.name.c_str());
227 int node_idx = 0;
228 for (auto &node : aig.nodes) {
229 if (node_idx != 0)
230 f << stringf(",\n");
231 f << stringf(" /* %3d */ [ ", node_idx);
232 if (node.portbit >= 0)
233 f << stringf("\"%sport\", \"%s\", %d", node.inverter ? "n" : "",
234 log_id(node.portname), node.portbit);
235 else if (node.left_parent < 0 && node.right_parent < 0)
236 f << stringf("\"%s\"", node.inverter ? "true" : "false");
237 else
238 f << stringf("\"%s\", %d, %d", node.inverter ? "nand" : "and", node.left_parent, node.right_parent);
239 for (auto &op : node.outports)
240 f << stringf(", \"%s\", %d", log_id(op.first), op.second);
241 f << stringf(" ]");
242 node_idx++;
243 }
244 f << stringf("\n ]");
245 first_model = false;
246 }
247 f << stringf("\n }");
248 }
249 f << stringf("\n}\n");
250 }
251 };
252
253 struct JsonBackend : public Backend {
254 JsonBackend() : Backend("json", "write design to a JSON file") { }
255 void help() YS_OVERRIDE
256 {
257 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
258 log("\n");
259 log(" write_json [options] [filename]\n");
260 log("\n");
261 log("Write a JSON netlist of the current design.\n");
262 log("\n");
263 log(" -aig\n");
264 log(" include AIG models for the different gate types\n");
265 log("\n");
266 log("\n");
267 log("The general syntax of the JSON output created by this command is as follows:\n");
268 log("\n");
269 log(" {\n");
270 log(" \"modules\": {\n");
271 log(" <module_name>: {\n");
272 log(" \"ports\": {\n");
273 log(" <port_name>: <port_details>,\n");
274 log(" ...\n");
275 log(" },\n");
276 log(" \"cells\": {\n");
277 log(" <cell_name>: <cell_details>,\n");
278 log(" ...\n");
279 log(" },\n");
280 log(" \"netnames\": {\n");
281 log(" <net_name>: <net_details>,\n");
282 log(" ...\n");
283 log(" }\n");
284 log(" }\n");
285 log(" },\n");
286 log(" \"models\": {\n");
287 log(" ...\n");
288 log(" },\n");
289 log(" }\n");
290 log("\n");
291 log("Where <port_details> is:\n");
292 log("\n");
293 log(" {\n");
294 log(" \"direction\": <\"input\" | \"output\" | \"inout\">,\n");
295 log(" \"bits\": <bit_vector>\n");
296 log(" }\n");
297 log("\n");
298 log("And <cell_details> is:\n");
299 log("\n");
300 log(" {\n");
301 log(" \"hide_name\": <1 | 0>,\n");
302 log(" \"type\": <cell_type>,\n");
303 log(" \"parameters\": {\n");
304 log(" <parameter_name>: <parameter_value>,\n");
305 log(" ...\n");
306 log(" },\n");
307 log(" \"attributes\": {\n");
308 log(" <attribute_name>: <attribute_value>,\n");
309 log(" ...\n");
310 log(" },\n");
311 log(" \"port_directions\": {\n");
312 log(" <port_name>: <\"input\" | \"output\" | \"inout\">,\n");
313 log(" ...\n");
314 log(" },\n");
315 log(" \"connections\": {\n");
316 log(" <port_name>: <bit_vector>,\n");
317 log(" ...\n");
318 log(" },\n");
319 log(" }\n");
320 log("\n");
321 log("And <net_details> is:\n");
322 log("\n");
323 log(" {\n");
324 log(" \"hide_name\": <1 | 0>,\n");
325 log(" \"bits\": <bit_vector>\n");
326 log(" }\n");
327 log("\n");
328 log("The \"hide_name\" fields are set to 1 when the name of this cell or net is\n");
329 log("automatically created and is likely not of interest for a regular user.\n");
330 log("\n");
331 log("The \"port_directions\" section is only included for cells for which the\n");
332 log("interface is known.\n");
333 log("\n");
334 log("Module and cell ports and nets can be single bit wide or vectors of multiple\n");
335 log("bits. Each individual signal bit is assigned a unique integer. The <bit_vector>\n");
336 log("values referenced above are vectors of this integers. Signal bits that are\n");
337 log("connected to a constant driver are denoted as string \"0\" or \"1\" instead of\n");
338 log("a number.\n");
339 log("\n");
340 log("Numeric parameter and attribute values up to 32 bits are written as decimal\n");
341 log("values. Numbers larger than that are written as string holding the binary\n");
342 log("representation of the value.\n");
343 log("\n");
344 log("For example the following Verilog code:\n");
345 log("\n");
346 log(" module test(input x, y);\n");
347 log(" (* keep *) foo #(.P(42), .Q(1337))\n");
348 log(" foo_inst (.A({x, y}), .B({y, x}), .C({4'd10, {4{x}}}));\n");
349 log(" endmodule\n");
350 log("\n");
351 log("Translates to the following JSON output:\n");
352 log("\n");
353 log(" {\n");
354 log(" \"modules\": {\n");
355 log(" \"test\": {\n");
356 log(" \"ports\": {\n");
357 log(" \"x\": {\n");
358 log(" \"direction\": \"input\",\n");
359 log(" \"bits\": [ 2 ]\n");
360 log(" },\n");
361 log(" \"y\": {\n");
362 log(" \"direction\": \"input\",\n");
363 log(" \"bits\": [ 3 ]\n");
364 log(" }\n");
365 log(" },\n");
366 log(" \"cells\": {\n");
367 log(" \"foo_inst\": {\n");
368 log(" \"hide_name\": 0,\n");
369 log(" \"type\": \"foo\",\n");
370 log(" \"parameters\": {\n");
371 log(" \"Q\": 1337,\n");
372 log(" \"P\": 42\n");
373 log(" },\n");
374 log(" \"attributes\": {\n");
375 log(" \"keep\": 1,\n");
376 log(" \"src\": \"test.v:2\"\n");
377 log(" },\n");
378 log(" \"connections\": {\n");
379 log(" \"C\": [ 2, 2, 2, 2, \"0\", \"1\", \"0\", \"1\" ],\n");
380 log(" \"B\": [ 2, 3 ],\n");
381 log(" \"A\": [ 3, 2 ]\n");
382 log(" }\n");
383 log(" }\n");
384 log(" },\n");
385 log(" \"netnames\": {\n");
386 log(" \"y\": {\n");
387 log(" \"hide_name\": 0,\n");
388 log(" \"bits\": [ 3 ],\n");
389 log(" \"attributes\": {\n");
390 log(" \"src\": \"test.v:1\"\n");
391 log(" }\n");
392 log(" },\n");
393 log(" \"x\": {\n");
394 log(" \"hide_name\": 0,\n");
395 log(" \"bits\": [ 2 ],\n");
396 log(" \"attributes\": {\n");
397 log(" \"src\": \"test.v:1\"\n");
398 log(" }\n");
399 log(" }\n");
400 log(" }\n");
401 log(" }\n");
402 log(" }\n");
403 log(" }\n");
404 log("\n");
405 log("The models are given as And-Inverter-Graphs (AIGs) in the following form:\n");
406 log("\n");
407 log(" \"models\": {\n");
408 log(" <model_name>: [\n");
409 log(" /* 0 */ [ <node-spec> ],\n");
410 log(" /* 1 */ [ <node-spec> ],\n");
411 log(" /* 2 */ [ <node-spec> ],\n");
412 log(" ...\n");
413 log(" ],\n");
414 log(" ...\n");
415 log(" },\n");
416 log("\n");
417 log("The following node-types may be used:\n");
418 log("\n");
419 log(" [ \"port\", <portname>, <bitindex>, <out-list> ]\n");
420 log(" - the value of the specified input port bit\n");
421 log("\n");
422 log(" [ \"nport\", <portname>, <bitindex>, <out-list> ]\n");
423 log(" - the inverted value of the specified input port bit\n");
424 log("\n");
425 log(" [ \"and\", <node-index>, <node-index>, <out-list> ]\n");
426 log(" - the ANDed value of the specified nodes\n");
427 log("\n");
428 log(" [ \"nand\", <node-index>, <node-index>, <out-list> ]\n");
429 log(" - the inverted ANDed value of the specified nodes\n");
430 log("\n");
431 log(" [ \"true\", <out-list> ]\n");
432 log(" - the constant value 1\n");
433 log("\n");
434 log(" [ \"false\", <out-list> ]\n");
435 log(" - the constant value 0\n");
436 log("\n");
437 log("All nodes appear in topological order. I.e. only nodes with smaller indices\n");
438 log("are referenced by \"and\" and \"nand\" nodes.\n");
439 log("\n");
440 log("The optional <out-list> at the end of a node specification is a list of\n");
441 log("output portname and bitindex pairs, specifying the outputs driven by this node.\n");
442 log("\n");
443 log("For example, the following is the model for a 3-input 3-output $reduce_and cell\n");
444 log("inferred by the following code:\n");
445 log("\n");
446 log(" module test(input [2:0] in, output [2:0] out);\n");
447 log(" assign in = &out;\n");
448 log(" endmodule\n");
449 log("\n");
450 log(" \"$reduce_and:3U:3\": [\n");
451 log(" /* 0 */ [ \"port\", \"A\", 0 ],\n");
452 log(" /* 1 */ [ \"port\", \"A\", 1 ],\n");
453 log(" /* 2 */ [ \"and\", 0, 1 ],\n");
454 log(" /* 3 */ [ \"port\", \"A\", 2 ],\n");
455 log(" /* 4 */ [ \"and\", 2, 3, \"Y\", 0 ],\n");
456 log(" /* 5 */ [ \"false\", \"Y\", 1, \"Y\", 2 ]\n");
457 log(" ]\n");
458 log("\n");
459 log("Future version of Yosys might add support for additional fields in the JSON\n");
460 log("format. A program processing this format must ignore all unknown fields.\n");
461 log("\n");
462 }
463 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
464 {
465 bool aig_mode = false;
466
467 size_t argidx;
468 for (argidx = 1; argidx < args.size(); argidx++)
469 {
470 if (args[argidx] == "-aig") {
471 aig_mode = true;
472 continue;
473 }
474 break;
475 }
476 extra_args(f, filename, args, argidx);
477
478 log_header(design, "Executing JSON backend.\n");
479
480 JsonWriter json_writer(*f, false, aig_mode);
481 json_writer.write_design(design);
482 }
483 } JsonBackend;
484
485 struct JsonPass : public Pass {
486 JsonPass() : Pass("json", "write design in JSON format") { }
487 void help() YS_OVERRIDE
488 {
489 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
490 log("\n");
491 log(" json [options] [selection]\n");
492 log("\n");
493 log("Write a JSON netlist of all selected objects.\n");
494 log("\n");
495 log(" -o <filename>\n");
496 log(" write to the specified file.\n");
497 log("\n");
498 log(" -aig\n");
499 log(" also include AIG models for the different gate types\n");
500 log("\n");
501 log("See 'help write_json' for a description of the JSON format used.\n");
502 log("\n");
503 }
504 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
505 {
506 std::string filename;
507 bool aig_mode = false;
508
509 size_t argidx;
510 for (argidx = 1; argidx < args.size(); argidx++)
511 {
512 if (args[argidx] == "-o" && argidx+1 < args.size()) {
513 filename = args[++argidx];
514 continue;
515 }
516 if (args[argidx] == "-aig") {
517 aig_mode = true;
518 continue;
519 }
520 break;
521 }
522 extra_args(args, argidx, design);
523
524 std::ostream *f;
525 std::stringstream buf;
526
527 if (!filename.empty()) {
528 std::ofstream *ff = new std::ofstream;
529 ff->open(filename.c_str(), std::ofstream::trunc);
530 if (ff->fail()) {
531 delete ff;
532 log_error("Can't open file `%s' for writing: %s\n", filename.c_str(), strerror(errno));
533 }
534 f = ff;
535 } else {
536 f = &buf;
537 }
538
539 JsonWriter json_writer(*f, true, aig_mode);
540 json_writer.write_design(design);
541
542 if (!filename.empty()) {
543 delete f;
544 } else {
545 log("%s", buf.str().c_str());
546 }
547 }
548 } JsonPass;
549
550 PRIVATE_NAMESPACE_END