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