Tidy up write_xaiger
[yosys.git] / backends / aiger / xaiger.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/yosys.h"
21 #include "kernel/sigtools.h"
22
23 USING_YOSYS_NAMESPACE
24 PRIVATE_NAMESPACE_BEGIN
25
26 void aiger_encode(std::ostream &f, int x)
27 {
28 log_assert(x >= 0);
29
30 while (x & ~0x7f) {
31 f.put((x & 0x7f) | 0x80);
32 x = x >> 7;
33 }
34
35 f.put(x);
36 }
37
38 struct XAigerWriter
39 {
40 Module *module;
41 bool zinit_mode;
42 SigMap sigmap;
43
44 dict<SigBit, bool> init_map;
45 pool<SigBit> input_bits, output_bits;
46 dict<SigBit, SigBit> not_map, ff_map, alias_map;
47 dict<SigBit, pair<SigBit, SigBit>> and_map;
48 pool<SigBit> initstate_bits;
49 pool<SigBit> ci_bits, co_bits;
50 dict<IdString, unsigned> type_map;
51
52 vector<pair<int, int>> aig_gates;
53 vector<int> aig_latchin, aig_latchinit, aig_outputs;
54 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
55
56 dict<SigBit, int> aig_map;
57 dict<SigBit, int> ordered_outputs;
58 dict<SigBit, int> ordered_latches;
59
60 dict<SigBit, int> init_inputs;
61 int initstate_ff = 0;
62
63 int mkgate(int a0, int a1)
64 {
65 aig_m++, aig_a++;
66 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
67 return 2*aig_m;
68 }
69
70 int bit2aig(SigBit bit)
71 {
72 if (aig_map.count(bit) == 0)
73 {
74 aig_map[bit] = -1;
75
76 if (initstate_bits.count(bit)) {
77 log_assert(initstate_ff > 0);
78 aig_map[bit] = initstate_ff;
79 } else
80 if (not_map.count(bit)) {
81 int a = bit2aig(not_map.at(bit)) ^ 1;
82 aig_map[bit] = a;
83 } else
84 if (and_map.count(bit)) {
85 auto args = and_map.at(bit);
86 int a0 = bit2aig(args.first);
87 int a1 = bit2aig(args.second);
88 aig_map[bit] = mkgate(a0, a1);
89 } else
90 if (alias_map.count(bit)) {
91 aig_map[bit] = bit2aig(alias_map.at(bit));
92 }
93
94 if (bit == State::Sx || bit == State::Sz)
95 log_error("Design contains 'x' or 'z' bits. Use 'setundef' to replace those constants.\n");
96 }
97
98 log_assert(aig_map.at(bit) >= 0);
99 return aig_map.at(bit);
100 }
101
102 XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode) : module(module), zinit_mode(zinit_mode), sigmap(module)
103 {
104 pool<SigBit> undriven_bits;
105 pool<SigBit> unused_bits;
106
107 // promote public wires
108 for (auto wire : module->wires())
109 if (wire->name[0] == '\\')
110 sigmap.add(wire);
111
112 // promote input wires
113 for (auto wire : module->wires())
114 if (wire->port_input)
115 sigmap.add(wire);
116
117 // promote output wires
118 for (auto wire : module->wires())
119 if (wire->port_output)
120 sigmap.add(wire);
121
122 for (auto wire : module->wires())
123 {
124 if (wire->attributes.count("\\init")) {
125 SigSpec initsig = sigmap(wire);
126 Const initval = wire->attributes.at("\\init");
127 for (int i = 0; i < GetSize(wire) && i < GetSize(initval); i++)
128 if (initval[i] == State::S0 || initval[i] == State::S1)
129 init_map[initsig[i]] = initval[i] == State::S1;
130 }
131
132 for (int i = 0; i < GetSize(wire); i++)
133 {
134 SigBit wirebit(wire, i);
135 SigBit bit = sigmap(wirebit);
136
137 if (bit.wire == nullptr) {
138 if (wire->port_output) {
139 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
140 output_bits.insert(wirebit);
141 }
142 continue;
143 }
144
145 undriven_bits.insert(bit);
146 unused_bits.insert(bit);
147
148 if (wire->port_input)
149 input_bits.insert(bit);
150
151 if (wire->port_output) {
152 if (bit != wirebit)
153 alias_map[wirebit] = bit;
154 output_bits.insert(wirebit);
155 }
156 }
157 }
158
159 for (auto bit : input_bits)
160 undriven_bits.erase(bit);
161
162 for (auto bit : output_bits)
163 unused_bits.erase(bit);
164
165 for (auto cell : module->cells())
166 {
167 if (cell->type == "$_NOT_")
168 {
169 SigBit A = sigmap(cell->getPort("\\A").as_bit());
170 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
171 unused_bits.erase(A);
172 undriven_bits.erase(Y);
173 not_map[Y] = A;
174 continue;
175 }
176
177 if (cell->type.in("$_FF_", "$_DFF_N_", "$_DFF_P_"))
178 {
179 SigBit D = sigmap(cell->getPort("\\D").as_bit());
180 SigBit Q = sigmap(cell->getPort("\\Q").as_bit());
181 unused_bits.erase(D);
182 undriven_bits.erase(Q);
183 ff_map[Q] = D;
184 continue;
185 }
186
187 if (cell->type == "$_AND_")
188 {
189 SigBit A = sigmap(cell->getPort("\\A").as_bit());
190 SigBit B = sigmap(cell->getPort("\\B").as_bit());
191 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
192 unused_bits.erase(A);
193 unused_bits.erase(B);
194 undriven_bits.erase(Y);
195 and_map[Y] = make_pair(A, B);
196 continue;
197 }
198
199 if (cell->type == "$initstate")
200 {
201 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
202 undriven_bits.erase(Y);
203 initstate_bits.insert(Y);
204 continue;
205 }
206
207 for (const auto &c : cell->connections()) {
208 if (c.second.is_fully_const()) continue;
209 SigBit b = c.second.as_bit();
210 Wire *w = b.wire;
211 if (cell->input(c.first)) {
212 SigBit I = sigmap(b);
213 if (!w->port_input)
214 co_bits.insert(I);
215 }
216 else if (cell->output(c.first)) {
217 SigBit O = sigmap(b);
218 ci_bits.insert(O);
219 }
220 else log_abort();
221 if (!type_map.count(cell->type))
222 type_map[cell->type] = type_map.size()+1;
223 }
224 //log_error("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
225 }
226
227 // Do some CI/CO post-processing:
228 // Erase all POs and COs that are undriven
229 for (auto bit : undriven_bits) {
230 co_bits.erase(bit);
231 output_bits.erase(bit);
232 }
233 // Erase all CIs that are also COs or POs
234 for (auto bit : co_bits)
235 ci_bits.erase(bit);
236 for (auto bit : output_bits)
237 ci_bits.erase(bit);
238 // CIs cannot be undriven
239 for (auto bit : ci_bits)
240 undriven_bits.erase(bit);
241
242 for (auto bit : unused_bits)
243 undriven_bits.erase(bit);
244
245 if (!undriven_bits.empty()) {
246 undriven_bits.sort();
247 for (auto bit : undriven_bits) {
248 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
249 input_bits.insert(bit);
250 }
251 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
252 }
253
254 init_map.sort();
255 input_bits.sort();
256 output_bits.sort();
257 not_map.sort();
258 ff_map.sort();
259 and_map.sort();
260
261 aig_map[State::S0] = 0;
262 aig_map[State::S1] = 1;
263
264 for (auto bit : ci_bits) {
265 aig_m++, aig_i++;
266 aig_map[bit] = 2*aig_m;
267 }
268
269 for (auto bit : input_bits) {
270 aig_m++, aig_i++;
271 aig_map[bit] = 2*aig_m;
272 }
273
274 if (imode && input_bits.empty()) {
275 aig_m++, aig_i++;
276 }
277
278 if (zinit_mode)
279 {
280 for (auto it : ff_map) {
281 if (init_map.count(it.first))
282 continue;
283 aig_m++, aig_i++;
284 init_inputs[it.first] = 2*aig_m;
285 }
286 }
287
288 for (auto it : ff_map) {
289 aig_m++, aig_l++;
290 aig_map[it.first] = 2*aig_m;
291 ordered_latches[it.first] = aig_l-1;
292 if (init_map.count(it.first) == 0)
293 aig_latchinit.push_back(2);
294 else
295 aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
296 }
297
298 if (!initstate_bits.empty() || !init_inputs.empty()) {
299 aig_m++, aig_l++;
300 initstate_ff = 2*aig_m+1;
301 aig_latchinit.push_back(0);
302 }
303
304 if (zinit_mode)
305 {
306 for (auto it : ff_map)
307 {
308 int l = ordered_latches[it.first];
309
310 if (aig_latchinit.at(l) == 1)
311 aig_map[it.first] ^= 1;
312
313 if (aig_latchinit.at(l) == 2)
314 {
315 int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
316 int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
317 aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
318 }
319 }
320 }
321
322 for (auto it : ff_map) {
323 int a = bit2aig(it.second);
324 int l = ordered_latches[it.first];
325 if (zinit_mode && aig_latchinit.at(l) == 1)
326 aig_latchin.push_back(a ^ 1);
327 else
328 aig_latchin.push_back(a);
329 }
330
331 if (!initstate_bits.empty() || !init_inputs.empty())
332 aig_latchin.push_back(1);
333
334 for (auto bit : co_bits) {
335 aig_o++;
336 ordered_outputs[bit] = aig_o-1;
337 aig_outputs.push_back(bit2aig(bit));
338 }
339
340 for (auto bit : output_bits) {
341 aig_o++;
342 ordered_outputs[bit] = aig_o-1;
343 aig_outputs.push_back(bit2aig(bit));
344 }
345
346 if (omode && output_bits.empty()) {
347 aig_o++;
348 aig_outputs.push_back(0);
349 }
350
351 if (bmode) {
352 //aig_b++;
353 aig_outputs.push_back(0);
354 }
355 }
356
357 void write_aiger(std::ostream &f, bool ascii_mode, bool miter_mode, bool symbols_mode)
358 {
359 int aig_obc = aig_o;
360 int aig_obcj = aig_obc;
361 int aig_obcjf = aig_obcj;
362
363 log_assert(aig_m == aig_i + aig_l + aig_a);
364 log_assert(aig_l == GetSize(aig_latchin));
365 log_assert(aig_l == GetSize(aig_latchinit));
366 log_assert(aig_obcjf == GetSize(aig_outputs));
367
368 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
369 f << stringf("\n");
370
371 if (ascii_mode)
372 {
373 for (int i = 0; i < aig_i; i++)
374 f << stringf("%d\n", 2*i+2);
375
376 for (int i = 0; i < aig_l; i++) {
377 if (zinit_mode || aig_latchinit.at(i) == 0)
378 f << stringf("%d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i));
379 else if (aig_latchinit.at(i) == 1)
380 f << stringf("%d %d 1\n", 2*(aig_i+i)+2, aig_latchin.at(i));
381 else if (aig_latchinit.at(i) == 2)
382 f << stringf("%d %d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i), 2*(aig_i+i)+2);
383 }
384
385 for (int i = 0; i < aig_obc; i++)
386 f << stringf("%d\n", aig_outputs.at(i));
387
388 for (int i = aig_obc; i < aig_obcj; i++)
389 f << stringf("1\n");
390
391 for (int i = aig_obc; i < aig_obcj; i++)
392 f << stringf("%d\n", aig_outputs.at(i));
393
394 for (int i = aig_obcj; i < aig_obcjf; i++)
395 f << stringf("%d\n", aig_outputs.at(i));
396
397 for (int i = 0; i < aig_a; i++)
398 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
399 }
400 else
401 {
402 for (int i = 0; i < aig_l; i++) {
403 if (zinit_mode || aig_latchinit.at(i) == 0)
404 f << stringf("%d\n", aig_latchin.at(i));
405 else if (aig_latchinit.at(i) == 1)
406 f << stringf("%d 1\n", aig_latchin.at(i));
407 else if (aig_latchinit.at(i) == 2)
408 f << stringf("%d %d\n", aig_latchin.at(i), 2*(aig_i+i)+2);
409 }
410
411 for (int i = 0; i < aig_obc; i++)
412 f << stringf("%d\n", aig_outputs.at(i));
413
414 for (int i = aig_obc; i < aig_obcj; i++)
415 f << stringf("1\n");
416
417 for (int i = aig_obc; i < aig_obcj; i++)
418 f << stringf("%d\n", aig_outputs.at(i));
419
420 for (int i = aig_obcj; i < aig_obcjf; i++)
421 f << stringf("%d\n", aig_outputs.at(i));
422
423 for (int i = 0; i < aig_a; i++) {
424 int lhs = 2*(aig_i+aig_l+i)+2;
425 int rhs0 = aig_gates.at(i).first;
426 int rhs1 = aig_gates.at(i).second;
427 int delta0 = lhs - rhs0;
428 int delta1 = rhs0 - rhs1;
429 aiger_encode(f, delta0);
430 aiger_encode(f, delta1);
431 }
432 }
433
434 if (symbols_mode)
435 {
436 dict<string, vector<string>> symbols;
437
438 for (auto wire : module->wires())
439 {
440 //if (wire->name[0] == '$')
441 // continue;
442
443 SigSpec sig = sigmap(wire);
444
445 for (int i = 0; i < GetSize(wire); i++)
446 {
447 if (sig[i].wire == nullptr) {
448 if (wire->port_output)
449 sig[i] = SigBit(wire, i);
450 else
451 continue;
452 }
453
454 if (input_bits.count(sig[i]) || ci_bits.count(SigSpec(sig[i]))) {
455 int a = aig_map.at(sig[i]);
456 log_assert((a & 1) == 0);
457 if (GetSize(wire) != 1)
458 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s[%d]", log_id(wire), i));
459 else
460 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
461 }
462
463 if (output_bits.count(SigSpec(wire, i)) || co_bits.count(SigSpec(wire, i))) {
464 int o = ordered_outputs.at(SigSpec(wire, i));
465 if (GetSize(wire) != 1)
466 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s[%d]", log_id(wire), i));
467 else
468 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
469 }
470
471 if (init_inputs.count(sig[i])) {
472 int a = init_inputs.at(sig[i]);
473 log_assert((a & 1) == 0);
474 if (GetSize(wire) != 1)
475 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
476 else
477 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
478 }
479
480 if (ordered_latches.count(sig[i])) {
481 int l = ordered_latches.at(sig[i]);
482 const char *p = (zinit_mode && (aig_latchinit.at(l) == 1)) ? "!" : "";
483 if (GetSize(wire) != 1)
484 symbols[stringf("l%d", l)].push_back(stringf("%s%s[%d]", p, log_id(wire), i));
485 else
486 symbols[stringf("l%d", l)].push_back(stringf("%s%s", p, log_id(wire)));
487 }
488 }
489 }
490
491 symbols.sort();
492
493 for (auto &sym : symbols) {
494 f << sym.first;
495 std::sort(sym.second.begin(), sym.second.end());
496 for (auto &s : sym.second)
497 f << " " << s;
498 f << std::endl;
499 }
500 }
501
502 f << stringf("c\nGenerated by %s\n", yosys_version_str);
503 }
504
505 void write_map(std::ostream &f, bool verbose_map)
506 {
507 dict<int, string> input_lines;
508 dict<int, string> init_lines;
509 dict<int, string> output_lines;
510 dict<int, string> latch_lines;
511 dict<int, string> wire_lines;
512
513 for (auto wire : module->wires())
514 {
515 //if (!verbose_map && wire->name[0] == '$')
516 // continue;
517
518 SigSpec sig = sigmap(wire);
519
520 for (int i = 0; i < GetSize(wire); i++)
521 {
522 if (aig_map.count(sig[i]) == 0 || sig[i].wire == nullptr)
523 continue;
524
525 int a = aig_map.at(sig[i]);
526
527 if (verbose_map)
528 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
529
530 if (wire->port_input || ci_bits.count(RTLIL::SigBit{wire, i})) {
531 log_assert((a & 1) == 0);
532 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
533 }
534
535 if (output_bits.count(RTLIL::SigBit{wire, i}) || co_bits.count(RTLIL::SigBit{wire, i})) {
536 int o = ordered_outputs.at(sig[i]);
537 output_lines[o] += stringf("output %d %d %s\n", o, i, log_id(wire));
538 }
539
540 if (init_inputs.count(sig[i])) {
541 int a = init_inputs.at(sig[i]);
542 log_assert((a & 1) == 0);
543 init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
544 }
545
546 if (ordered_latches.count(sig[i])) {
547 int l = ordered_latches.at(sig[i]);
548 if (zinit_mode && (aig_latchinit.at(l) == 1))
549 latch_lines[l] += stringf("invlatch %d %d %s\n", l, i, log_id(wire));
550 else
551 latch_lines[l] += stringf("latch %d %d %s\n", l, i, log_id(wire));
552 }
553 }
554 }
555
556 input_lines.sort();
557 for (auto &it : input_lines)
558 f << it.second;
559
560 init_lines.sort();
561 for (auto &it : init_lines)
562 f << it.second;
563
564 output_lines.sort();
565 for (auto &it : output_lines)
566 f << it.second;
567
568 latch_lines.sort();
569 for (auto &it : latch_lines)
570 f << it.second;
571
572 wire_lines.sort();
573 for (auto &it : wire_lines)
574 f << it.second;
575 }
576 };
577
578 struct XAigerBackend : public Backend {
579 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
580 void help() YS_OVERRIDE
581 {
582 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
583 log("\n");
584 log(" write_xaiger [options] [filename]\n");
585 log("\n");
586 log("Write the current design to an XAIGER file. The design must be flattened and\n");
587 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
588 log("\n");
589 log(" -ascii\n");
590 log(" write ASCII version of AGIER format\n");
591 log("\n");
592 log(" -zinit\n");
593 log(" convert FFs to zero-initialized FFs, adding additional inputs for\n");
594 log(" uninitialized FFs.\n");
595 log("\n");
596 log(" -symbols\n");
597 log(" include a symbol table in the generated AIGER file\n");
598 log("\n");
599 log(" -map <filename>\n");
600 log(" write an extra file with port and latch symbols\n");
601 log("\n");
602 log(" -vmap <filename>\n");
603 log(" like -map, but more verbose\n");
604 log("\n");
605 log(" -I, -O, -B\n");
606 log(" If the design contains no input/output/assert then create one\n");
607 log(" dummy input/output/bad_state pin to make the tools reading the\n");
608 log(" AIGER file happy.\n");
609 log("\n");
610 }
611 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
612 {
613 bool ascii_mode = false;
614 bool zinit_mode = false;
615 bool miter_mode = false;
616 bool symbols_mode = false;
617 bool verbose_map = false;
618 bool imode = false;
619 bool omode = false;
620 bool bmode = false;
621 std::string map_filename;
622
623 log_header(design, "Executing XAIGER backend.\n");
624
625 size_t argidx;
626 for (argidx = 1; argidx < args.size(); argidx++)
627 {
628 if (args[argidx] == "-ascii") {
629 ascii_mode = true;
630 continue;
631 }
632 if (args[argidx] == "-zinit") {
633 zinit_mode = true;
634 continue;
635 }
636 if (args[argidx] == "-symbols") {
637 symbols_mode = true;
638 continue;
639 }
640 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
641 map_filename = args[++argidx];
642 continue;
643 }
644 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
645 map_filename = args[++argidx];
646 verbose_map = true;
647 continue;
648 }
649 if (args[argidx] == "-I") {
650 imode = true;
651 continue;
652 }
653 if (args[argidx] == "-O") {
654 omode = true;
655 continue;
656 }
657 if (args[argidx] == "-B") {
658 bmode = true;
659 continue;
660 }
661 break;
662 }
663 extra_args(f, filename, args, argidx);
664
665 Module *top_module = design->top_module();
666
667 if (top_module == nullptr)
668 log_error("Can't find top module in current design!\n");
669
670 XAigerWriter writer(top_module, zinit_mode, imode, omode, bmode);
671 writer.write_aiger(*f, ascii_mode, miter_mode, symbols_mode);
672
673 if (!map_filename.empty()) {
674 std::ofstream mapf;
675 mapf.open(map_filename.c_str(), std::ofstream::trunc);
676 if (mapf.fail())
677 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
678 writer.write_map(mapf, verbose_map);
679 }
680 }
681 } XAigerBackend;
682
683 PRIVATE_NAMESPACE_END