Fixes for simple_abc9 tests
[yosys.git] / backends / aiger / xaiger.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * Copyright (C) 2019 Eddie Hung <eddie@fpgeh.com>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 */
20
21 #include "kernel/yosys.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/utils.h"
25
26 USING_YOSYS_NAMESPACE
27 PRIVATE_NAMESPACE_BEGIN
28
29 void aiger_encode(std::ostream &f, int x)
30 {
31 log_assert(x >= 0);
32
33 while (x & ~0x7f) {
34 f.put((x & 0x7f) | 0x80);
35 x = x >> 7;
36 }
37
38 f.put(x);
39 }
40
41 struct XAigerWriter
42 {
43 Module *module;
44 bool zinit_mode;
45 SigMap sigmap;
46
47 dict<SigBit, bool> init_map;
48 pool<SigBit> input_bits, output_bits;
49 dict<SigBit, SigBit> not_map, ff_map, alias_map;
50 dict<SigBit, pair<SigBit, SigBit>> and_map;
51 //pool<SigBit> initstate_bits;
52 vector<std::pair<SigBit,int>> ci_bits, co_bits;
53 vector<std::pair<SigBit,SigBit>> ff_bits;
54
55 vector<pair<int, int>> aig_gates;
56 vector<int> aig_latchin, aig_latchinit, aig_outputs;
57 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
58
59 dict<SigBit, int> aig_map;
60 dict<SigBit, int> ordered_outputs;
61 dict<SigBit, int> ordered_latches;
62
63 vector<Cell*> box_list;
64
65 //dict<SigBit, int> init_inputs;
66 //int initstate_ff = 0;
67
68 int mkgate(int a0, int a1)
69 {
70 aig_m++, aig_a++;
71 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
72 return 2*aig_m;
73 }
74
75 int bit2aig(SigBit bit)
76 {
77 if (aig_map.count(bit) == 0)
78 {
79 aig_map[bit] = -1;
80
81 //if (initstate_bits.count(bit)) {
82 // log_assert(initstate_ff > 0);
83 // aig_map[bit] = initstate_ff;
84 //} else
85 if (not_map.count(bit)) {
86 int a = bit2aig(not_map.at(bit)) ^ 1;
87 aig_map[bit] = a;
88 } else
89 if (and_map.count(bit)) {
90 auto args = and_map.at(bit);
91 int a0 = bit2aig(args.first);
92 int a1 = bit2aig(args.second);
93 aig_map[bit] = mkgate(a0, a1);
94 } else
95 if (alias_map.count(bit)) {
96 aig_map[bit] = bit2aig(alias_map.at(bit));
97 }
98
99 if (bit == State::Sx || bit == State::Sz)
100 log_error("Design contains 'x' or 'z' bits. Use 'setundef' to replace those constants.\n");
101 }
102
103 log_assert(aig_map.at(bit) >= 0);
104 return aig_map.at(bit);
105 }
106
107 XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode, bool holes_mode=false) : module(module), zinit_mode(zinit_mode), sigmap(module)
108 {
109 pool<SigBit> undriven_bits;
110 pool<SigBit> unused_bits;
111
112 // promote public wires
113 for (auto wire : module->wires())
114 if (wire->name[0] == '\\')
115 sigmap.add(wire);
116
117 // promote input wires
118 for (auto wire : module->wires())
119 if (wire->port_input)
120 sigmap.add(wire);
121
122 // promote output wires
123 for (auto wire : module->wires())
124 if (wire->port_output)
125 sigmap.add(wire);
126
127 for (auto wire : module->wires())
128 {
129 if (wire->attributes.count("\\init")) {
130 SigSpec initsig = sigmap(wire);
131 Const initval = wire->attributes.at("\\init");
132 for (int i = 0; i < GetSize(wire) && i < GetSize(initval); i++)
133 if (initval[i] == State::S0 || initval[i] == State::S1)
134 init_map[initsig[i]] = initval[i] == State::S1;
135 }
136
137 for (int i = 0; i < GetSize(wire); i++)
138 {
139 SigBit wirebit(wire, i);
140 SigBit bit = sigmap(wirebit);
141
142 if (bit.wire == nullptr) {
143 if (wire->port_output) {
144 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
145 output_bits.insert(wirebit);
146 }
147 continue;
148 }
149
150 undriven_bits.insert(bit);
151 unused_bits.insert(bit);
152
153 if (wire->port_input)
154 input_bits.insert(bit);
155
156 if (wire->port_output) {
157 if (bit != wirebit)
158 alias_map[wirebit] = bit;
159 output_bits.insert(wirebit);
160 }
161 }
162 }
163
164 for (auto bit : input_bits) {
165 if (!bit.wire->port_output)
166 undriven_bits.erase(bit);
167 // Erase POs that are also PIs
168 output_bits.erase(bit);
169 }
170
171 for (auto bit : output_bits)
172 if (!bit.wire->port_input)
173 unused_bits.erase(bit);
174
175 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
176 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
177 bool abc_box_seen = false;
178
179 for (auto cell : module->cells())
180 {
181 RTLIL::Module* inst_module = module->design->module(cell->type);
182 bool inst_flop = inst_module ? inst_module->attributes.count("\\abc_flop") : false;
183 bool known_type = yosys_celltypes.cell_known(cell->type);
184
185 if (!holes_mode) {
186 toposort.node(cell->name);
187 for (const auto &conn : cell->connections())
188 {
189 if (!cell->type.in("$_NOT_", "$_AND_")) {
190 if (known_type) {
191 if (conn.first.in("\\Q", "\\CTRL_OUT", "\\RD_DATA"))
192 continue;
193 if (cell->type == "$memrd" && conn.first == "\\DATA")
194 continue;
195 }
196
197 if (inst_module) {
198 RTLIL::Wire* inst_module_port = inst_module->wire(conn.first);
199 log_assert(inst_module_port);
200
201 if (inst_module_port->attributes.count("\\abc_flop_q"))
202 continue;
203 }
204 }
205
206 if (cell->input(conn.first)) {
207 // Ignore inout for the sake of topographical ordering
208 if (cell->output(conn.first)) continue;
209 for (auto bit : sigmap(conn.second))
210 bit_users[bit].insert(cell->name);
211 }
212
213 if (cell->output(conn.first))
214 for (auto bit : sigmap(conn.second))
215 bit_drivers[bit].insert(cell->name);
216 }
217 }
218
219 if (cell->type == "$_NOT_")
220 {
221 SigBit A = sigmap(cell->getPort("\\A").as_bit());
222 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
223 unused_bits.erase(A);
224 undriven_bits.erase(Y);
225 not_map[Y] = A;
226 continue;
227 }
228
229 //if (cell->type.in("$_FF_", "$_DFF_N_", "$_DFF_P_"))
230 //{
231 // SigBit D = sigmap(cell->getPort("\\D").as_bit());
232 // SigBit Q = sigmap(cell->getPort("\\Q").as_bit());
233 // unused_bits.erase(D);
234 // undriven_bits.erase(Q);
235 // ff_map[Q] = D;
236 // continue;
237 //}
238
239 if (cell->type == "$_AND_")
240 {
241 SigBit A = sigmap(cell->getPort("\\A").as_bit());
242 SigBit B = sigmap(cell->getPort("\\B").as_bit());
243 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
244 unused_bits.erase(A);
245 unused_bits.erase(B);
246 undriven_bits.erase(Y);
247 and_map[Y] = make_pair(A, B);
248 continue;
249 }
250
251 //if (cell->type == "$initstate")
252 //{
253 // SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
254 // undriven_bits.erase(Y);
255 // initstate_bits.insert(Y);
256 // continue;
257 //}
258
259 if (inst_flop) {
260 SigBit d, q;
261 for (const auto &c : cell->connections()) {
262 for (auto b : c.second.bits()) {
263 auto is_input = cell->input(c.first);
264 auto is_output = cell->output(c.first);
265 log_assert(is_input || is_output);
266 if (is_input && inst_module->wire(c.first)->attributes.count("\\abc_flop_d")) {
267 SigBit I = sigmap(b);
268 if (I != b)
269 alias_map[b] = I;
270 d = b;
271 }
272 if (is_output && inst_module->wire(c.first)->attributes.count("\\abc_flop_q")) {
273 SigBit O = sigmap(b);
274 q = O;
275 }
276 }
277 }
278 if (!abc_box_seen) abc_box_seen = inst_module->attributes.count("\\abc_box_id");
279
280 ff_bits.emplace_back(d, q);
281 undriven_bits.erase(q);
282 }
283 else if (inst_module && inst_module->attributes.count("\\abc_box_id")) {
284 abc_box_seen = true;
285 }
286 else {
287 for (const auto &c : cell->connections()) {
288 if (c.second.is_fully_const()) continue;
289 for (auto b : c.second.bits()) {
290 Wire *w = b.wire;
291 if (!w) continue;
292 auto is_input = cell->input(c.first);
293 auto is_output = cell->output(c.first);
294 log_assert(is_input || is_output);
295 if (is_input) {
296 if (!w->port_input) {
297 SigBit I = sigmap(b);
298 if (I != b)
299 alias_map[b] = I;
300 output_bits.insert(b);
301 unused_bits.erase(b);
302 }
303 }
304 if (is_output) {
305 SigBit O = sigmap(b);
306 input_bits.insert(O);
307 undriven_bits.erase(O);
308 }
309 }
310 }
311 }
312
313 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
314 }
315
316 if (abc_box_seen) {
317 for (auto &it : bit_users)
318 if (bit_drivers.count(it.first))
319 for (auto driver_cell : bit_drivers.at(it.first))
320 for (auto user_cell : it.second)
321 toposort.edge(driver_cell, user_cell);
322
323 #ifndef NDEBUG
324 toposort.analyze_loops = true;
325 #endif
326 toposort.sort();
327 #ifndef NDEBUG
328 for (auto &it : toposort.loops) {
329 log(" loop");
330 for (auto cell : it)
331 log(" %s", log_id(cell));
332 log("\n");
333 }
334 #endif
335 log_assert(!toposort.found_loops);
336
337 for (auto cell_name : toposort.sorted) {
338 RTLIL::Cell *cell = module->cell(cell_name);
339 RTLIL::Module* box_module = module->design->module(cell->type);
340 if (!box_module || !box_module->attributes.count("\\abc_box_id"))
341 continue;
342
343 // Box ordering is alphabetical
344 cell->connections_.sort(RTLIL::sort_by_id_str());
345 for (const auto &c : cell->connections()) {
346 for (auto b : c.second.bits()) {
347 auto is_input = cell->input(c.first);
348 auto is_output = cell->output(c.first);
349 log_assert(is_input || is_output);
350 if (is_input) {
351 SigBit I = sigmap(b);
352 if (I != b)
353 alias_map[b] = I;
354 co_bits.emplace_back(b, 0);
355 }
356 if (is_output) {
357 SigBit O = sigmap(b);
358 ci_bits.emplace_back(O, 0);
359 }
360 }
361 }
362
363 box_list.emplace_back(cell);
364 }
365
366 // TODO: Free memory from toposort, bit_drivers, bit_users
367 }
368
369 for (auto bit : input_bits) {
370 RTLIL::Wire *wire = bit.wire;
371 // If encountering an inout port, then create a new wire with $inout.out
372 // suffix, make it a PO driven by the existing inout, and inherit existing
373 // inout's drivers
374 if (wire->port_input && wire->port_output && !undriven_bits.count(bit)) {
375 RTLIL::Wire *new_wire = module->wire(wire->name.str() + "$inout.out");
376 if (!new_wire)
377 new_wire = module->addWire(wire->name.str() + "$inout.out", GetSize(wire));
378 SigBit new_bit(new_wire, bit.offset);
379 module->connect(new_bit, bit);
380 if (not_map.count(bit))
381 not_map[new_bit] = not_map.at(bit);
382 else if (and_map.count(bit))
383 and_map[new_bit] = and_map.at(bit);
384 else if (alias_map.count(bit))
385 alias_map[new_bit] = alias_map.at(bit);
386 else
387 alias_map[new_bit] = bit;
388 output_bits.insert(new_bit);
389 }
390 }
391
392 // Do some CI/CO post-processing:
393 // Erase all POs that are undriven
394 for (auto bit : undriven_bits)
395 output_bits.erase(bit);
396 // CIs cannot be undriven
397 for (const auto &c : ci_bits)
398 undriven_bits.erase(c.first);
399 for (auto bit : unused_bits)
400 undriven_bits.erase(bit);
401
402 if (!undriven_bits.empty() && !holes_mode) {
403 undriven_bits.sort();
404 for (auto bit : undriven_bits) {
405 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
406 input_bits.insert(bit);
407 }
408 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
409 }
410
411 init_map.sort();
412 input_bits.sort();
413 output_bits.sort();
414 not_map.sort();
415 ff_map.sort();
416 and_map.sort();
417
418 aig_map[State::S0] = 0;
419 aig_map[State::S1] = 1;
420
421 for (auto bit : input_bits) {
422 aig_m++, aig_i++;
423 aig_map[bit] = 2*aig_m;
424 }
425
426 for (auto &f : ff_bits) {
427 auto bit = f.second;
428 aig_m++, aig_i++;
429 aig_map[bit] = 2*aig_m;
430 }
431
432 dict<SigBit, int> ff_aig_map;
433 for (auto &c : ci_bits) {
434 aig_m++, aig_i++;
435 c.second = 2*aig_m;
436 auto r = aig_map.insert(std::make_pair(c.first, c.second));
437 if (!r.second) {
438 ff_aig_map[c.first] = c.second;
439 }
440 }
441
442 if (imode && input_bits.empty()) {
443 aig_m++, aig_i++;
444 }
445
446 //if (zinit_mode)
447 //{
448 // for (auto it : ff_map) {
449 // if (init_map.count(it.first))
450 // continue;
451 // aig_m++, aig_i++;
452 // init_inputs[it.first] = 2*aig_m;
453 // }
454 //}
455
456 for (auto it : ff_map) {
457 aig_m++, aig_l++;
458 aig_map[it.first] = 2*aig_m;
459 ordered_latches[it.first] = aig_l-1;
460 if (init_map.count(it.first) == 0)
461 aig_latchinit.push_back(2);
462 else
463 aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
464 }
465
466 //if (!initstate_bits.empty() || !init_inputs.empty()) {
467 // aig_m++, aig_l++;
468 // initstate_ff = 2*aig_m+1;
469 // aig_latchinit.push_back(0);
470 //}
471
472 //if (zinit_mode)
473 //{
474 // for (auto it : ff_map)
475 // {
476 // int l = ordered_latches[it.first];
477
478 // if (aig_latchinit.at(l) == 1)
479 // aig_map[it.first] ^= 1;
480
481 // if (aig_latchinit.at(l) == 2)
482 // {
483 // int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
484 // int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
485 // aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
486 // }
487 // }
488 //}
489
490 for (auto it : ff_map) {
491 int a = bit2aig(it.second);
492 int l = ordered_latches[it.first];
493 if (zinit_mode && aig_latchinit.at(l) == 1)
494 aig_latchin.push_back(a ^ 1);
495 else
496 aig_latchin.push_back(a);
497 }
498
499 //if (!initstate_bits.empty() || !init_inputs.empty())
500 // aig_latchin.push_back(1);
501
502 for (auto &c : co_bits) {
503 RTLIL::SigBit bit = c.first;
504 c.second = aig_o++;
505 ordered_outputs[bit] = c.second;
506 aig_outputs.push_back(bit2aig(bit));
507 }
508
509 for (auto bit : output_bits) {
510 ordered_outputs[bit] = aig_o++;
511 aig_outputs.push_back(bit2aig(bit));
512 }
513
514 for (auto &f : ff_bits) {
515 aig_o++;
516 aig_outputs.push_back(ff_aig_map.at(f.second));
517 }
518
519 if (omode && output_bits.empty()) {
520 aig_o++;
521 aig_outputs.push_back(0);
522 }
523
524 if (bmode) {
525 //aig_b++;
526 aig_outputs.push_back(0);
527 }
528 }
529
530 void write_aiger(std::ostream &f, bool ascii_mode, bool miter_mode, bool symbols_mode, bool omode)
531 {
532 int aig_obc = aig_o;
533 int aig_obcj = aig_obc;
534 int aig_obcjf = aig_obcj;
535
536 log_assert(aig_m == aig_i + aig_l + aig_a);
537 log_assert(aig_l == GetSize(aig_latchin));
538 log_assert(aig_l == GetSize(aig_latchinit));
539 log_assert(aig_obcjf == GetSize(aig_outputs));
540
541 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
542 f << stringf("\n");
543
544 if (ascii_mode)
545 {
546 for (int i = 0; i < aig_i; i++)
547 f << stringf("%d\n", 2*i+2);
548
549 for (int i = 0; i < aig_l; i++) {
550 if (zinit_mode || aig_latchinit.at(i) == 0)
551 f << stringf("%d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i));
552 else if (aig_latchinit.at(i) == 1)
553 f << stringf("%d %d 1\n", 2*(aig_i+i)+2, aig_latchin.at(i));
554 else if (aig_latchinit.at(i) == 2)
555 f << stringf("%d %d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i), 2*(aig_i+i)+2);
556 }
557
558 for (int i = 0; i < aig_obc; i++)
559 f << stringf("%d\n", aig_outputs.at(i));
560
561 for (int i = aig_obc; i < aig_obcj; i++)
562 f << stringf("1\n");
563
564 for (int i = aig_obc; i < aig_obcj; i++)
565 f << stringf("%d\n", aig_outputs.at(i));
566
567 for (int i = aig_obcj; i < aig_obcjf; i++)
568 f << stringf("%d\n", aig_outputs.at(i));
569
570 for (int i = 0; i < aig_a; i++)
571 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
572 }
573 else
574 {
575 for (int i = 0; i < aig_l; i++) {
576 if (zinit_mode || aig_latchinit.at(i) == 0)
577 f << stringf("%d\n", aig_latchin.at(i));
578 else if (aig_latchinit.at(i) == 1)
579 f << stringf("%d 1\n", aig_latchin.at(i));
580 else if (aig_latchinit.at(i) == 2)
581 f << stringf("%d %d\n", aig_latchin.at(i), 2*(aig_i+i)+2);
582 }
583
584 for (int i = 0; i < aig_obc; i++)
585 f << stringf("%d\n", aig_outputs.at(i));
586
587 for (int i = aig_obc; i < aig_obcj; i++)
588 f << stringf("1\n");
589
590 for (int i = aig_obc; i < aig_obcj; i++)
591 f << stringf("%d\n", aig_outputs.at(i));
592
593 for (int i = aig_obcj; i < aig_obcjf; i++)
594 f << stringf("%d\n", aig_outputs.at(i));
595
596 for (int i = 0; i < aig_a; i++) {
597 int lhs = 2*(aig_i+aig_l+i)+2;
598 int rhs0 = aig_gates.at(i).first;
599 int rhs1 = aig_gates.at(i).second;
600 int delta0 = lhs - rhs0;
601 int delta1 = rhs0 - rhs1;
602 aiger_encode(f, delta0);
603 aiger_encode(f, delta1);
604 }
605 }
606
607 if (symbols_mode)
608 {
609 dict<string, vector<string>> symbols;
610
611 bool output_seen = false;
612 for (auto wire : module->wires())
613 {
614 //if (wire->name[0] == '$')
615 // continue;
616
617 SigSpec sig = sigmap(wire);
618
619 for (int i = 0; i < GetSize(wire); i++)
620 {
621 RTLIL::SigBit b(wire, i);
622 if (input_bits.count(b)) {
623 int a = aig_map.at(sig[i]);
624 log_assert((a & 1) == 0);
625 if (GetSize(wire) != 1)
626 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s[%d]", log_id(wire), i));
627 else
628 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
629 }
630
631 if (output_bits.count(b)) {
632 int o = ordered_outputs.at(b);
633 output_seen = !miter_mode;
634 if (GetSize(wire) != 1)
635 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s[%d]", log_id(wire), i));
636 else
637 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
638 }
639
640 //if (init_inputs.count(sig[i])) {
641 // int a = init_inputs.at(sig[i]);
642 // log_assert((a & 1) == 0);
643 // if (GetSize(wire) != 1)
644 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
645 // else
646 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
647 //}
648
649 if (ordered_latches.count(sig[i])) {
650 int l = ordered_latches.at(sig[i]);
651 const char *p = (zinit_mode && (aig_latchinit.at(l) == 1)) ? "!" : "";
652 if (GetSize(wire) != 1)
653 symbols[stringf("l%d", l)].push_back(stringf("%s%s[%d]", p, log_id(wire), i));
654 else
655 symbols[stringf("l%d", l)].push_back(stringf("%s%s", p, log_id(wire)));
656 }
657 }
658 }
659
660 if (omode && !output_seen)
661 symbols["o0"].push_back("__dummy_o__");
662
663 symbols.sort();
664
665 for (auto &sym : symbols) {
666 f << sym.first;
667 std::sort(sym.second.begin(), sym.second.end());
668 for (auto &s : sym.second)
669 f << " " << s;
670 f << std::endl;
671 }
672 }
673
674 f << "c";
675
676 if (!box_list.empty() || !ff_bits.empty()) {
677 std::stringstream h_buffer;
678 auto write_h_buffer = [&h_buffer](int i32) {
679 // TODO: Don't assume we're on little endian
680 #ifdef _WIN32
681 int i32_be = _byteswap_ulong(i32);
682 #else
683 int i32_be = __builtin_bswap32(i32);
684 #endif
685 h_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
686 };
687 int num_outputs = output_bits.size();
688 if (omode && num_outputs == 0)
689 num_outputs = 1;
690 write_h_buffer(1);
691 write_h_buffer(input_bits.size() + ff_bits.size() + ci_bits.size());
692 write_h_buffer(num_outputs + ff_bits.size() + co_bits.size());
693 write_h_buffer(input_bits.size() + ff_bits.size());
694 write_h_buffer(num_outputs + ff_bits.size());
695 write_h_buffer(box_list.size());
696
697 RTLIL::Module *holes_module = nullptr;
698 holes_module = module->design->addModule("\\__holes__");
699
700 for (auto cell : box_list) {
701 int box_inputs = 0, box_outputs = 0;
702 int box_id = module->design->module(cell->type)->attributes.at("\\abc_box_id").as_int();
703 Cell *holes_cell = nullptr;
704 if (holes_module && !holes_module->cell(stringf("\\u%d", box_id)))
705 holes_cell = holes_module->addCell(stringf("\\u%d", box_id), cell->type);
706 RTLIL::Wire *holes_wire;
707 // NB: cell->connections_ already sorted from before
708 for (const auto &c : cell->connections()) {
709 log_assert(c.second.size() == 1);
710 if (cell->input(c.first)) {
711 box_inputs += c.second.size();
712 if (holes_cell) {
713 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
714 if (!holes_wire) {
715 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
716 holes_wire->port_input = true;
717 }
718 holes_cell->setPort(c.first, holes_wire);
719 }
720 }
721 if (cell->output(c.first)) {
722 box_outputs += c.second.size();
723 if (holes_cell) {
724 holes_wire = holes_module->addWire(stringf("\\%s.%s", cell->type.c_str(), c.first.c_str()));
725 holes_wire->port_output = true;
726 holes_cell->setPort(c.first, holes_wire);
727 }
728 }
729 }
730 write_h_buffer(box_inputs);
731 write_h_buffer(box_outputs);
732 write_h_buffer(box_id);
733 write_h_buffer(0 /* OldBoxNum */);
734 }
735
736 f << "h";
737 std::string buffer_str = h_buffer.str();
738 // TODO: Don't assume we're on little endian
739 #ifdef _WIN32
740 int buffer_size_be = _byteswap_ulong(buffer_str.size());
741 #else
742 int buffer_size_be = __builtin_bswap32(buffer_str.size());
743 #endif
744 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
745 f.write(buffer_str.data(), buffer_str.size());
746
747 if (!ff_bits.empty()) {
748 std::stringstream r_buffer;
749 auto write_r_buffer = [&r_buffer](int i32) {
750 // TODO: Don't assume we're on little endian
751 #ifdef _WIN32
752 int i32_be = _byteswap_ulong(i32);
753 #else
754 int i32_be = __builtin_bswap32(i32);
755 #endif
756 r_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
757 };
758 write_r_buffer(ff_bits.size());
759 int mergeability_class = 1;
760 for (auto cell : ff_bits)
761 write_r_buffer(mergeability_class++);
762
763 f << "r";
764 std::string buffer_str = r_buffer.str();
765 // TODO: Don't assume we're on little endian
766 #ifdef _WIN32
767 int buffer_size_be = _byteswap_ulong(buffer_str.size());
768 #else
769 int buffer_size_be = __builtin_bswap32(buffer_str.size());
770 #endif
771 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
772 f.write(buffer_str.data(), buffer_str.size());
773 }
774
775 if (holes_module) {
776 holes_module->fixup_ports();
777
778 holes_module->design->selection_stack.emplace_back(false);
779 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
780 sel.select(holes_module);
781
782 Pass::call(holes_module->design, "flatten -wb; aigmap; clean -purge");
783
784 holes_module->design->selection_stack.pop_back();
785
786 std::stringstream a_buffer;
787 XAigerWriter writer(holes_module, false /*zinit_mode*/, false /*imode*/, false /*omode*/, false /*bmode*/, true /* holes_mode */);
788 writer.write_aiger(a_buffer, false /*ascii_mode*/, false /*miter_mode*/, false /*symbols_mode*/, false /*omode*/);
789
790 f << "a";
791 std::string buffer_str = a_buffer.str();
792 // TODO: Don't assume we're on little endian
793 #ifdef _WIN32
794 int buffer_size_be = _byteswap_ulong(buffer_str.size());
795 #else
796 int buffer_size_be = __builtin_bswap32(buffer_str.size());
797 #endif
798 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
799 f.write(buffer_str.data(), buffer_str.size());
800 holes_module->design->remove(holes_module);
801 }
802 }
803
804 f << stringf("Generated by %s\n", yosys_version_str);
805 }
806
807 void write_map(std::ostream &f, bool verbose_map, bool omode)
808 {
809 dict<int, string> input_lines;
810 dict<int, string> init_lines;
811 dict<int, string> output_lines;
812 dict<int, string> latch_lines;
813 dict<int, string> wire_lines;
814
815 for (auto wire : module->wires())
816 {
817 //if (!verbose_map && wire->name[0] == '$')
818 // continue;
819
820 SigSpec sig = sigmap(wire);
821
822 for (int i = 0; i < GetSize(wire); i++)
823 {
824 RTLIL::SigBit b(wire, i);
825 if (input_bits.count(b)) {
826 int a = aig_map.at(sig[i]);
827 log_assert((a & 1) == 0);
828 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
829 }
830
831 if (output_bits.count(b)) {
832 int o = ordered_outputs.at(b);
833 output_lines[o] += stringf("output %d %d %s\n", o, i, log_id(wire));
834 continue;
835 }
836
837 //if (init_inputs.count(sig[i])) {
838 // int a = init_inputs.at(sig[i]);
839 // log_assert((a & 1) == 0);
840 // init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
841 // continue;
842 //}
843
844 if (ordered_latches.count(sig[i])) {
845 int l = ordered_latches.at(sig[i]);
846 if (zinit_mode && (aig_latchinit.at(l) == 1))
847 latch_lines[l] += stringf("invlatch %d %d %s\n", l, i, log_id(wire));
848 else
849 latch_lines[l] += stringf("latch %d %d %s\n", l, i, log_id(wire));
850 continue;
851 }
852
853 if (verbose_map) {
854 if (aig_map.count(sig[i]) == 0)
855 continue;
856
857 int a = aig_map.at(sig[i]);
858 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
859 }
860 }
861 }
862
863 for (const auto &c : ci_bits) {
864 RTLIL::SigBit b = c.first;
865 RTLIL::Wire *wire = b.wire;
866 int i = b.offset;
867 int a = bit2aig(b);
868 log_assert((a & 1) == 0);
869 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
870 }
871
872 for (const auto &c : co_bits) {
873 RTLIL::SigBit b = c.first;
874 RTLIL::Wire *wire = b.wire;
875 int o = c.second;
876 if (wire)
877 output_lines[o] += stringf("output %d %d %s\n", o, b.offset, log_id(wire));
878 else
879 output_lines[o] += stringf("output %d %d __const%d__\n", o, 0, b.data);
880 }
881
882 input_lines.sort();
883 for (auto &it : input_lines)
884 f << it.second;
885 log_assert(input_lines.size() == input_bits.size() + ci_bits.size());
886
887 init_lines.sort();
888 for (auto &it : init_lines)
889 f << it.second;
890
891 output_lines.sort();
892 for (auto &it : output_lines)
893 f << it.second;
894 log_assert(output_lines.size() == output_bits.size() + co_bits.size());
895 if (omode && output_bits.empty())
896 f << "output " << output_lines.size() << " 0 __dummy_o__\n";
897
898 latch_lines.sort();
899 for (auto &it : latch_lines)
900 f << it.second;
901
902 wire_lines.sort();
903 for (auto &it : wire_lines)
904 f << it.second;
905 }
906 };
907
908 struct XAigerBackend : public Backend {
909 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
910 void help() YS_OVERRIDE
911 {
912 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
913 log("\n");
914 log(" write_xaiger [options] [filename]\n");
915 log("\n");
916 log("Write the current design to an XAIGER file. The design must be flattened and\n");
917 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
918 log("\n");
919 log(" -ascii\n");
920 log(" write ASCII version of AIGER format\n");
921 log("\n");
922 log(" -zinit\n");
923 log(" convert FFs to zero-initialized FFs, adding additional inputs for\n");
924 log(" uninitialized FFs.\n");
925 log("\n");
926 log(" -symbols\n");
927 log(" include a symbol table in the generated AIGER file\n");
928 log("\n");
929 log(" -map <filename>\n");
930 log(" write an extra file with port and latch symbols\n");
931 log("\n");
932 log(" -vmap <filename>\n");
933 log(" like -map, but more verbose\n");
934 log("\n");
935 log(" -I, -O, -B\n");
936 log(" If the design contains no input/output/assert then create one\n");
937 log(" dummy input/output/bad_state pin to make the tools reading the\n");
938 log(" AIGER file happy.\n");
939 log("\n");
940 }
941 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
942 {
943 bool ascii_mode = false;
944 bool zinit_mode = false;
945 bool miter_mode = false;
946 bool symbols_mode = false;
947 bool verbose_map = false;
948 bool imode = false;
949 bool omode = false;
950 bool bmode = false;
951 std::string map_filename;
952
953 log_header(design, "Executing XAIGER backend.\n");
954
955 size_t argidx;
956 for (argidx = 1; argidx < args.size(); argidx++)
957 {
958 if (args[argidx] == "-ascii") {
959 ascii_mode = true;
960 continue;
961 }
962 if (args[argidx] == "-zinit") {
963 zinit_mode = true;
964 continue;
965 }
966 if (args[argidx] == "-symbols") {
967 symbols_mode = true;
968 continue;
969 }
970 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
971 map_filename = args[++argidx];
972 continue;
973 }
974 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
975 map_filename = args[++argidx];
976 verbose_map = true;
977 continue;
978 }
979 if (args[argidx] == "-I") {
980 imode = true;
981 continue;
982 }
983 if (args[argidx] == "-O") {
984 omode = true;
985 continue;
986 }
987 if (args[argidx] == "-B") {
988 bmode = true;
989 continue;
990 }
991 break;
992 }
993 extra_args(f, filename, args, argidx);
994
995 Module *top_module = design->top_module();
996
997 if (top_module == nullptr)
998 log_error("Can't find top module in current design!\n");
999
1000 XAigerWriter writer(top_module, zinit_mode, imode, omode, bmode);
1001 writer.write_aiger(*f, ascii_mode, miter_mode, symbols_mode, omode);
1002
1003 if (!map_filename.empty()) {
1004 std::ofstream mapf;
1005 mapf.open(map_filename.c_str(), std::ofstream::trunc);
1006 if (mapf.fail())
1007 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
1008 writer.write_map(mapf, verbose_map, omode);
1009 }
1010 }
1011 } XAigerBackend;
1012
1013 PRIVATE_NAMESPACE_END