Merge pull request #2817 from YosysHQ/claire/fixemails
[yosys.git] / backends / aiger / xaiger.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
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 #include "kernel/timinginfo.h"
51
52 USING_YOSYS_NAMESPACE
53 PRIVATE_NAMESPACE_BEGIN
54
55 inline int32_t to_big_endian(int32_t i32) {
56 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
57 return bswap32(i32);
58 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
59 return i32;
60 #else
61 #error "Unknown endianness"
62 #endif
63 }
64
65 void aiger_encode(std::ostream &f, int x)
66 {
67 log_assert(x >= 0);
68
69 while (x & ~0x7f) {
70 f.put((x & 0x7f) | 0x80);
71 x = x >> 7;
72 }
73
74 f.put(x);
75 }
76
77 struct XAigerWriter
78 {
79 Design *design;
80 Module *module;
81 SigMap sigmap;
82
83 dict<SigBit, State> init_map;
84 pool<SigBit> input_bits, output_bits;
85 dict<SigBit, SigBit> not_map, alias_map;
86 dict<SigBit, pair<SigBit, SigBit>> and_map;
87 vector<SigBit> ci_bits, co_bits;
88 vector<Cell*> ff_list;
89 dict<SigBit, float> arrival_times;
90
91 vector<pair<int, int>> aig_gates;
92 vector<int> aig_outputs;
93 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
94
95 dict<SigBit, int> aig_map;
96 dict<SigBit, int> ordered_outputs;
97
98 vector<Cell*> box_list;
99
100 int mkgate(int a0, int a1)
101 {
102 aig_m++, aig_a++;
103 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
104 return 2*aig_m;
105 }
106
107 int bit2aig(SigBit bit)
108 {
109 auto it = aig_map.find(bit);
110 if (it != aig_map.end()) {
111 log_assert(it->second >= 0);
112 return it->second;
113 }
114
115 // NB: Cannot use iterator returned from aig_map.insert()
116 // since this function is called recursively
117
118 int a = -1;
119 if (not_map.count(bit)) {
120 a = bit2aig(not_map.at(bit)) ^ 1;
121 } else
122 if (and_map.count(bit)) {
123 auto args = and_map.at(bit);
124 int a0 = bit2aig(args.first);
125 int a1 = bit2aig(args.second);
126 a = mkgate(a0, a1);
127 } else
128 if (alias_map.count(bit)) {
129 a = bit2aig(alias_map.at(bit));
130 }
131
132 if (bit == State::Sx || bit == State::Sz) {
133 log_debug("Design contains 'x' or 'z' bits. Treating as 1'b0.\n");
134 a = aig_map.at(State::S0);
135 }
136
137 log_assert(a >= 0);
138 aig_map[bit] = a;
139 return a;
140 }
141
142 XAigerWriter(Module *module, bool dff_mode) : design(module->design), module(module), sigmap(module)
143 {
144 pool<SigBit> undriven_bits;
145 pool<SigBit> unused_bits;
146
147 // promote public wires
148 for (auto wire : module->wires())
149 if (wire->name.isPublic())
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 auto it = wire->attributes.find(ID::init);
164 for (int i = 0; i < GetSize(wire); i++)
165 {
166 SigBit wirebit(wire, i);
167 SigBit bit = sigmap(wirebit);
168
169 if (bit.wire == nullptr) {
170 if (wire->port_output) {
171 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
172 output_bits.insert(wirebit);
173 }
174 continue;
175 }
176
177 undriven_bits.insert(bit);
178 unused_bits.insert(bit);
179
180 if (wire->port_input)
181 input_bits.insert(bit);
182
183 bool keep = wire->get_bool_attribute(ID::keep);
184 if (wire->port_output || keep) {
185 if (bit != wirebit)
186 alias_map[wirebit] = bit;
187 output_bits.insert(wirebit);
188 }
189
190 if (it != wire->attributes.end()) {
191 auto s = it->second[i];
192 if (s != State::Sx) {
193 auto r = init_map.insert(std::make_pair(bit, it->second[i]));
194 if (!r.second && r.first->second != it->second[i])
195 log_error("Bit '%s' has a conflicting (* init *) value.\n", log_signal(bit));
196 }
197 }
198 }
199 }
200
201 TimingInfo timing;
202
203 for (auto cell : module->cells()) {
204 if (!cell->has_keep_attr()) {
205 if (cell->type == ID($_NOT_))
206 {
207 SigBit A = sigmap(cell->getPort(ID::A).as_bit());
208 SigBit Y = sigmap(cell->getPort(ID::Y).as_bit());
209 unused_bits.erase(A);
210 undriven_bits.erase(Y);
211 not_map[Y] = A;
212 continue;
213 }
214
215 if (cell->type == ID($_AND_))
216 {
217 SigBit A = sigmap(cell->getPort(ID::A).as_bit());
218 SigBit B = sigmap(cell->getPort(ID::B).as_bit());
219 SigBit Y = sigmap(cell->getPort(ID::Y).as_bit());
220 unused_bits.erase(A);
221 unused_bits.erase(B);
222 undriven_bits.erase(Y);
223 and_map[Y] = make_pair(A, B);
224 continue;
225 }
226
227 if (dff_mode && cell->type.in(ID($_DFF_N_), ID($_DFF_P_)) && !cell->get_bool_attribute(ID::abc9_keep))
228 {
229 SigBit D = sigmap(cell->getPort(ID::D).as_bit());
230 SigBit Q = sigmap(cell->getPort(ID::Q).as_bit());
231 unused_bits.erase(D);
232 undriven_bits.erase(Q);
233 alias_map[Q] = D;
234 ff_list.emplace_back(cell);
235 continue;
236 }
237
238 if (cell->type.in(ID($specify2), ID($specify3), ID($specrule)))
239 continue;
240 }
241
242 RTLIL::Module* inst_module = design->module(cell->type);
243 if (inst_module && inst_module->get_blackbox_attribute()) {
244 bool abc9_flop = false;
245
246 auto it = cell->attributes.find(ID::abc9_box_seq);
247 if (it != cell->attributes.end()) {
248 log_assert(!cell->has_keep_attr());
249 log_assert(cell->parameters.empty());
250 int abc9_box_seq = it->second.as_int();
251 if (GetSize(box_list) <= abc9_box_seq)
252 box_list.resize(abc9_box_seq+1);
253 box_list[abc9_box_seq] = cell;
254 // Only flop boxes may have arrival times
255 // (all others are combinatorial)
256 log_assert(cell->parameters.empty());
257 abc9_flop = inst_module->get_bool_attribute(ID::abc9_flop);
258 if (!abc9_flop)
259 continue;
260 }
261
262 if (!timing.count(inst_module->name))
263 timing.setup_module(inst_module);
264 auto &t = timing.at(inst_module->name).arrival;
265 for (const auto &conn : cell->connections()) {
266 auto port_wire = inst_module->wire(conn.first);
267 if (!port_wire->port_output)
268 continue;
269
270 for (int i = 0; i < GetSize(conn.second); i++) {
271 auto d = t.at(TimingInfo::NameBit(conn.first,i), 0);
272 if (d == 0)
273 continue;
274
275 #ifndef NDEBUG
276 if (ys_debug(1)) {
277 static std::set<std::tuple<IdString,IdString,int>> seen;
278 if (seen.emplace(inst_module->name, conn.first, i).second) log("%s.%s[%d] abc9_arrival = %d\n",
279 log_id(cell->type), log_id(conn.first), i, d);
280 }
281 #endif
282 arrival_times[conn.second[i]] = d;
283 }
284 }
285
286 if (abc9_flop)
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 // Do not add as PO if bit is already a PI
304 if (input_bits.count(b))
305 continue;
306 if (!w->port_output || !cell_known) {
307 SigBit I = sigmap(b);
308 if (I != b)
309 alias_map[b] = I;
310 output_bits.insert(b);
311 }
312 }
313 }
314
315 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
316 }
317
318 dict<IdString, std::vector<IdString>> box_ports;
319 for (auto cell : box_list) {
320 log_assert(cell);
321
322 RTLIL::Module* box_module = design->module(cell->type);
323 log_assert(box_module);
324 log_assert(box_module->has_attribute(ID::abc9_box_id));
325
326 auto r = box_ports.insert(cell->type);
327 if (r.second) {
328 // Make carry in the last PI, and carry out the last PO
329 // since ABC requires it this way
330 IdString carry_in, carry_out;
331 for (const auto &port_name : box_module->ports) {
332 auto w = box_module->wire(port_name);
333 log_assert(w);
334 if (w->get_bool_attribute(ID::abc9_carry)) {
335 if (w->port_input) {
336 if (carry_in != IdString())
337 log_error("Module '%s' contains more than one 'abc9_carry' input port.\n", log_id(box_module));
338 carry_in = port_name;
339 }
340 if (w->port_output) {
341 if (carry_out != IdString())
342 log_error("Module '%s' contains more than one 'abc9_carry' output port.\n", log_id(box_module));
343 carry_out = port_name;
344 }
345 }
346 else
347 r.first->second.push_back(port_name);
348 }
349
350 if (carry_in != IdString() && carry_out == IdString())
351 log_error("Module '%s' contains an 'abc9_carry' input port but no output port.\n", log_id(box_module));
352 if (carry_in == IdString() && carry_out != IdString())
353 log_error("Module '%s' contains an 'abc9_carry' output port but no input port.\n", log_id(box_module));
354 if (carry_in != IdString()) {
355 r.first->second.push_back(carry_in);
356 r.first->second.push_back(carry_out);
357 }
358 }
359
360 for (auto port_name : r.first->second) {
361 auto w = box_module->wire(port_name);
362 log_assert(w);
363 auto rhs = cell->connections_.at(port_name, SigSpec());
364 rhs.append(Const(State::Sx, GetSize(w)-GetSize(rhs)));
365 if (w->port_input)
366 for (auto b : rhs) {
367 SigBit I = sigmap(b);
368 if (b == RTLIL::Sx)
369 b = State::S0;
370 else if (I != b) {
371 if (I == RTLIL::Sx)
372 alias_map[b] = State::S0;
373 else
374 alias_map[b] = I;
375 }
376 co_bits.emplace_back(b);
377 unused_bits.erase(I);
378 }
379 if (w->port_output)
380 for (const auto &b : rhs) {
381 SigBit O = sigmap(b);
382 if (O != b)
383 alias_map[O] = b;
384 ci_bits.emplace_back(b);
385 undriven_bits.erase(O);
386 }
387 }
388 }
389
390 for (auto bit : input_bits)
391 undriven_bits.erase(bit);
392 for (auto bit : output_bits)
393 unused_bits.erase(sigmap(bit));
394 for (auto bit : unused_bits)
395 undriven_bits.erase(bit);
396
397 // Make all undriven bits a primary input
398 for (auto bit : undriven_bits) {
399 input_bits.insert(bit);
400 undriven_bits.erase(bit);
401 }
402
403 struct sort_by_port_id {
404 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
405 return a.wire->port_id < b.wire->port_id ||
406 (a.wire->port_id == b.wire->port_id && a.offset < b.offset);
407 }
408 };
409 input_bits.sort(sort_by_port_id());
410 output_bits.sort(sort_by_port_id());
411
412 aig_map[State::S0] = 0;
413 aig_map[State::S1] = 1;
414
415 for (const auto &bit : input_bits) {
416 aig_m++, aig_i++;
417 log_assert(!aig_map.count(bit));
418 aig_map[bit] = 2*aig_m;
419 }
420
421 for (auto cell : ff_list) {
422 const SigBit &q = sigmap(cell->getPort(ID::Q));
423 aig_m++, aig_i++;
424 log_assert(!aig_map.count(q));
425 aig_map[q] = 2*aig_m;
426 }
427
428 for (auto &bit : ci_bits) {
429 aig_m++, aig_i++;
430 // 1'bx may exist here due to a box output
431 // that has been padded to its full width
432 if (bit == State::Sx)
433 continue;
434 if (aig_map.count(bit))
435 log_error("Visited AIG node more than once; this could be a combinatorial loop that has not been broken\n");
436 aig_map[bit] = 2*aig_m;
437 }
438
439 for (auto bit : co_bits) {
440 ordered_outputs[bit] = aig_o++;
441 aig_outputs.push_back(bit2aig(bit));
442 }
443
444 for (const auto &bit : output_bits) {
445 ordered_outputs[bit] = aig_o++;
446 int aig;
447 // Unlike bit2aig() which checks aig_map first for
448 // inout/scc bits, since aig_map will point to
449 // the PI, first attempt to find the NOT/AND driver
450 // before resorting to an aig_map lookup (which
451 // could be another PO)
452 if (input_bits.count(bit)) {
453 if (not_map.count(bit)) {
454 aig = bit2aig(not_map.at(bit)) ^ 1;
455 } else if (and_map.count(bit)) {
456 auto args = and_map.at(bit);
457 int a0 = bit2aig(args.first);
458 int a1 = bit2aig(args.second);
459 aig = mkgate(a0, a1);
460 }
461 else
462 aig = aig_map.at(bit);
463 }
464 else
465 aig = bit2aig(bit);
466 aig_outputs.push_back(aig);
467 }
468
469 for (auto cell : ff_list) {
470 const SigBit &d = sigmap(cell->getPort(ID::D));
471 aig_o++;
472 aig_outputs.push_back(aig_map.at(d));
473 }
474 }
475
476 void write_aiger(std::ostream &f, bool ascii_mode)
477 {
478 int aig_obc = aig_o;
479 int aig_obcj = aig_obc;
480 int aig_obcjf = aig_obcj;
481
482 log_assert(aig_m == aig_i + aig_l + aig_a);
483 log_assert(aig_obcjf == GetSize(aig_outputs));
484
485 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
486 f << stringf("\n");
487
488 if (ascii_mode)
489 {
490 for (int i = 0; i < aig_i; i++)
491 f << stringf("%d\n", 2*i+2);
492
493 for (int i = 0; i < aig_obc; i++)
494 f << stringf("%d\n", aig_outputs.at(i));
495
496 for (int i = aig_obc; i < aig_obcj; i++)
497 f << stringf("1\n");
498
499 for (int i = aig_obc; i < aig_obcj; i++)
500 f << stringf("%d\n", aig_outputs.at(i));
501
502 for (int i = aig_obcj; i < aig_obcjf; i++)
503 f << stringf("%d\n", aig_outputs.at(i));
504
505 for (int i = 0; i < aig_a; i++)
506 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
507 }
508 else
509 {
510 for (int i = 0; i < aig_obc; i++)
511 f << stringf("%d\n", aig_outputs.at(i));
512
513 for (int i = aig_obc; i < aig_obcj; i++)
514 f << stringf("1\n");
515
516 for (int i = aig_obc; i < aig_obcj; i++)
517 f << stringf("%d\n", aig_outputs.at(i));
518
519 for (int i = aig_obcj; i < aig_obcjf; i++)
520 f << stringf("%d\n", aig_outputs.at(i));
521
522 for (int i = 0; i < aig_a; i++) {
523 int lhs = 2*(aig_i+aig_l+i)+2;
524 int rhs0 = aig_gates.at(i).first;
525 int rhs1 = aig_gates.at(i).second;
526 int delta0 = lhs - rhs0;
527 int delta1 = rhs0 - rhs1;
528 aiger_encode(f, delta0);
529 aiger_encode(f, delta1);
530 }
531 }
532
533 f << "c";
534
535 auto write_buffer = [](std::stringstream &buffer, int i32) {
536 int32_t i32_be = to_big_endian(i32);
537 buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
538 };
539 std::stringstream h_buffer;
540 auto write_h_buffer = std::bind(write_buffer, std::ref(h_buffer), std::placeholders::_1);
541 write_h_buffer(1);
542 log_debug("ciNum = %d\n", GetSize(input_bits) + GetSize(ff_list) + GetSize(ci_bits));
543 write_h_buffer(GetSize(input_bits) + GetSize(ff_list) + GetSize(ci_bits));
544 log_debug("coNum = %d\n", GetSize(output_bits) + GetSize(ff_list) + GetSize(co_bits));
545 write_h_buffer(GetSize(output_bits) + GetSize(ff_list) + GetSize(co_bits));
546 log_debug("piNum = %d\n", GetSize(input_bits) + GetSize(ff_list));
547 write_h_buffer(GetSize(input_bits) + GetSize(ff_list));
548 log_debug("poNum = %d\n", GetSize(output_bits) + GetSize(ff_list));
549 write_h_buffer(GetSize(output_bits) + GetSize(ff_list));
550 log_debug("boxNum = %d\n", GetSize(box_list));
551 write_h_buffer(GetSize(box_list));
552
553 auto write_buffer_float = [](std::stringstream &buffer, float f32) {
554 buffer.write(reinterpret_cast<const char*>(&f32), sizeof(f32));
555 };
556 std::stringstream i_buffer;
557 auto write_i_buffer = std::bind(write_buffer_float, std::ref(i_buffer), std::placeholders::_1);
558 for (auto bit : input_bits)
559 write_i_buffer(arrival_times.at(bit, 0));
560 //std::stringstream o_buffer;
561 //auto write_o_buffer = std::bind(write_buffer_float, std::ref(o_buffer), std::placeholders::_1);
562 //for (auto bit : output_bits)
563 // write_o_buffer(0);
564
565 if (!box_list.empty() || !ff_list.empty()) {
566 dict<IdString, std::tuple<int,int,int>> cell_cache;
567
568 int box_count = 0;
569 for (auto cell : box_list) {
570 log_assert(cell);
571 log_assert(cell->parameters.empty());
572
573 auto r = cell_cache.insert(cell->type);
574 auto &v = r.first->second;
575 if (r.second) {
576 RTLIL::Module* box_module = design->module(cell->type);
577 log_assert(box_module);
578
579 int box_inputs = 0, box_outputs = 0;
580 for (auto port_name : box_module->ports) {
581 RTLIL::Wire *w = box_module->wire(port_name);
582 log_assert(w);
583 if (w->port_input)
584 box_inputs += GetSize(w);
585 if (w->port_output)
586 box_outputs += GetSize(w);
587 }
588
589 std::get<0>(v) = box_inputs;
590 std::get<1>(v) = box_outputs;
591 std::get<2>(v) = box_module->attributes.at(ID::abc9_box_id).as_int();
592 }
593
594 write_h_buffer(std::get<0>(v));
595 write_h_buffer(std::get<1>(v));
596 write_h_buffer(std::get<2>(v));
597 write_h_buffer(box_count++);
598 }
599
600 std::stringstream r_buffer;
601 auto write_r_buffer = std::bind(write_buffer, std::ref(r_buffer), std::placeholders::_1);
602 log_debug("flopNum = %d\n", GetSize(ff_list));
603 write_r_buffer(ff_list.size());
604
605 std::stringstream s_buffer;
606 auto write_s_buffer = std::bind(write_buffer, std::ref(s_buffer), std::placeholders::_1);
607 write_s_buffer(ff_list.size());
608
609 dict<SigSpec, int> clk_to_mergeability;
610 for (const auto cell : ff_list) {
611 const SigBit &d = sigmap(cell->getPort(ID::D));
612 const SigBit &q = sigmap(cell->getPort(ID::Q));
613
614 SigSpec clk_and_pol{sigmap(cell->getPort(ID::C)), cell->type[6] == 'P' ? State::S1 : State::S0};
615 auto r = clk_to_mergeability.insert(std::make_pair(clk_and_pol, clk_to_mergeability.size()+1));
616 int mergeability = r.first->second;
617 log_assert(mergeability > 0);
618 write_r_buffer(mergeability);
619
620 State init = init_map.at(q, State::Sx);
621 log_debug("Cell '%s' (type %s) has (* init *) value '%s'.\n", log_id(cell), log_id(cell->type), log_signal(init));
622 if (init == State::S1)
623 write_s_buffer(1);
624 else if (init == State::S0)
625 write_s_buffer(0);
626 else {
627 log_assert(init == State::Sx);
628 write_s_buffer(2);
629 }
630
631 // Use arrival time from output of flop box
632 write_i_buffer(arrival_times.at(d, 0));
633 //write_o_buffer(0);
634 }
635
636 f << "r";
637 std::string buffer_str = r_buffer.str();
638 int32_t buffer_size_be = to_big_endian(buffer_str.size());
639 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
640 f.write(buffer_str.data(), buffer_str.size());
641
642 f << "s";
643 buffer_str = s_buffer.str();
644 buffer_size_be = to_big_endian(buffer_str.size());
645 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
646 f.write(buffer_str.data(), buffer_str.size());
647
648 RTLIL::Design *holes_design;
649 auto it = saved_designs.find("$abc9_holes");
650 if (it != saved_designs.end())
651 holes_design = it->second;
652 else
653 holes_design = nullptr;
654 RTLIL::Module *holes_module = holes_design ? holes_design->module(module->name) : nullptr;
655 if (holes_module) {
656 std::stringstream a_buffer;
657 XAigerWriter writer(holes_module, false /* dff_mode */);
658 writer.write_aiger(a_buffer, false /*ascii_mode*/);
659
660 f << "a";
661 std::string buffer_str = a_buffer.str();
662 int32_t buffer_size_be = to_big_endian(buffer_str.size());
663 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
664 f.write(buffer_str.data(), buffer_str.size());
665 }
666 }
667
668 f << "h";
669 std::string buffer_str = h_buffer.str();
670 int32_t buffer_size_be = to_big_endian(buffer_str.size());
671 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
672 f.write(buffer_str.data(), buffer_str.size());
673
674 f << "i";
675 buffer_str = i_buffer.str();
676 buffer_size_be = to_big_endian(buffer_str.size());
677 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
678 f.write(buffer_str.data(), buffer_str.size());
679 //f << "o";
680 //buffer_str = o_buffer.str();
681 //buffer_size_be = to_big_endian(buffer_str.size());
682 //f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
683 //f.write(buffer_str.data(), buffer_str.size());
684
685 f << stringf("Generated by %s\n", yosys_version_str);
686
687 design->scratchpad_set_int("write_xaiger.num_ands", and_map.size());
688 design->scratchpad_set_int("write_xaiger.num_wires", aig_map.size());
689 design->scratchpad_set_int("write_xaiger.num_inputs", input_bits.size());
690 design->scratchpad_set_int("write_xaiger.num_outputs", output_bits.size());
691 }
692
693 void write_map(std::ostream &f)
694 {
695 dict<int, string> input_lines;
696 dict<int, string> output_lines;
697
698 for (auto wire : module->wires())
699 {
700 for (int i = 0; i < GetSize(wire); i++)
701 {
702 RTLIL::SigBit b(wire, i);
703 if (input_bits.count(b)) {
704 int a = aig_map.at(b);
705 log_assert((a & 1) == 0);
706 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, wire->start_offset+i, log_id(wire));
707 }
708
709 if (output_bits.count(b)) {
710 int o = ordered_outputs.at(b);
711 output_lines[o] += stringf("output %d %d %s\n", o - GetSize(co_bits), wire->start_offset+i, log_id(wire));
712 }
713 }
714 }
715
716 input_lines.sort();
717 for (auto &it : input_lines)
718 f << it.second;
719 log_assert(input_lines.size() == input_bits.size());
720
721 int box_count = 0;
722 for (auto cell : box_list)
723 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
724
725 output_lines.sort();
726 for (auto &it : output_lines)
727 f << it.second;
728 log_assert(output_lines.size() == output_bits.size());
729 }
730 };
731
732 struct XAigerBackend : public Backend {
733 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
734 void help() override
735 {
736 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
737 log("\n");
738 log(" write_xaiger [options] [filename]\n");
739 log("\n");
740 log("Write the top module (according to the (* top *) attribute or if only one module\n");
741 log("is currently selected) to an XAIGER file. Any non $_NOT_, $_AND_, (optionally\n");
742 log("$_DFF_N_, $_DFF_P_), or non (* abc9_box *) cells will be converted into psuedo-\n");
743 log("inputs and pseudo-outputs. Whitebox contents will be taken from the equivalent\n");
744 log("module in the '$abc9_holes' design, if it exists.\n");
745 log("\n");
746 log(" -ascii\n");
747 log(" write ASCII version of AIGER format\n");
748 log("\n");
749 log(" -map <filename>\n");
750 log(" write an extra file with port and box symbols\n");
751 log("\n");
752 log(" -dff\n");
753 log(" write $_DFF_[NP]_ cells\n");
754 log("\n");
755 }
756 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
757 {
758 bool ascii_mode = false, dff_mode = false;
759 std::string map_filename;
760
761 log_header(design, "Executing XAIGER backend.\n");
762
763 size_t argidx;
764 for (argidx = 1; argidx < args.size(); argidx++)
765 {
766 if (args[argidx] == "-ascii") {
767 ascii_mode = true;
768 continue;
769 }
770 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
771 map_filename = args[++argidx];
772 continue;
773 }
774 if (args[argidx] == "-dff") {
775 dff_mode = true;
776 continue;
777 }
778 break;
779 }
780 extra_args(f, filename, args, argidx, !ascii_mode);
781
782 Module *top_module = design->top_module();
783
784 if (top_module == nullptr)
785 log_error("Can't find top module in current design!\n");
786
787 if (!design->selected_whole_module(top_module))
788 log_cmd_error("Can't handle partially selected module %s!\n", log_id(top_module));
789
790 if (!top_module->processes.empty())
791 log_error("Found unmapped processes in module %s: unmapped processes are not supported in XAIGER backend!\n", log_id(top_module));
792 if (!top_module->memories.empty())
793 log_error("Found unmapped memories in module %s: unmapped memories are not supported in XAIGER backend!\n", log_id(top_module));
794
795 XAigerWriter writer(top_module, dff_mode);
796 writer.write_aiger(*f, ascii_mode);
797
798 if (!map_filename.empty()) {
799 std::ofstream mapf;
800 mapf.open(map_filename.c_str(), std::ofstream::trunc);
801 if (mapf.fail())
802 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
803 writer.write_map(mapf);
804 }
805 }
806 } XAigerBackend;
807
808 PRIVATE_NAMESPACE_END