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