Merge remote-tracking branch 'origin/master' into xaig
[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 bool keep = wire->attributes.count("\\keep");
138
139 for (int i = 0; i < GetSize(wire); i++)
140 {
141 SigBit wirebit(wire, i);
142 SigBit bit = sigmap(wirebit);
143
144 if (bit.wire == nullptr) {
145 if (wire->port_output) {
146 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
147 output_bits.insert(wirebit);
148 }
149 continue;
150 }
151
152 undriven_bits.insert(bit);
153 unused_bits.insert(bit);
154
155 if (wire->port_input)
156 input_bits.insert(bit);
157 else if (keep)
158 input_bits.insert(wirebit);
159
160 if (wire->port_output || keep) {
161 if (bit != wirebit)
162 alias_map[wirebit] = bit;
163 output_bits.insert(wirebit);
164 }
165 }
166 }
167
168 for (auto bit : input_bits)
169 undriven_bits.erase(bit);
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)
279 abc_box_seen = inst_module->attributes.count("\\abc_box_id");
280
281 ff_bits.emplace_back(d, q);
282 undriven_bits.erase(q);
283 }
284 else if (inst_module && inst_module->attributes.count("\\abc_box_id")) {
285 abc_box_seen = true;
286 }
287 else {
288 for (const auto &c : cell->connections()) {
289 if (c.second.is_fully_const()) continue;
290 for (auto b : c.second.bits()) {
291 Wire *w = b.wire;
292 if (!w) continue;
293 auto is_input = cell->input(c.first);
294 auto is_output = cell->output(c.first);
295 log_assert(is_input || is_output);
296 if (is_input) {
297 if (!w->port_input) {
298 SigBit I = sigmap(b);
299 if (I != b)
300 alias_map[b] = I;
301 output_bits.insert(b);
302 unused_bits.erase(b);
303 }
304 }
305 if (is_output) {
306 SigBit O = sigmap(b);
307 input_bits.insert(O);
308 undriven_bits.erase(O);
309 }
310 }
311 }
312 }
313
314 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
315 }
316
317 if (abc_box_seen) {
318 for (auto &it : bit_users)
319 if (bit_drivers.count(it.first))
320 for (auto driver_cell : bit_drivers.at(it.first))
321 for (auto user_cell : it.second)
322 toposort.edge(driver_cell, user_cell);
323
324 #ifndef NDEBUG
325 toposort.analyze_loops = true;
326 #endif
327 toposort.sort();
328 #ifndef NDEBUG
329 for (auto &it : toposort.loops) {
330 log(" loop");
331 for (auto cell : it)
332 log(" %s", log_id(cell));
333 log("\n");
334 }
335 #endif
336 log_assert(!toposort.found_loops);
337
338 for (auto cell_name : toposort.sorted) {
339 RTLIL::Cell *cell = module->cell(cell_name);
340 RTLIL::Module* box_module = module->design->module(cell->type);
341 if (!box_module || !box_module->attributes.count("\\abc_box_id"))
342 continue;
343
344 // Box ordering is alphabetical
345 cell->connections_.sort(RTLIL::sort_by_id_str());
346 for (const auto &c : cell->connections()) {
347 for (auto b : c.second.bits()) {
348 auto is_input = cell->input(c.first);
349 auto is_output = cell->output(c.first);
350 log_assert(is_input || is_output);
351 if (is_input) {
352 SigBit I = sigmap(b);
353 if (I != b)
354 alias_map[b] = I;
355 co_bits.emplace_back(b, 0);
356 }
357 if (is_output) {
358 SigBit O = sigmap(b);
359 ci_bits.emplace_back(O, 0);
360 }
361 }
362 }
363
364 box_list.emplace_back(cell);
365 }
366
367 // TODO: Free memory from toposort, bit_drivers, bit_users
368 }
369
370 for (auto bit : input_bits) {
371 RTLIL::Wire *wire = bit.wire;
372 // If encountering an inout port, or a keep-ed wire, then create a new wire
373 // with $inout.out suffix, make it a PO driven by the existing inout, and
374 // inherit existing inout's drivers
375 if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
376 || wire->attributes.count("\\keep")) {
377 log_assert(input_bits.count(bit) && output_bits.count(bit));
378 RTLIL::Wire *new_wire = module->wire(wire->name.str() + "$inout.out");
379 if (!new_wire)
380 new_wire = module->addWire(wire->name.str() + "$inout.out", GetSize(wire));
381 SigBit new_bit(new_wire, bit.offset);
382 module->connect(new_bit, bit);
383 if (not_map.count(bit))
384 not_map[new_bit] = not_map.at(bit);
385 else if (and_map.count(bit))
386 and_map[new_bit] = and_map.at(bit);
387 else if (alias_map.count(bit))
388 alias_map[new_bit] = alias_map.at(bit);
389 else
390 //log_abort();
391 alias_map[new_bit] = bit;
392 output_bits.erase(bit);
393 output_bits.insert(new_bit);
394 }
395 }
396
397 // Do some CI/CO post-processing:
398 // Erase all POs that are undriven
399 for (auto bit : undriven_bits)
400 output_bits.erase(bit);
401 // CIs cannot be undriven
402 for (const auto &c : ci_bits)
403 undriven_bits.erase(c.first);
404 for (auto bit : unused_bits)
405 undriven_bits.erase(bit);
406
407 if (!undriven_bits.empty() && !holes_mode) {
408 undriven_bits.sort();
409 for (auto bit : undriven_bits) {
410 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
411 input_bits.insert(bit);
412 }
413 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
414 }
415
416 init_map.sort();
417 input_bits.sort();
418 output_bits.sort();
419 not_map.sort();
420 ff_map.sort();
421 and_map.sort();
422
423 aig_map[State::S0] = 0;
424 aig_map[State::S1] = 1;
425
426 for (auto bit : input_bits) {
427 aig_m++, aig_i++;
428 aig_map[bit] = 2*aig_m;
429 }
430
431 for (auto &f : ff_bits) {
432 auto bit = f.second;
433 aig_m++, aig_i++;
434 aig_map[bit] = 2*aig_m;
435 }
436
437 dict<SigBit, int> ff_aig_map;
438 for (auto &c : ci_bits) {
439 aig_m++, aig_i++;
440 c.second = 2*aig_m;
441 auto r = aig_map.insert(std::make_pair(c.first, c.second));
442 if (!r.second) {
443 ff_aig_map[c.first] = c.second;
444 }
445 }
446
447 if (imode && input_bits.empty()) {
448 aig_m++, aig_i++;
449 }
450
451 //if (zinit_mode)
452 //{
453 // for (auto it : ff_map) {
454 // if (init_map.count(it.first))
455 // continue;
456 // aig_m++, aig_i++;
457 // init_inputs[it.first] = 2*aig_m;
458 // }
459 //}
460
461 for (auto it : ff_map) {
462 aig_m++, aig_l++;
463 aig_map[it.first] = 2*aig_m;
464 ordered_latches[it.first] = aig_l-1;
465 if (init_map.count(it.first) == 0)
466 aig_latchinit.push_back(2);
467 else
468 aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
469 }
470
471 //if (!initstate_bits.empty() || !init_inputs.empty()) {
472 // aig_m++, aig_l++;
473 // initstate_ff = 2*aig_m+1;
474 // aig_latchinit.push_back(0);
475 //}
476
477 //if (zinit_mode)
478 //{
479 // for (auto it : ff_map)
480 // {
481 // int l = ordered_latches[it.first];
482
483 // if (aig_latchinit.at(l) == 1)
484 // aig_map[it.first] ^= 1;
485
486 // if (aig_latchinit.at(l) == 2)
487 // {
488 // int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
489 // int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
490 // aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
491 // }
492 // }
493 //}
494
495 for (auto it : ff_map) {
496 int a = bit2aig(it.second);
497 int l = ordered_latches[it.first];
498 if (zinit_mode && aig_latchinit.at(l) == 1)
499 aig_latchin.push_back(a ^ 1);
500 else
501 aig_latchin.push_back(a);
502 }
503
504 //if (!initstate_bits.empty() || !init_inputs.empty())
505 // aig_latchin.push_back(1);
506
507 for (auto &c : co_bits) {
508 RTLIL::SigBit bit = c.first;
509 c.second = aig_o++;
510 ordered_outputs[bit] = c.second;
511 aig_outputs.push_back(bit2aig(bit));
512 }
513
514 for (auto bit : output_bits) {
515 ordered_outputs[bit] = aig_o++;
516 aig_outputs.push_back(bit2aig(bit));
517 }
518
519 for (auto &f : ff_bits) {
520 aig_o++;
521 aig_outputs.push_back(ff_aig_map.at(f.second));
522 }
523
524 if (omode && output_bits.empty()) {
525 aig_o++;
526 aig_outputs.push_back(0);
527 }
528
529 if (bmode) {
530 //aig_b++;
531 aig_outputs.push_back(0);
532 }
533 }
534
535 void write_aiger(std::ostream &f, bool ascii_mode, bool miter_mode, bool symbols_mode, bool omode)
536 {
537 int aig_obc = aig_o;
538 int aig_obcj = aig_obc;
539 int aig_obcjf = aig_obcj;
540
541 log_assert(aig_m == aig_i + aig_l + aig_a);
542 log_assert(aig_l == GetSize(aig_latchin));
543 log_assert(aig_l == GetSize(aig_latchinit));
544 log_assert(aig_obcjf == GetSize(aig_outputs));
545
546 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
547 f << stringf("\n");
548
549 if (ascii_mode)
550 {
551 for (int i = 0; i < aig_i; i++)
552 f << stringf("%d\n", 2*i+2);
553
554 for (int i = 0; i < aig_l; i++) {
555 if (zinit_mode || aig_latchinit.at(i) == 0)
556 f << stringf("%d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i));
557 else if (aig_latchinit.at(i) == 1)
558 f << stringf("%d %d 1\n", 2*(aig_i+i)+2, aig_latchin.at(i));
559 else if (aig_latchinit.at(i) == 2)
560 f << stringf("%d %d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i), 2*(aig_i+i)+2);
561 }
562
563 for (int i = 0; i < aig_obc; i++)
564 f << stringf("%d\n", aig_outputs.at(i));
565
566 for (int i = aig_obc; i < aig_obcj; i++)
567 f << stringf("1\n");
568
569 for (int i = aig_obc; i < aig_obcj; i++)
570 f << stringf("%d\n", aig_outputs.at(i));
571
572 for (int i = aig_obcj; i < aig_obcjf; i++)
573 f << stringf("%d\n", aig_outputs.at(i));
574
575 for (int i = 0; i < aig_a; i++)
576 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
577 }
578 else
579 {
580 for (int i = 0; i < aig_l; i++) {
581 if (zinit_mode || aig_latchinit.at(i) == 0)
582 f << stringf("%d\n", aig_latchin.at(i));
583 else if (aig_latchinit.at(i) == 1)
584 f << stringf("%d 1\n", aig_latchin.at(i));
585 else if (aig_latchinit.at(i) == 2)
586 f << stringf("%d %d\n", aig_latchin.at(i), 2*(aig_i+i)+2);
587 }
588
589 for (int i = 0; i < aig_obc; i++)
590 f << stringf("%d\n", aig_outputs.at(i));
591
592 for (int i = aig_obc; i < aig_obcj; i++)
593 f << stringf("1\n");
594
595 for (int i = aig_obc; i < aig_obcj; i++)
596 f << stringf("%d\n", aig_outputs.at(i));
597
598 for (int i = aig_obcj; i < aig_obcjf; i++)
599 f << stringf("%d\n", aig_outputs.at(i));
600
601 for (int i = 0; i < aig_a; i++) {
602 int lhs = 2*(aig_i+aig_l+i)+2;
603 int rhs0 = aig_gates.at(i).first;
604 int rhs1 = aig_gates.at(i).second;
605 int delta0 = lhs - rhs0;
606 int delta1 = rhs0 - rhs1;
607 aiger_encode(f, delta0);
608 aiger_encode(f, delta1);
609 }
610 }
611
612 if (symbols_mode)
613 {
614 dict<string, vector<string>> symbols;
615
616 bool output_seen = false;
617 for (auto wire : module->wires())
618 {
619 //if (wire->name[0] == '$')
620 // continue;
621
622 SigSpec sig = sigmap(wire);
623
624 for (int i = 0; i < GetSize(wire); i++)
625 {
626 RTLIL::SigBit b(wire, i);
627 if (input_bits.count(b)) {
628 int a = aig_map.at(sig[i]);
629 log_assert((a & 1) == 0);
630 if (GetSize(wire) != 1)
631 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s[%d]", log_id(wire), i));
632 else
633 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
634 }
635
636 if (output_bits.count(b)) {
637 int o = ordered_outputs.at(b);
638 output_seen = !miter_mode;
639 if (GetSize(wire) != 1)
640 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s[%d]", log_id(wire), i));
641 else
642 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
643 }
644
645 //if (init_inputs.count(sig[i])) {
646 // int a = init_inputs.at(sig[i]);
647 // log_assert((a & 1) == 0);
648 // if (GetSize(wire) != 1)
649 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
650 // else
651 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
652 //}
653
654 if (ordered_latches.count(sig[i])) {
655 int l = ordered_latches.at(sig[i]);
656 const char *p = (zinit_mode && (aig_latchinit.at(l) == 1)) ? "!" : "";
657 if (GetSize(wire) != 1)
658 symbols[stringf("l%d", l)].push_back(stringf("%s%s[%d]", p, log_id(wire), i));
659 else
660 symbols[stringf("l%d", l)].push_back(stringf("%s%s", p, log_id(wire)));
661 }
662 }
663 }
664
665 if (omode && !output_seen)
666 symbols["o0"].push_back("__dummy_o__");
667
668 symbols.sort();
669
670 for (auto &sym : symbols) {
671 f << sym.first;
672 std::sort(sym.second.begin(), sym.second.end());
673 for (auto &s : sym.second)
674 f << " " << s;
675 f << std::endl;
676 }
677 }
678
679 f << "c";
680
681 if (!box_list.empty() || !ff_bits.empty()) {
682 std::stringstream h_buffer;
683 auto write_h_buffer = [&h_buffer](int i32) {
684 // TODO: Don't assume we're on little endian
685 #ifdef _WIN32
686 int i32_be = _byteswap_ulong(i32);
687 #else
688 int i32_be = __builtin_bswap32(i32);
689 #endif
690 h_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
691 };
692 int num_outputs = output_bits.size();
693 if (omode && num_outputs == 0)
694 num_outputs = 1;
695 write_h_buffer(1);
696 write_h_buffer(input_bits.size() + ff_bits.size() + ci_bits.size());
697 write_h_buffer(num_outputs + ff_bits.size() + co_bits.size());
698 write_h_buffer(input_bits.size() + ff_bits.size());
699 write_h_buffer(num_outputs + ff_bits.size());
700 write_h_buffer(box_list.size());
701
702 RTLIL::Module *holes_module = nullptr;
703 holes_module = module->design->addModule("\\__holes__");
704
705 for (auto cell : box_list) {
706 int box_inputs = 0, box_outputs = 0;
707 int box_id = module->design->module(cell->type)->attributes.at("\\abc_box_id").as_int();
708 Cell *holes_cell = nullptr;
709 if (holes_module && !holes_module->cell(stringf("\\u%d", box_id)))
710 holes_cell = holes_module->addCell(stringf("\\u%d", box_id), cell->type);
711 RTLIL::Wire *holes_wire;
712 // NB: cell->connections_ already sorted from before
713 for (const auto &c : cell->connections()) {
714 log_assert(c.second.size() == 1);
715 if (cell->input(c.first)) {
716 box_inputs += c.second.size();
717 if (holes_cell) {
718 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
719 if (!holes_wire) {
720 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
721 holes_wire->port_input = true;
722 }
723 holes_cell->setPort(c.first, holes_wire);
724 }
725 }
726 if (cell->output(c.first)) {
727 box_outputs += c.second.size();
728 if (holes_cell) {
729 holes_wire = holes_module->addWire(stringf("\\%s.%s", cell->type.c_str(), c.first.c_str()));
730 holes_wire->port_output = true;
731 holes_cell->setPort(c.first, holes_wire);
732 }
733 }
734 }
735 write_h_buffer(box_inputs);
736 write_h_buffer(box_outputs);
737 write_h_buffer(box_id);
738 write_h_buffer(0 /* OldBoxNum */);
739 }
740
741 f << "h";
742 std::string buffer_str = h_buffer.str();
743 // TODO: Don't assume we're on little endian
744 #ifdef _WIN32
745 int buffer_size_be = _byteswap_ulong(buffer_str.size());
746 #else
747 int buffer_size_be = __builtin_bswap32(buffer_str.size());
748 #endif
749 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
750 f.write(buffer_str.data(), buffer_str.size());
751
752 if (!ff_bits.empty()) {
753 std::stringstream r_buffer;
754 auto write_r_buffer = [&r_buffer](int i32) {
755 // TODO: Don't assume we're on little endian
756 #ifdef _WIN32
757 int i32_be = _byteswap_ulong(i32);
758 #else
759 int i32_be = __builtin_bswap32(i32);
760 #endif
761 r_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
762 };
763 write_r_buffer(ff_bits.size());
764 int mergeability_class = 1;
765 for (auto cell : ff_bits)
766 write_r_buffer(mergeability_class++);
767
768 f << "r";
769 std::string buffer_str = r_buffer.str();
770 // TODO: Don't assume we're on little endian
771 #ifdef _WIN32
772 int buffer_size_be = _byteswap_ulong(buffer_str.size());
773 #else
774 int buffer_size_be = __builtin_bswap32(buffer_str.size());
775 #endif
776 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
777 f.write(buffer_str.data(), buffer_str.size());
778 }
779
780 if (holes_module) {
781 holes_module->fixup_ports();
782
783 holes_module->design->selection_stack.emplace_back(false);
784 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
785 sel.select(holes_module);
786
787 Pass::call(holes_module->design, "flatten -wb; aigmap; clean -purge");
788
789 holes_module->design->selection_stack.pop_back();
790
791 std::stringstream a_buffer;
792 XAigerWriter writer(holes_module, false /*zinit_mode*/, false /*imode*/, false /*omode*/, false /*bmode*/, true /* holes_mode */);
793 writer.write_aiger(a_buffer, false /*ascii_mode*/, false /*miter_mode*/, false /*symbols_mode*/, false /*omode*/);
794
795 f << "a";
796 std::string buffer_str = a_buffer.str();
797 // TODO: Don't assume we're on little endian
798 #ifdef _WIN32
799 int buffer_size_be = _byteswap_ulong(buffer_str.size());
800 #else
801 int buffer_size_be = __builtin_bswap32(buffer_str.size());
802 #endif
803 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
804 f.write(buffer_str.data(), buffer_str.size());
805 holes_module->design->remove(holes_module);
806 }
807 }
808
809 f << stringf("Generated by %s\n", yosys_version_str);
810 }
811
812 void write_map(std::ostream &f, bool verbose_map, bool omode)
813 {
814 dict<int, string> input_lines;
815 dict<int, string> init_lines;
816 dict<int, string> output_lines;
817 dict<int, string> latch_lines;
818 dict<int, string> wire_lines;
819
820 for (auto wire : module->wires())
821 {
822 //if (!verbose_map && wire->name[0] == '$')
823 // continue;
824
825 SigSpec sig = sigmap(wire);
826
827 for (int i = 0; i < GetSize(wire); i++)
828 {
829 RTLIL::SigBit b(wire, i);
830 if (input_bits.count(b)) {
831 int a = aig_map.at(b);
832 log_assert((a & 1) == 0);
833 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
834 }
835
836 if (output_bits.count(b)) {
837 int o = ordered_outputs.at(b);
838 output_lines[o] += stringf("output %d %d %s\n", o, i, log_id(wire));
839 continue;
840 }
841
842 //if (init_inputs.count(sig[i])) {
843 // int a = init_inputs.at(sig[i]);
844 // log_assert((a & 1) == 0);
845 // init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
846 // continue;
847 //}
848
849 if (ordered_latches.count(sig[i])) {
850 int l = ordered_latches.at(sig[i]);
851 if (zinit_mode && (aig_latchinit.at(l) == 1))
852 latch_lines[l] += stringf("invlatch %d %d %s\n", l, i, log_id(wire));
853 else
854 latch_lines[l] += stringf("latch %d %d %s\n", l, i, log_id(wire));
855 continue;
856 }
857
858 if (verbose_map) {
859 if (aig_map.count(sig[i]) == 0)
860 continue;
861
862 int a = aig_map.at(sig[i]);
863 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
864 }
865 }
866 }
867
868 for (const auto &c : ci_bits) {
869 RTLIL::SigBit b = c.first;
870 RTLIL::Wire *wire = b.wire;
871 int i = b.offset;
872 int a = bit2aig(b);
873 log_assert((a & 1) == 0);
874 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
875 }
876
877 for (const auto &c : co_bits) {
878 RTLIL::SigBit b = c.first;
879 RTLIL::Wire *wire = b.wire;
880 int o = c.second;
881 if (wire)
882 output_lines[o] += stringf("output %d %d %s\n", o, b.offset, log_id(wire));
883 else
884 output_lines[o] += stringf("output %d %d __const%d__\n", o, 0, b.data);
885 }
886
887 input_lines.sort();
888 for (auto &it : input_lines)
889 f << it.second;
890 log_assert(input_lines.size() == input_bits.size() + ci_bits.size());
891
892 init_lines.sort();
893 for (auto &it : init_lines)
894 f << it.second;
895
896 output_lines.sort();
897 for (auto &it : output_lines)
898 f << it.second;
899 log_assert(output_lines.size() == output_bits.size() + co_bits.size());
900 if (omode && output_bits.empty())
901 f << "output " << output_lines.size() << " 0 __dummy_o__\n";
902
903 latch_lines.sort();
904 for (auto &it : latch_lines)
905 f << it.second;
906
907 wire_lines.sort();
908 for (auto &it : wire_lines)
909 f << it.second;
910 }
911 };
912
913 struct XAigerBackend : public Backend {
914 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
915 void help() YS_OVERRIDE
916 {
917 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
918 log("\n");
919 log(" write_xaiger [options] [filename]\n");
920 log("\n");
921 log("Write the current design to an XAIGER file. The design must be flattened and\n");
922 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
923 log("\n");
924 log(" -ascii\n");
925 log(" write ASCII version of AIGER format\n");
926 log("\n");
927 log(" -zinit\n");
928 log(" convert FFs to zero-initialized FFs, adding additional inputs for\n");
929 log(" uninitialized FFs.\n");
930 log("\n");
931 log(" -symbols\n");
932 log(" include a symbol table in the generated AIGER file\n");
933 log("\n");
934 log(" -map <filename>\n");
935 log(" write an extra file with port and latch symbols\n");
936 log("\n");
937 log(" -vmap <filename>\n");
938 log(" like -map, but more verbose\n");
939 log("\n");
940 log(" -I, -O, -B\n");
941 log(" If the design contains no input/output/assert then create one\n");
942 log(" dummy input/output/bad_state pin to make the tools reading the\n");
943 log(" AIGER file happy.\n");
944 log("\n");
945 }
946 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
947 {
948 bool ascii_mode = false;
949 bool zinit_mode = false;
950 bool miter_mode = false;
951 bool symbols_mode = false;
952 bool verbose_map = false;
953 bool imode = false;
954 bool omode = false;
955 bool bmode = false;
956 std::string map_filename;
957
958 log_header(design, "Executing XAIGER backend.\n");
959
960 size_t argidx;
961 for (argidx = 1; argidx < args.size(); argidx++)
962 {
963 if (args[argidx] == "-ascii") {
964 ascii_mode = true;
965 continue;
966 }
967 if (args[argidx] == "-zinit") {
968 zinit_mode = true;
969 continue;
970 }
971 if (args[argidx] == "-symbols") {
972 symbols_mode = true;
973 continue;
974 }
975 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
976 map_filename = args[++argidx];
977 continue;
978 }
979 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
980 map_filename = args[++argidx];
981 verbose_map = true;
982 continue;
983 }
984 if (args[argidx] == "-I") {
985 imode = true;
986 continue;
987 }
988 if (args[argidx] == "-O") {
989 omode = true;
990 continue;
991 }
992 if (args[argidx] == "-B") {
993 bmode = true;
994 continue;
995 }
996 break;
997 }
998 extra_args(f, filename, args, argidx);
999
1000 Module *top_module = design->top_module();
1001
1002 if (top_module == nullptr)
1003 log_error("Can't find top module in current design!\n");
1004
1005 XAigerWriter writer(top_module, zinit_mode, imode, omode, bmode);
1006 writer.write_aiger(*f, ascii_mode, miter_mode, symbols_mode, omode);
1007
1008 if (!map_filename.empty()) {
1009 std::ofstream mapf;
1010 mapf.open(map_filename.c_str(), std::ofstream::trunc);
1011 if (mapf.fail())
1012 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
1013 writer.write_map(mapf, verbose_map, omode);
1014 }
1015 }
1016 } XAigerBackend;
1017
1018 PRIVATE_NAMESPACE_END