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 * 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 SigMap sigmap;
63
64 pool<SigBit> input_bits, output_bits;
65 dict<SigBit, SigBit> not_map, alias_map;
66 dict<SigBit, pair<SigBit, SigBit>> and_map;
67 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int>> ci_bits;
68 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int,int>> co_bits;
69
70 vector<pair<int, int>> aig_gates;
71 vector<int> aig_outputs;
72 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
73
74 dict<SigBit, int> aig_map;
75 dict<SigBit, int> ordered_outputs;
76
77 vector<Cell*> box_list;
78 bool omode = false;
79
80 int mkgate(int a0, int a1)
81 {
82 aig_m++, aig_a++;
83 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
84 return 2*aig_m;
85 }
86
87 int bit2aig(SigBit bit)
88 {
89 auto it = aig_map.find(bit);
90 if (it != aig_map.end()) {
91 log_assert(it->second >= 0);
92 return it->second;
93 }
94
95 // NB: Cannot use iterator returned from aig_map.insert()
96 // since this function is called recursively
97
98 int a = -1;
99 if (not_map.count(bit)) {
100 a = bit2aig(not_map.at(bit)) ^ 1;
101 } else
102 if (and_map.count(bit)) {
103 auto args = and_map.at(bit);
104 int a0 = bit2aig(args.first);
105 int a1 = bit2aig(args.second);
106 a = mkgate(a0, a1);
107 } else
108 if (alias_map.count(bit)) {
109 a = bit2aig(alias_map.at(bit));
110 }
111
112 if (bit == State::Sx || bit == State::Sz) {
113 log_debug("Design contains 'x' or 'z' bits. Treating as 1'b0.\n");
114 a = aig_map.at(State::S0);
115 }
116
117 log_assert(a >= 0);
118 aig_map[bit] = a;
119 return a;
120 }
121
122 XAigerWriter(Module *module, bool holes_mode=false) : module(module), sigmap(module)
123 {
124 pool<SigBit> undriven_bits;
125 pool<SigBit> unused_bits;
126
127 // promote public wires
128 for (auto wire : module->wires())
129 if (wire->name[0] == '\\')
130 sigmap.add(wire);
131
132 // promote input wires
133 for (auto wire : module->wires())
134 if (wire->port_input)
135 sigmap.add(wire);
136
137 // promote output wires
138 for (auto wire : module->wires())
139 if (wire->port_output)
140 sigmap.add(wire);
141
142 for (auto wire : module->wires())
143 {
144 bool keep = wire->attributes.count("\\keep");
145
146 for (int i = 0; i < GetSize(wire); i++)
147 {
148 SigBit wirebit(wire, i);
149 SigBit bit = sigmap(wirebit);
150
151 if (bit.wire) {
152 undriven_bits.insert(bit);
153 unused_bits.insert(bit);
154 }
155
156 if (wire->port_input || keep) {
157 if (bit != wirebit)
158 alias_map[bit] = wirebit;
159 input_bits.insert(wirebit);
160 }
161
162 if (wire->port_output || keep) {
163 if (bit != RTLIL::Sx) {
164 if (bit != wirebit)
165 alias_map[wirebit] = bit;
166 output_bits.insert(wirebit);
167 }
168 else
169 log_debug("Skipping PO '%s' driven by 1'bx\n", log_signal(wirebit));
170 }
171 }
172 }
173
174 for (auto bit : input_bits)
175 undriven_bits.erase(sigmap(bit));
176 for (auto bit : output_bits)
177 if (!bit.wire->port_input)
178 unused_bits.erase(bit);
179
180 // TODO: Speed up toposort -- ultimately we care about
181 // box ordering, but not individual AIG cells
182 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
183 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
184 bool abc_box_seen = false;
185
186 for (auto cell : module->selected_cells()) {
187 if (cell->type == "$_NOT_")
188 {
189 SigBit A = sigmap(cell->getPort("\\A").as_bit());
190 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
191 unused_bits.erase(A);
192 undriven_bits.erase(Y);
193 not_map[Y] = A;
194 if (!holes_mode) {
195 toposort.node(cell->name);
196 bit_users[A].insert(cell->name);
197 bit_drivers[Y].insert(cell->name);
198 }
199 continue;
200 }
201
202 if (cell->type == "$_AND_")
203 {
204 SigBit A = sigmap(cell->getPort("\\A").as_bit());
205 SigBit B = sigmap(cell->getPort("\\B").as_bit());
206 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
207 unused_bits.erase(A);
208 unused_bits.erase(B);
209 undriven_bits.erase(Y);
210 and_map[Y] = make_pair(A, B);
211 if (!holes_mode) {
212 toposort.node(cell->name);
213 bit_users[A].insert(cell->name);
214 bit_users[B].insert(cell->name);
215 bit_drivers[Y].insert(cell->name);
216 }
217 continue;
218 }
219
220 log_assert(!holes_mode);
221
222 RTLIL::Module* inst_module = module->design->module(cell->type);
223 if (inst_module && inst_module->attributes.count("\\abc_box_id")) {
224 abc_box_seen = true;
225
226 if (!holes_mode) {
227 toposort.node(cell->name);
228 for (const auto &conn : cell->connections()) {
229 if (cell->input(conn.first)) {
230 // Ignore inout for the sake of topographical ordering
231 if (cell->output(conn.first)) continue;
232 for (auto bit : sigmap(conn.second))
233 bit_users[bit].insert(cell->name);
234 }
235
236 if (cell->output(conn.first))
237 for (auto bit : sigmap(conn.second))
238 bit_drivers[bit].insert(cell->name);
239 }
240 }
241 }
242 else {
243 for (const auto &c : cell->connections()) {
244 if (c.second.is_fully_const()) continue;
245 auto is_input = cell->input(c.first);
246 auto is_output = cell->output(c.first);
247 if (!is_input && !is_output)
248 log_error("Connection '%s' on cell '%s' (type '%s') not recognised!\n", log_id(c.first), log_id(cell), log_id(cell->type));
249
250 if (is_input) {
251 for (auto b : c.second.bits()) {
252 Wire *w = b.wire;
253 if (!w) continue;
254 if (!w->port_output) {
255 SigBit I = sigmap(b);
256 if (I != b)
257 alias_map[b] = I;
258 output_bits.insert(b);
259 unused_bits.erase(b);
260 }
261 }
262 }
263 if (is_output) {
264 for (auto b : c.second.bits()) {
265 Wire *w = b.wire;
266 if (!w) continue;
267 input_bits.insert(b);
268 SigBit O = sigmap(b);
269 if (O != b)
270 alias_map[O] = b;
271 undriven_bits.erase(O);
272 }
273 }
274 }
275 }
276
277 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
278 }
279
280 if (abc_box_seen) {
281 for (auto &it : bit_users)
282 if (bit_drivers.count(it.first))
283 for (auto driver_cell : bit_drivers.at(it.first))
284 for (auto user_cell : it.second)
285 toposort.edge(driver_cell, user_cell);
286
287 pool<RTLIL::Module*> abc_carry_modules;
288
289 #if 0
290 toposort.analyze_loops = true;
291 #endif
292 bool no_loops = toposort.sort();
293 #if 0
294 unsigned i = 0;
295 for (auto &it : toposort.loops) {
296 log(" loop %d", i++);
297 for (auto cell : it)
298 log(" %s", log_id(cell));
299 log("\n");
300 }
301 #endif
302 log_assert(no_loops);
303
304 for (auto cell_name : toposort.sorted) {
305 RTLIL::Cell *cell = module->cell(cell_name);
306 RTLIL::Module* box_module = module->design->module(cell->type);
307 if (!box_module || !box_module->attributes.count("\\abc_box_id"))
308 continue;
309
310 if (box_module->attributes.count("\\abc_carry") && !abc_carry_modules.count(box_module)) {
311 RTLIL::Wire* carry_in = nullptr, *carry_out = nullptr;
312 RTLIL::Wire* last_in = nullptr, *last_out = nullptr;
313 for (const auto &port_name : box_module->ports) {
314 RTLIL::Wire* w = box_module->wire(port_name);
315 log_assert(w);
316 if (w->port_input) {
317 if (w->attributes.count("\\abc_carry_in")) {
318 log_assert(!carry_in);
319 carry_in = w;
320 }
321 log_assert(!last_in || last_in->port_id < w->port_id);
322 last_in = w;
323 }
324 if (w->port_output) {
325 if (w->attributes.count("\\abc_carry_out")) {
326 log_assert(!carry_out);
327 carry_out = w;
328 }
329 log_assert(!last_out || last_out->port_id < w->port_id);
330 last_out = w;
331 }
332 }
333
334 if (carry_in) {
335 log_assert(last_in);
336 std::swap(box_module->ports[carry_in->port_id-1], box_module->ports[last_in->port_id-1]);
337 std::swap(carry_in->port_id, last_in->port_id);
338 }
339 if (carry_out) {
340 log_assert(last_out);
341 std::swap(box_module->ports[carry_out->port_id-1], box_module->ports[last_out->port_id-1]);
342 std::swap(carry_out->port_id, last_out->port_id);
343 }
344 }
345
346 // Fully pad all unused input connections of this box cell with S0
347 // Fully pad all undriven output connections of this box cell with anonymous wires
348 // NB: Assume box_module->ports are sorted alphabetically
349 // (as RTLIL::Module::fixup_ports() would do)
350 for (const auto &port_name : box_module->ports) {
351 RTLIL::Wire* w = box_module->wire(port_name);
352 log_assert(w);
353 auto it = cell->connections_.find(port_name);
354 if (w->port_input) {
355 RTLIL::SigSpec rhs;
356 if (it != cell->connections_.end()) {
357 if (GetSize(it->second) < GetSize(w))
358 it->second.append(RTLIL::SigSpec(RTLIL::S0, GetSize(w)-GetSize(it->second)));
359 rhs = it->second;
360 }
361 else {
362 rhs = RTLIL::SigSpec(RTLIL::S0, GetSize(w));
363 cell->setPort(port_name, rhs);
364 }
365
366 int offset = 0;
367 for (auto b : rhs.bits()) {
368 SigBit I = sigmap(b);
369 if (b == RTLIL::Sx)
370 b = RTLIL::S0;
371 else if (I != b) {
372 if (I == RTLIL::Sx)
373 alias_map[b] = RTLIL::S0;
374 else
375 alias_map[b] = I;
376 }
377 co_bits.emplace_back(b, cell, port_name, offset++, 0);
378 unused_bits.erase(b);
379 }
380 }
381 if (w->port_output) {
382 RTLIL::SigSpec rhs;
383 auto it = cell->connections_.find(w->name);
384 if (it != cell->connections_.end()) {
385 if (GetSize(it->second) < GetSize(w))
386 it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
387 rhs = it->second;
388 }
389 else {
390 rhs = module->addWire(NEW_ID, GetSize(w));
391 cell->setPort(port_name, rhs);
392 }
393
394 int offset = 0;
395 for (const auto &b : rhs.bits()) {
396 ci_bits.emplace_back(b, cell, port_name, offset++);
397 SigBit O = sigmap(b);
398 if (O != b)
399 alias_map[O] = b;
400 undriven_bits.erase(O);
401
402 auto jt = input_bits.find(b);
403 if (jt != input_bits.end()) {
404 log_assert(b.wire->attributes.count("\\keep"));
405 input_bits.erase(b);
406 }
407 }
408 }
409 }
410 box_list.emplace_back(cell);
411 }
412
413 // TODO: Free memory from toposort, bit_drivers, bit_users
414 }
415
416 for (auto bit : input_bits) {
417 if (!output_bits.count(bit))
418 continue;
419 RTLIL::Wire *wire = bit.wire;
420 // If encountering an inout port, or a keep-ed wire, then create a new wire
421 // with $inout.out suffix, make it a PO driven by the existing inout, and
422 // inherit existing inout's drivers
423 if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
424 || wire->attributes.count("\\keep")) {
425 RTLIL::IdString wire_name = wire->name.str() + "$inout.out";
426 RTLIL::Wire *new_wire = module->wire(wire_name);
427 if (!new_wire)
428 new_wire = module->addWire(wire_name, GetSize(wire));
429 SigBit new_bit(new_wire, bit.offset);
430 module->connect(new_bit, bit);
431 if (not_map.count(bit))
432 not_map[new_bit] = not_map.at(bit);
433 else if (and_map.count(bit)) {
434 //and_map[new_bit] = and_map.at(bit); // Breaks gcc-4.8
435 and_map.insert(std::make_pair(new_bit, and_map.at(bit)));
436 }
437 else if (alias_map.count(bit))
438 alias_map[new_bit] = alias_map.at(bit);
439 else
440 alias_map[new_bit] = bit;
441 output_bits.erase(bit);
442 output_bits.insert(new_bit);
443 }
444 }
445
446 for (auto bit : unused_bits)
447 undriven_bits.erase(bit);
448
449 if (!undriven_bits.empty() && !holes_mode) {
450 undriven_bits.sort();
451 for (auto bit : undriven_bits) {
452 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
453 input_bits.insert(bit);
454 }
455 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
456 }
457
458 if (holes_mode) {
459 struct sort_by_port_id {
460 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
461 return a.wire->port_id < b.wire->port_id;
462 }
463 };
464 input_bits.sort(sort_by_port_id());
465 output_bits.sort(sort_by_port_id());
466 }
467 else {
468 input_bits.sort();
469 output_bits.sort();
470 }
471
472 not_map.sort();
473 and_map.sort();
474
475 aig_map[State::S0] = 0;
476 aig_map[State::S1] = 1;
477
478 for (auto bit : input_bits) {
479 aig_m++, aig_i++;
480 log_assert(!aig_map.count(bit));
481 aig_map[bit] = 2*aig_m;
482 }
483
484 for (auto &c : ci_bits) {
485 RTLIL::SigBit bit = std::get<0>(c);
486 aig_m++, aig_i++;
487 aig_map[bit] = 2*aig_m;
488 }
489
490 for (auto &c : co_bits) {
491 RTLIL::SigBit bit = std::get<0>(c);
492 std::get<4>(c) = ordered_outputs[bit] = aig_o++;
493 aig_outputs.push_back(bit2aig(bit));
494 }
495
496 for (auto bit : output_bits) {
497 ordered_outputs[bit] = aig_o++;
498 aig_outputs.push_back(bit2aig(bit));
499 }
500
501 if (output_bits.empty()) {
502 aig_o++;
503 aig_outputs.push_back(0);
504 omode = true;
505 }
506 }
507
508 void write_aiger(std::ostream &f, bool ascii_mode)
509 {
510 int aig_obc = aig_o;
511 int aig_obcj = aig_obc;
512 int aig_obcjf = aig_obcj;
513
514 log_assert(aig_m == aig_i + aig_l + aig_a);
515 log_assert(aig_obcjf == GetSize(aig_outputs));
516
517 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
518 f << stringf("\n");
519
520 if (ascii_mode)
521 {
522 for (int i = 0; i < aig_i; i++)
523 f << stringf("%d\n", 2*i+2);
524
525 for (int i = 0; i < aig_obc; i++)
526 f << stringf("%d\n", aig_outputs.at(i));
527
528 for (int i = aig_obc; i < aig_obcj; i++)
529 f << stringf("1\n");
530
531 for (int i = aig_obc; i < aig_obcj; i++)
532 f << stringf("%d\n", aig_outputs.at(i));
533
534 for (int i = aig_obcj; i < aig_obcjf; i++)
535 f << stringf("%d\n", aig_outputs.at(i));
536
537 for (int i = 0; i < aig_a; i++)
538 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
539 }
540 else
541 {
542 for (int i = 0; i < aig_obc; i++)
543 f << stringf("%d\n", aig_outputs.at(i));
544
545 for (int i = aig_obc; i < aig_obcj; i++)
546 f << stringf("1\n");
547
548 for (int i = aig_obc; i < aig_obcj; i++)
549 f << stringf("%d\n", aig_outputs.at(i));
550
551 for (int i = aig_obcj; i < aig_obcjf; i++)
552 f << stringf("%d\n", aig_outputs.at(i));
553
554 for (int i = 0; i < aig_a; i++) {
555 int lhs = 2*(aig_i+aig_l+i)+2;
556 int rhs0 = aig_gates.at(i).first;
557 int rhs1 = aig_gates.at(i).second;
558 int delta0 = lhs - rhs0;
559 int delta1 = rhs0 - rhs1;
560 aiger_encode(f, delta0);
561 aiger_encode(f, delta1);
562 }
563 }
564
565 f << "c";
566
567 if (!box_list.empty()) {
568 auto write_buffer = [](std::stringstream &buffer, int i32) {
569 int32_t i32_be = to_big_endian(i32);
570 buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
571 };
572
573 std::stringstream h_buffer;
574 auto write_h_buffer = std::bind(write_buffer, std::ref(h_buffer), std::placeholders::_1);
575 write_h_buffer(1);
576 log_debug("ciNum = %zu\n", input_bits.size() + ci_bits.size());
577 write_h_buffer(input_bits.size() + ci_bits.size());
578 log_debug("coNum = %zu\n", output_bits.size() + co_bits.size());
579 write_h_buffer(output_bits.size() + co_bits.size());
580 log_debug("piNum = %zu\n", input_bits.size());
581 write_h_buffer(input_bits.size());
582 log_debug("poNum = %zu\n", output_bits.size());
583 write_h_buffer(output_bits.size());
584 log_debug("boxNum = %zu\n", box_list.size());
585 write_h_buffer(box_list.size());
586
587 RTLIL::Module *holes_module = nullptr;
588 holes_module = module->design->addModule("$__holes__");
589 log_assert(holes_module);
590
591 int port_id = 1;
592 int box_count = 0;
593 for (auto cell : box_list) {
594 RTLIL::Module* box_module = module->design->module(cell->type);
595 int box_inputs = 0, box_outputs = 0;
596 Cell *holes_cell = nullptr;
597 if (box_module->get_bool_attribute("\\whitebox")) {
598 holes_cell = holes_module->addCell(cell->name, cell->type);
599 holes_cell->parameters = cell->parameters;
600 }
601
602 // NB: Assume box_module->ports are sorted alphabetically
603 // (as RTLIL::Module::fixup_ports() would do)
604 for (const auto &port_name : box_module->ports) {
605 RTLIL::Wire *w = box_module->wire(port_name);
606 log_assert(w);
607 RTLIL::Wire *holes_wire;
608 RTLIL::SigSpec port_wire;
609 if (w->port_input) {
610 for (int i = 0; i < GetSize(w); i++) {
611 box_inputs++;
612 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
613 if (!holes_wire) {
614 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
615 holes_wire->port_input = true;
616 holes_wire->port_id = port_id++;
617 holes_module->ports.push_back(holes_wire->name);
618 }
619 if (holes_cell)
620 port_wire.append(holes_wire);
621 }
622 if (!port_wire.empty())
623 holes_cell->setPort(w->name, port_wire);
624 }
625 if (w->port_output) {
626 box_outputs += GetSize(w);
627 for (int i = 0; i < GetSize(w); i++) {
628 if (GetSize(w) == 1)
629 holes_wire = holes_module->addWire(stringf("%s.%s", cell->name.c_str(), w->name.c_str()));
630 else
631 holes_wire = holes_module->addWire(stringf("%s.%s[%d]", cell->name.c_str(), w->name.c_str(), i));
632 holes_wire->port_output = true;
633 holes_wire->port_id = port_id++;
634 holes_module->ports.push_back(holes_wire->name);
635 if (holes_cell)
636 port_wire.append(holes_wire);
637 else
638 holes_module->connect(holes_wire, RTLIL::S0);
639 }
640 if (!port_wire.empty())
641 holes_cell->setPort(w->name, port_wire);
642 }
643 }
644
645 write_h_buffer(box_inputs);
646 write_h_buffer(box_outputs);
647 write_h_buffer(box_module->attributes.at("\\abc_box_id").as_int());
648 write_h_buffer(box_count++);
649 }
650
651 f << "h";
652 std::string buffer_str = h_buffer.str();
653 int32_t buffer_size_be = to_big_endian(buffer_str.size());
654 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
655 f.write(buffer_str.data(), buffer_str.size());
656
657 std::stringstream r_buffer;
658 auto write_r_buffer = std::bind(write_buffer, std::ref(r_buffer), std::placeholders::_1);
659 write_r_buffer(0);
660
661 f << "r";
662 buffer_str = r_buffer.str();
663 buffer_size_be = to_big_endian(buffer_str.size());
664 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
665 f.write(buffer_str.data(), buffer_str.size());
666
667 if (holes_module) {
668 log_push();
669
670 // NB: fixup_ports() will sort ports by name
671 //holes_module->fixup_ports();
672 holes_module->check();
673
674 holes_module->design->selection_stack.emplace_back(false);
675 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
676 sel.select(holes_module);
677
678 // TODO: Should not need to opt_merge if we only instantiate
679 // each box type once...
680 Pass::call(holes_module->design, "opt_merge -share_all");
681
682 Pass::call(holes_module->design, "flatten -wb");
683
684 // TODO: Should techmap/aigmap/check all lib_whitebox-es just once,
685 // instead of per write_xaiger call
686 Pass::call(holes_module->design, "techmap");
687 Pass::call(holes_module->design, "aigmap");
688 for (auto cell : holes_module->cells())
689 if (!cell->type.in("$_NOT_", "$_AND_"))
690 log_error("Whitebox contents cannot be represented as AIG. Please verify whiteboxes are synthesisable.\n");
691
692 Pass::call(holes_module->design, "clean -purge");
693
694 std::stringstream a_buffer;
695 XAigerWriter writer(holes_module, true /* holes_mode */);
696 writer.write_aiger(a_buffer, false /*ascii_mode*/);
697
698 holes_module->design->selection_stack.pop_back();
699
700 f << "a";
701 std::string buffer_str = a_buffer.str();
702 int32_t buffer_size_be = to_big_endian(buffer_str.size());
703 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
704 f.write(buffer_str.data(), buffer_str.size());
705 holes_module->design->remove(holes_module);
706
707 log_pop();
708 }
709 }
710
711 f << stringf("Generated by %s\n", yosys_version_str);
712 }
713
714 void write_map(std::ostream &f, bool verbose_map)
715 {
716 dict<int, string> input_lines;
717 dict<int, string> output_lines;
718 dict<int, string> wire_lines;
719
720 for (auto wire : module->wires())
721 {
722 //if (!verbose_map && wire->name[0] == '$')
723 // continue;
724
725 SigSpec sig = sigmap(wire);
726
727 for (int i = 0; i < GetSize(wire); i++)
728 {
729 RTLIL::SigBit b(wire, i);
730 if (input_bits.count(b)) {
731 int a = aig_map.at(b);
732 log_assert((a & 1) == 0);
733 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
734 }
735
736 if (output_bits.count(b)) {
737 int o = ordered_outputs.at(b);
738 output_lines[o] += stringf("output %lu %d %s\n", o - co_bits.size(), i, log_id(wire));
739 continue;
740 }
741
742 if (verbose_map) {
743 if (aig_map.count(sig[i]) == 0)
744 continue;
745
746 int a = aig_map.at(sig[i]);
747 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
748 }
749 }
750 }
751
752 input_lines.sort();
753 for (auto &it : input_lines)
754 f << it.second;
755 log_assert(input_lines.size() == input_bits.size());
756
757 int box_count = 0;
758 for (auto cell : box_list)
759 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
760
761 output_lines.sort();
762 for (auto &it : output_lines)
763 f << it.second;
764 log_assert(output_lines.size() == output_bits.size());
765 if (omode && output_bits.empty())
766 f << "output " << output_lines.size() << " 0 $__dummy__\n";
767
768 wire_lines.sort();
769 for (auto &it : wire_lines)
770 f << it.second;
771 }
772 };
773
774 struct XAigerBackend : public Backend {
775 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
776 void help() YS_OVERRIDE
777 {
778 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
779 log("\n");
780 log(" write_xaiger [options] [filename]\n");
781 log("\n");
782 log("Write the current design to an XAIGER file. The design must be flattened and\n");
783 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
784 log("\n");
785 log(" -ascii\n");
786 log(" write ASCII version of AIGER format\n");
787 log("\n");
788 log(" -map <filename>\n");
789 log(" write an extra file with port and latch symbols\n");
790 log("\n");
791 log(" -vmap <filename>\n");
792 log(" like -map, but more verbose\n");
793 log("\n");
794 }
795 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
796 {
797 bool ascii_mode = false;
798 bool verbose_map = false;
799 std::string map_filename;
800
801 log_header(design, "Executing XAIGER backend.\n");
802
803 size_t argidx;
804 for (argidx = 1; argidx < args.size(); argidx++)
805 {
806 if (args[argidx] == "-ascii") {
807 ascii_mode = true;
808 continue;
809 }
810 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
811 map_filename = args[++argidx];
812 continue;
813 }
814 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
815 map_filename = args[++argidx];
816 verbose_map = true;
817 continue;
818 }
819 break;
820 }
821 extra_args(f, filename, args, argidx);
822
823 Module *top_module = design->top_module();
824
825 if (top_module == nullptr)
826 log_error("Can't find top module in current design!\n");
827
828 XAigerWriter writer(top_module);
829 writer.write_aiger(*f, ascii_mode);
830
831 if (!map_filename.empty()) {
832 std::ofstream mapf;
833 mapf.open(map_filename.c_str(), std::ofstream::trunc);
834 if (mapf.fail())
835 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
836 writer.write_map(mapf, verbose_map);
837 }
838 }
839 } XAigerBackend;
840
841 PRIVATE_NAMESPACE_END