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\n", i++);
297 for (auto cell_name : it) {
298 auto cell = module->cell(cell_name);
299 log_assert(cell);
300 log("\t%s (%s @ %s)\n", log_id(cell), log_id(cell->type), cell->get_src_attribute().c_str());
301 }
302 }
303 #endif
304 log_assert(no_loops);
305
306 for (auto cell_name : toposort.sorted) {
307 RTLIL::Cell *cell = module->cell(cell_name);
308 RTLIL::Module* box_module = module->design->module(cell->type);
309 if (!box_module || !box_module->attributes.count("\\abc_box_id"))
310 continue;
311
312 if (box_module->attributes.count("\\abc_carry") && !abc_carry_modules.count(box_module)) {
313 RTLIL::Wire* carry_in = nullptr, *carry_out = nullptr;
314 auto &ports = box_module->ports;
315 for (auto it = ports.begin(); it != ports.end(); ) {
316 RTLIL::Wire* w = box_module->wire(*it);
317 log_assert(w);
318 if (w->port_input && w->attributes.count("\\abc_carry_in")) {
319 if (carry_in)
320 log_error("More than one port with attribute 'abc_carry_in' found in module '%s'\n", log_id(box_module));
321 carry_in = w;
322 it = ports.erase(it);
323 continue;
324 }
325 if (w->port_output && w->attributes.count("\\abc_carry_out")) {
326 if (carry_out)
327 log_error("More than one port with attribute 'abc_carry_out' found in module '%s'\n", log_id(box_module));
328 carry_out = w;
329 it = ports.erase(it);
330 continue;
331 }
332 ++it;
333 }
334
335 if (!carry_in)
336 log_error("Port with attribute 'abc_carry_in' not found in module '%s'\n", log_id(box_module));
337 if (!carry_out)
338 log_error("Port with attribute 'abc_carry_out' not found in module '%s'\n", log_id(box_module));
339
340 for (const auto port_name : ports) {
341 RTLIL::Wire* w = box_module->wire(port_name);
342 log_assert(w);
343 if (w->port_id > carry_in->port_id)
344 --w->port_id;
345 if (w->port_id > carry_out->port_id)
346 --w->port_id;
347 log_assert(w->port_input || w->port_output);
348 log_assert(ports[w->port_id-1] == w->name);
349 }
350 ports.push_back(carry_in->name);
351 carry_in->port_id = ports.size();
352 ports.push_back(carry_out->name);
353 carry_out->port_id = ports.size();
354 }
355
356 // Fully pad all unused input connections of this box cell with S0
357 // Fully pad all undriven output connections of this box cell with anonymous wires
358 // NB: Assume box_module->ports are sorted alphabetically
359 // (as RTLIL::Module::fixup_ports() would do)
360 for (const auto &port_name : box_module->ports) {
361 RTLIL::Wire* w = box_module->wire(port_name);
362 log_assert(w);
363 auto it = cell->connections_.find(port_name);
364 if (w->port_input) {
365 RTLIL::SigSpec rhs;
366 if (it != cell->connections_.end()) {
367 if (GetSize(it->second) < GetSize(w))
368 it->second.append(RTLIL::SigSpec(RTLIL::S0, GetSize(w)-GetSize(it->second)));
369 rhs = it->second;
370 }
371 else {
372 rhs = RTLIL::SigSpec(RTLIL::S0, GetSize(w));
373 cell->setPort(port_name, rhs);
374 }
375
376 int offset = 0;
377 for (auto b : rhs.bits()) {
378 SigBit I = sigmap(b);
379 if (b == RTLIL::Sx)
380 b = RTLIL::S0;
381 else if (I != b) {
382 if (I == RTLIL::Sx)
383 alias_map[b] = RTLIL::S0;
384 else
385 alias_map[b] = I;
386 }
387 co_bits.emplace_back(b, cell, port_name, offset++, 0);
388 unused_bits.erase(b);
389 }
390 }
391 if (w->port_output) {
392 RTLIL::SigSpec rhs;
393 auto it = cell->connections_.find(w->name);
394 if (it != cell->connections_.end()) {
395 if (GetSize(it->second) < GetSize(w))
396 it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
397 rhs = it->second;
398 }
399 else {
400 rhs = module->addWire(NEW_ID, GetSize(w));
401 cell->setPort(port_name, rhs);
402 }
403
404 int offset = 0;
405 for (const auto &b : rhs.bits()) {
406 ci_bits.emplace_back(b, cell, port_name, offset++);
407 SigBit O = sigmap(b);
408 if (O != b)
409 alias_map[O] = b;
410 undriven_bits.erase(O);
411
412 auto jt = input_bits.find(b);
413 if (jt != input_bits.end()) {
414 log_assert(b.wire->attributes.count("\\keep"));
415 input_bits.erase(b);
416 }
417 }
418 }
419 }
420 box_list.emplace_back(cell);
421 }
422
423 // TODO: Free memory from toposort, bit_drivers, bit_users
424 }
425
426 for (auto bit : input_bits) {
427 if (!output_bits.count(bit))
428 continue;
429 RTLIL::Wire *wire = bit.wire;
430 // If encountering an inout port, or a keep-ed wire, then create a new wire
431 // with $inout.out suffix, make it a PO driven by the existing inout, and
432 // inherit existing inout's drivers
433 if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
434 || wire->attributes.count("\\keep")) {
435 RTLIL::IdString wire_name = wire->name.str() + "$inout.out";
436 RTLIL::Wire *new_wire = module->wire(wire_name);
437 if (!new_wire)
438 new_wire = module->addWire(wire_name, GetSize(wire));
439 SigBit new_bit(new_wire, bit.offset);
440 module->connect(new_bit, bit);
441 if (not_map.count(bit))
442 not_map[new_bit] = not_map.at(bit);
443 else if (and_map.count(bit)) {
444 //and_map[new_bit] = and_map.at(bit); // Breaks gcc-4.8
445 and_map.insert(std::make_pair(new_bit, and_map.at(bit)));
446 }
447 else if (alias_map.count(bit))
448 alias_map[new_bit] = alias_map.at(bit);
449 else
450 alias_map[new_bit] = bit;
451 output_bits.erase(bit);
452 output_bits.insert(new_bit);
453 }
454 }
455
456 for (auto bit : unused_bits)
457 undriven_bits.erase(bit);
458
459 if (!undriven_bits.empty() && !holes_mode) {
460 undriven_bits.sort();
461 for (auto bit : undriven_bits) {
462 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
463 input_bits.insert(bit);
464 }
465 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
466 }
467
468 if (holes_mode) {
469 struct sort_by_port_id {
470 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
471 return a.wire->port_id < b.wire->port_id;
472 }
473 };
474 input_bits.sort(sort_by_port_id());
475 output_bits.sort(sort_by_port_id());
476 }
477 else {
478 input_bits.sort();
479 output_bits.sort();
480 }
481
482 not_map.sort();
483 and_map.sort();
484
485 aig_map[State::S0] = 0;
486 aig_map[State::S1] = 1;
487
488 for (auto bit : input_bits) {
489 aig_m++, aig_i++;
490 log_assert(!aig_map.count(bit));
491 aig_map[bit] = 2*aig_m;
492 }
493
494 for (auto &c : ci_bits) {
495 RTLIL::SigBit bit = std::get<0>(c);
496 aig_m++, aig_i++;
497 aig_map[bit] = 2*aig_m;
498 }
499
500 for (auto &c : co_bits) {
501 RTLIL::SigBit bit = std::get<0>(c);
502 std::get<4>(c) = ordered_outputs[bit] = aig_o++;
503 aig_outputs.push_back(bit2aig(bit));
504 }
505
506 for (auto bit : output_bits) {
507 ordered_outputs[bit] = aig_o++;
508 aig_outputs.push_back(bit2aig(bit));
509 }
510
511 if (output_bits.empty()) {
512 aig_o++;
513 aig_outputs.push_back(0);
514 omode = true;
515 }
516 }
517
518 void write_aiger(std::ostream &f, bool ascii_mode)
519 {
520 int aig_obc = aig_o;
521 int aig_obcj = aig_obc;
522 int aig_obcjf = aig_obcj;
523
524 log_assert(aig_m == aig_i + aig_l + aig_a);
525 log_assert(aig_obcjf == GetSize(aig_outputs));
526
527 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
528 f << stringf("\n");
529
530 if (ascii_mode)
531 {
532 for (int i = 0; i < aig_i; i++)
533 f << stringf("%d\n", 2*i+2);
534
535 for (int i = 0; i < aig_obc; i++)
536 f << stringf("%d\n", aig_outputs.at(i));
537
538 for (int i = aig_obc; i < aig_obcj; i++)
539 f << stringf("1\n");
540
541 for (int i = aig_obc; i < aig_obcj; i++)
542 f << stringf("%d\n", aig_outputs.at(i));
543
544 for (int i = aig_obcj; i < aig_obcjf; i++)
545 f << stringf("%d\n", aig_outputs.at(i));
546
547 for (int i = 0; i < aig_a; i++)
548 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
549 }
550 else
551 {
552 for (int i = 0; i < aig_obc; i++)
553 f << stringf("%d\n", aig_outputs.at(i));
554
555 for (int i = aig_obc; i < aig_obcj; i++)
556 f << stringf("1\n");
557
558 for (int i = aig_obc; i < aig_obcj; i++)
559 f << stringf("%d\n", aig_outputs.at(i));
560
561 for (int i = aig_obcj; i < aig_obcjf; i++)
562 f << stringf("%d\n", aig_outputs.at(i));
563
564 for (int i = 0; i < aig_a; i++) {
565 int lhs = 2*(aig_i+aig_l+i)+2;
566 int rhs0 = aig_gates.at(i).first;
567 int rhs1 = aig_gates.at(i).second;
568 int delta0 = lhs - rhs0;
569 int delta1 = rhs0 - rhs1;
570 aiger_encode(f, delta0);
571 aiger_encode(f, delta1);
572 }
573 }
574
575 f << "c";
576
577 if (!box_list.empty()) {
578 auto write_buffer = [](std::stringstream &buffer, int i32) {
579 int32_t i32_be = to_big_endian(i32);
580 buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
581 };
582
583 std::stringstream h_buffer;
584 auto write_h_buffer = std::bind(write_buffer, std::ref(h_buffer), std::placeholders::_1);
585 write_h_buffer(1);
586 log_debug("ciNum = %zu\n", input_bits.size() + ci_bits.size());
587 write_h_buffer(input_bits.size() + ci_bits.size());
588 log_debug("coNum = %zu\n", output_bits.size() + co_bits.size());
589 write_h_buffer(output_bits.size() + co_bits.size());
590 log_debug("piNum = %zu\n", input_bits.size());
591 write_h_buffer(input_bits.size());
592 log_debug("poNum = %zu\n", output_bits.size());
593 write_h_buffer(output_bits.size());
594 log_debug("boxNum = %zu\n", box_list.size());
595 write_h_buffer(box_list.size());
596
597 RTLIL::Module *holes_module = nullptr;
598 holes_module = module->design->addModule("$__holes__");
599 log_assert(holes_module);
600
601 int port_id = 1;
602 int box_count = 0;
603 for (auto cell : box_list) {
604 RTLIL::Module* box_module = module->design->module(cell->type);
605 int box_inputs = 0, box_outputs = 0;
606 Cell *holes_cell = nullptr;
607 if (box_module->get_bool_attribute("\\whitebox")) {
608 holes_cell = holes_module->addCell(cell->name, cell->type);
609 holes_cell->parameters = cell->parameters;
610 }
611
612 // NB: Assume box_module->ports are sorted alphabetically
613 // (as RTLIL::Module::fixup_ports() would do)
614 for (const auto &port_name : box_module->ports) {
615 RTLIL::Wire *w = box_module->wire(port_name);
616 log_assert(w);
617 RTLIL::Wire *holes_wire;
618 RTLIL::SigSpec port_wire;
619 if (w->port_input) {
620 for (int i = 0; i < GetSize(w); i++) {
621 box_inputs++;
622 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
623 if (!holes_wire) {
624 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
625 holes_wire->port_input = true;
626 holes_wire->port_id = port_id++;
627 holes_module->ports.push_back(holes_wire->name);
628 }
629 if (holes_cell)
630 port_wire.append(holes_wire);
631 }
632 if (!port_wire.empty())
633 holes_cell->setPort(w->name, port_wire);
634 }
635 if (w->port_output) {
636 box_outputs += GetSize(w);
637 for (int i = 0; i < GetSize(w); i++) {
638 if (GetSize(w) == 1)
639 holes_wire = holes_module->addWire(stringf("%s.%s", cell->name.c_str(), w->name.c_str()));
640 else
641 holes_wire = holes_module->addWire(stringf("%s.%s[%d]", cell->name.c_str(), w->name.c_str(), i));
642 holes_wire->port_output = true;
643 holes_wire->port_id = port_id++;
644 holes_module->ports.push_back(holes_wire->name);
645 if (holes_cell)
646 port_wire.append(holes_wire);
647 else
648 holes_module->connect(holes_wire, RTLIL::S0);
649 }
650 if (!port_wire.empty())
651 holes_cell->setPort(w->name, port_wire);
652 }
653 }
654
655 write_h_buffer(box_inputs);
656 write_h_buffer(box_outputs);
657 write_h_buffer(box_module->attributes.at("\\abc_box_id").as_int());
658 write_h_buffer(box_count++);
659 }
660
661 f << "h";
662 std::string buffer_str = h_buffer.str();
663 int32_t 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 std::stringstream r_buffer;
668 auto write_r_buffer = std::bind(write_buffer, std::ref(r_buffer), std::placeholders::_1);
669 write_r_buffer(0);
670
671 f << "r";
672 buffer_str = r_buffer.str();
673 buffer_size_be = to_big_endian(buffer_str.size());
674 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
675 f.write(buffer_str.data(), buffer_str.size());
676
677 if (holes_module) {
678 log_push();
679
680 // NB: fixup_ports() will sort ports by name
681 //holes_module->fixup_ports();
682 holes_module->check();
683
684 holes_module->design->selection_stack.emplace_back(false);
685 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
686 sel.select(holes_module);
687
688 // TODO: Should not need to opt_merge if we only instantiate
689 // each box type once...
690 Pass::call(holes_module->design, "opt_merge -share_all");
691
692 Pass::call(holes_module->design, "flatten -wb");
693
694 // TODO: Should techmap/aigmap/check all lib_whitebox-es just once,
695 // instead of per write_xaiger call
696 Pass::call(holes_module->design, "techmap");
697 Pass::call(holes_module->design, "aigmap");
698 for (auto cell : holes_module->cells())
699 if (!cell->type.in("$_NOT_", "$_AND_"))
700 log_error("Whitebox contents cannot be represented as AIG. Please verify whiteboxes are synthesisable.\n");
701
702 Pass::call(holes_module->design, "clean -purge");
703
704 std::stringstream a_buffer;
705 XAigerWriter writer(holes_module, true /* holes_mode */);
706 writer.write_aiger(a_buffer, false /*ascii_mode*/);
707
708 holes_module->design->selection_stack.pop_back();
709
710 f << "a";
711 std::string buffer_str = a_buffer.str();
712 int32_t buffer_size_be = to_big_endian(buffer_str.size());
713 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
714 f.write(buffer_str.data(), buffer_str.size());
715 holes_module->design->remove(holes_module);
716
717 log_pop();
718 }
719 }
720
721 f << stringf("Generated by %s\n", yosys_version_str);
722 }
723
724 void write_map(std::ostream &f, bool verbose_map)
725 {
726 dict<int, string> input_lines;
727 dict<int, string> output_lines;
728 dict<int, string> wire_lines;
729
730 for (auto wire : module->wires())
731 {
732 //if (!verbose_map && wire->name[0] == '$')
733 // continue;
734
735 SigSpec sig = sigmap(wire);
736
737 for (int i = 0; i < GetSize(wire); i++)
738 {
739 RTLIL::SigBit b(wire, i);
740 if (input_bits.count(b)) {
741 int a = aig_map.at(b);
742 log_assert((a & 1) == 0);
743 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
744 }
745
746 if (output_bits.count(b)) {
747 int o = ordered_outputs.at(b);
748 output_lines[o] += stringf("output %lu %d %s\n", o - co_bits.size(), i, log_id(wire));
749 continue;
750 }
751
752 if (verbose_map) {
753 if (aig_map.count(sig[i]) == 0)
754 continue;
755
756 int a = aig_map.at(sig[i]);
757 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
758 }
759 }
760 }
761
762 input_lines.sort();
763 for (auto &it : input_lines)
764 f << it.second;
765 log_assert(input_lines.size() == input_bits.size());
766
767 int box_count = 0;
768 for (auto cell : box_list)
769 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
770
771 output_lines.sort();
772 for (auto &it : output_lines)
773 f << it.second;
774 log_assert(output_lines.size() == output_bits.size());
775 if (omode && output_bits.empty())
776 f << "output " << output_lines.size() << " 0 $__dummy__\n";
777
778 wire_lines.sort();
779 for (auto &it : wire_lines)
780 f << it.second;
781 }
782 };
783
784 struct XAigerBackend : public Backend {
785 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
786 void help() YS_OVERRIDE
787 {
788 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
789 log("\n");
790 log(" write_xaiger [options] [filename]\n");
791 log("\n");
792 log("Write the current design to an XAIGER file. The design must be flattened and\n");
793 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
794 log("\n");
795 log(" -ascii\n");
796 log(" write ASCII version of AIGER format\n");
797 log("\n");
798 log(" -map <filename>\n");
799 log(" write an extra file with port and latch symbols\n");
800 log("\n");
801 log(" -vmap <filename>\n");
802 log(" like -map, but more verbose\n");
803 log("\n");
804 }
805 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
806 {
807 bool ascii_mode = false;
808 bool verbose_map = false;
809 std::string map_filename;
810
811 log_header(design, "Executing XAIGER backend.\n");
812
813 size_t argidx;
814 for (argidx = 1; argidx < args.size(); argidx++)
815 {
816 if (args[argidx] == "-ascii") {
817 ascii_mode = true;
818 continue;
819 }
820 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
821 map_filename = args[++argidx];
822 continue;
823 }
824 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
825 map_filename = args[++argidx];
826 verbose_map = true;
827 continue;
828 }
829 break;
830 }
831 extra_args(f, filename, args, argidx);
832
833 Module *top_module = design->top_module();
834
835 if (top_module == nullptr)
836 log_error("Can't find top module in current design!\n");
837
838 XAigerWriter writer(top_module);
839 writer.write_aiger(*f, ascii_mode);
840
841 if (!map_filename.empty()) {
842 std::ofstream mapf;
843 mapf.open(map_filename.c_str(), std::ofstream::trunc);
844 if (mapf.fail())
845 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
846 writer.write_map(mapf, verbose_map);
847 }
848 }
849 } XAigerBackend;
850
851 PRIVATE_NAMESPACE_END