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