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