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