bf2f9f1bc1d20746ec9494d0a480aca48b631e07
[yosys.git] / backends / aiger / xaiger.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * Copyright (C) 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 #include "kernel/yosys.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/utils.h"
25
26 USING_YOSYS_NAMESPACE
27 PRIVATE_NAMESPACE_BEGIN
28
29 void aiger_encode(std::ostream &f, int x)
30 {
31 log_assert(x >= 0);
32
33 while (x & ~0x7f) {
34 f.put((x & 0x7f) | 0x80);
35 x = x >> 7;
36 }
37
38 f.put(x);
39 }
40
41 struct XAigerWriter
42 {
43 Module *module;
44 bool zinit_mode;
45 SigMap sigmap;
46
47 dict<SigBit, bool> init_map;
48 pool<SigBit> input_bits, output_bits;
49 dict<SigBit, SigBit> not_map, ff_map, alias_map;
50 dict<SigBit, pair<SigBit, SigBit>> and_map;
51 //pool<SigBit> initstate_bits;
52 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int>> ci_bits;
53 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int,int>> co_bits;
54 vector<std::pair<SigBit,SigBit>> ff_bits;
55
56 vector<pair<int, int>> aig_gates;
57 vector<int> aig_latchin, aig_latchinit, aig_outputs;
58 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
59
60 dict<SigBit, int> aig_map;
61 dict<SigBit, int> ordered_outputs;
62 dict<SigBit, int> ordered_latches;
63
64 vector<Cell*> box_list;
65
66 //dict<SigBit, int> init_inputs;
67 //int initstate_ff = 0;
68
69 int mkgate(int a0, int a1)
70 {
71 aig_m++, aig_a++;
72 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
73 return 2*aig_m;
74 }
75
76 int bit2aig(SigBit bit)
77 {
78 if (aig_map.count(bit) == 0)
79 {
80 aig_map[bit] = -1;
81
82 //if (initstate_bits.count(bit)) {
83 // log_assert(initstate_ff > 0);
84 // aig_map[bit] = initstate_ff;
85 //} else
86 if (not_map.count(bit)) {
87 int a = bit2aig(not_map.at(bit)) ^ 1;
88 aig_map[bit] = a;
89 } else
90 if (and_map.count(bit)) {
91 auto args = and_map.at(bit);
92 int a0 = bit2aig(args.first);
93 int a1 = bit2aig(args.second);
94 aig_map[bit] = mkgate(a0, a1);
95 } else
96 if (alias_map.count(bit)) {
97 aig_map[bit] = bit2aig(alias_map.at(bit));
98 }
99
100 if (bit == State::Sx || bit == State::Sz)
101 log_error("Design contains 'x' or 'z' bits. Use 'setundef' to replace those constants.\n");
102 }
103
104 log_assert(aig_map.at(bit) >= 0);
105 return aig_map.at(bit);
106 }
107
108 XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode, bool holes_mode=false) : module(module), zinit_mode(zinit_mode), sigmap(module)
109 {
110 pool<SigBit> undriven_bits;
111 pool<SigBit> unused_bits;
112
113 // promote public wires
114 for (auto wire : module->wires())
115 if (wire->name[0] == '\\')
116 sigmap.add(wire);
117
118 // promote input wires
119 for (auto wire : module->wires())
120 if (wire->port_input)
121 sigmap.add(wire);
122
123 // promote output wires
124 for (auto wire : module->wires())
125 if (wire->port_output)
126 sigmap.add(wire);
127
128 for (auto wire : module->wires())
129 {
130 if (wire->attributes.count("\\init")) {
131 SigSpec initsig = sigmap(wire);
132 Const initval = wire->attributes.at("\\init");
133 for (int i = 0; i < GetSize(wire) && i < GetSize(initval); i++)
134 if (initval[i] == State::S0 || initval[i] == State::S1)
135 init_map[initsig[i]] = initval[i] == State::S1;
136 }
137
138 bool keep = wire->attributes.count("\\keep");
139
140 for (int i = 0; i < GetSize(wire); i++)
141 {
142 SigBit wirebit(wire, i);
143 SigBit bit = sigmap(wirebit);
144
145 if (bit.wire == nullptr) {
146 if (wire->port_output) {
147 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
148 output_bits.insert(wirebit);
149 }
150 continue;
151 }
152
153 undriven_bits.insert(bit);
154 unused_bits.insert(bit);
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 != wirebit)
164 alias_map[wirebit] = bit;
165 output_bits.insert(wirebit);
166 }
167 }
168 }
169
170 for (auto bit : input_bits)
171 undriven_bits.erase(sigmap(bit));
172
173 for (auto bit : output_bits)
174 if (!bit.wire->port_input)
175 unused_bits.erase(bit);
176
177 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
178 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
179 bool abc_box_seen = false;
180
181 for (auto cell : module->cells())
182 {
183 RTLIL::Module* inst_module = module->design->module(cell->type);
184 bool builtin_type = yosys_celltypes.cell_known(cell->type);
185 bool abc_type = inst_module && inst_module->attributes.count("\\abc_box_id");
186
187 if (!holes_mode) {
188 toposort.node(cell->name);
189 for (const auto &conn : cell->connections()) {
190 if (!builtin_type && !abc_type)
191 continue;
192
193 if (!cell->type.in("$_NOT_", "$_AND_")) {
194 if (builtin_type) {
195 if (conn.first.in("\\Q", "\\CTRL_OUT", "\\RD_DATA"))
196 continue;
197 if (cell->type == "$memrd" && conn.first == "\\DATA")
198 continue;
199 }
200
201 if (inst_module) {
202 RTLIL::Wire* inst_module_port = inst_module->wire(conn.first);
203 log_assert(inst_module_port);
204
205 if (inst_module_port->port_output && inst_module_port->attributes.count("\\abc_flop_q"))
206 continue;
207 }
208 }
209
210 if (cell->input(conn.first)) {
211 // Ignore inout for the sake of topographical ordering
212 if (cell->output(conn.first)) continue;
213 for (auto bit : sigmap(conn.second))
214 bit_users[bit].insert(cell->name);
215 }
216
217 if (cell->output(conn.first))
218 for (auto bit : sigmap(conn.second))
219 bit_drivers[bit].insert(cell->name);
220 }
221 }
222
223 if (cell->type == "$_NOT_")
224 {
225 SigBit A = sigmap(cell->getPort("\\A").as_bit());
226 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
227 unused_bits.erase(A);
228 undriven_bits.erase(Y);
229 not_map[Y] = A;
230 continue;
231 }
232
233 //if (cell->type.in("$_FF_", "$_DFF_N_", "$_DFF_P_"))
234 //{
235 // SigBit D = sigmap(cell->getPort("\\D").as_bit());
236 // SigBit Q = sigmap(cell->getPort("\\Q").as_bit());
237 // unused_bits.erase(D);
238 // undriven_bits.erase(Q);
239 // ff_map[Q] = D;
240 // continue;
241 //}
242
243 if (cell->type == "$_AND_")
244 {
245 SigBit A = sigmap(cell->getPort("\\A").as_bit());
246 SigBit B = sigmap(cell->getPort("\\B").as_bit());
247 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
248 unused_bits.erase(A);
249 unused_bits.erase(B);
250 undriven_bits.erase(Y);
251 and_map[Y] = make_pair(A, B);
252 continue;
253 }
254
255 //if (cell->type == "$initstate")
256 //{
257 // SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
258 // undriven_bits.erase(Y);
259 // initstate_bits.insert(Y);
260 // continue;
261 //}
262
263 bool inst_flop = inst_module ? inst_module->attributes.count("\\abc_flop") : false;
264 if (inst_flop) {
265 SigBit d, q;
266 for (const auto &c : cell->connections()) {
267 auto is_input = cell->input(c.first);
268 auto is_output = cell->output(c.first);
269 log_assert(is_input || is_output);
270 RTLIL::Wire* port = inst_module->wire(c.first);
271 for (auto b : c.second.bits()) {
272 if (is_input && port->attributes.count("\\abc_flop_d")) {
273 d = b;
274 SigBit I = sigmap(d);
275 if (I != d)
276 alias_map[I] = d;
277 unused_bits.erase(d);
278 }
279 if (is_output && port->attributes.count("\\abc_flop_q")) {
280 q = b;
281 SigBit O = sigmap(q);
282 if (O != q)
283 alias_map[O] = q;
284 undriven_bits.erase(O);
285 }
286 }
287 }
288 if (!abc_box_seen)
289 abc_box_seen = inst_module->attributes.count("\\abc_box_id");
290
291 ff_bits.emplace_back(d, q);
292 }
293 else if (inst_module && inst_module->attributes.count("\\abc_box_id")) {
294 abc_box_seen = true;
295 }
296 else {
297 for (const auto &c : cell->connections()) {
298 if (c.second.is_fully_const()) continue;
299 for (auto b : c.second.bits()) {
300 Wire *w = b.wire;
301 if (!w) continue;
302 auto is_input = cell->input(c.first);
303 auto is_output = cell->output(c.first);
304 log_assert(is_input || is_output);
305 if (is_input) {
306 if (!w->port_input) {
307 SigBit I = sigmap(b);
308 if (I != b)
309 alias_map[b] = I;
310 output_bits.insert(b);
311 unused_bits.erase(b);
312 }
313 }
314 if (is_output) {
315 input_bits.insert(b);
316 SigBit O = sigmap(b);
317 if (O != b)
318 alias_map[O] = b;
319 undriven_bits.erase(O);
320 }
321 }
322 }
323 }
324
325 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
326 }
327
328 if (abc_box_seen) {
329 for (auto &it : bit_users)
330 if (bit_drivers.count(it.first))
331 for (auto driver_cell : bit_drivers.at(it.first))
332 for (auto user_cell : it.second)
333 toposort.edge(driver_cell, user_cell);
334
335 pool<RTLIL::Module*> abc_carry_modules;
336
337 #if 0
338 toposort.analyze_loops = true;
339 #endif
340 bool no_loops = toposort.sort();
341 #if 0
342 unsigned i = 0;
343 for (auto &it : toposort.loops) {
344 log(" loop %d", i++);
345 for (auto cell : it)
346 log(" %s", log_id(cell));
347 log("\n");
348 }
349 #endif
350 log_assert(no_loops);
351
352 for (auto cell_name : toposort.sorted) {
353 RTLIL::Cell *cell = module->cell(cell_name);
354 RTLIL::Module* box_module = module->design->module(cell->type);
355 if (!box_module || !box_module->attributes.count("\\abc_box_id"))
356 continue;
357
358 if (box_module->attributes.count("\\abc_carry") && !abc_carry_modules.count(box_module)) {
359 RTLIL::Wire* carry_in = nullptr, *carry_out = nullptr;
360 RTLIL::Wire* last_in = nullptr, *last_out = nullptr;
361 for (const auto &port_name : box_module->ports) {
362 RTLIL::Wire* w = box_module->wire(port_name);
363 log_assert(w);
364 if (w->port_input) {
365 if (w->attributes.count("\\abc_carry_in")) {
366 log_assert(!carry_in);
367 carry_in = w;
368 }
369 log_assert(!last_in || last_in->port_id < w->port_id);
370 last_in = w;
371 }
372 if (w->port_output) {
373 if (w->attributes.count("\\abc_carry_out")) {
374 log_assert(!carry_out);
375 carry_out = w;
376 }
377 log_assert(!last_out || last_out->port_id < w->port_id);
378 last_out = w;
379 }
380 }
381
382 if (carry_in) {
383 log_assert(last_in);
384 std::swap(box_module->ports[carry_in->port_id-1], box_module->ports[last_in->port_id-1]);
385 std::swap(carry_in->port_id, last_in->port_id);
386 }
387 if (carry_out) {
388 log_assert(last_out);
389 std::swap(box_module->ports[carry_out->port_id-1], box_module->ports[last_out->port_id-1]);
390 std::swap(carry_out->port_id, last_out->port_id);
391 }
392 }
393
394 // Fully pad all unused input connections of this box cell with S0
395 // Fully pad all undriven output connections of this box cell with anonymous wires
396 // NB: Assume box_module->ports are sorted alphabetically
397 // (as RTLIL::Module::fixup_ports() would do)
398 for (const auto &port_name : box_module->ports) {
399 RTLIL::Wire* w = box_module->wire(port_name);
400 log_assert(w);
401 auto it = cell->connections_.find(port_name);
402 if (w->port_input) {
403 RTLIL::SigSpec rhs;
404 if (it != cell->connections_.end()) {
405 if (GetSize(it->second) < GetSize(w))
406 it->second.append(RTLIL::SigSpec(RTLIL::S0, GetSize(w)-GetSize(it->second)));
407 rhs = it->second;
408 }
409 else {
410 rhs = RTLIL::SigSpec(RTLIL::S0, GetSize(w));
411 cell->setPort(port_name, rhs);
412 }
413
414 int offset = 0;
415 for (const auto &b : rhs.bits()) {
416 SigBit I = sigmap(b);
417 if (I != b)
418 alias_map[b] = I;
419 co_bits.emplace_back(b, cell, port_name, offset++, 0);
420 unused_bits.erase(b);
421 }
422 }
423 if (w->port_output) {
424 RTLIL::SigSpec rhs;
425 auto it = cell->connections_.find(w->name);
426 if (it != cell->connections_.end()) {
427 if (GetSize(it->second) < GetSize(w))
428 it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
429 rhs = it->second;
430 }
431 else {
432 rhs = module->addWire(NEW_ID, GetSize(w));
433 cell->setPort(port_name, rhs);
434 }
435
436 int offset = 0;
437 for (const auto &b : rhs.bits()) {
438 ci_bits.emplace_back(b, cell, port_name, offset++);
439 SigBit O = sigmap(b);
440 if (O != b)
441 alias_map[O] = b;
442 undriven_bits.erase(O);
443
444 auto jt = input_bits.find(b);
445 if (jt != input_bits.end()) {
446 log_assert(b.wire->attributes.count("\\keep"));
447 input_bits.erase(b);
448 }
449 }
450 }
451 }
452 box_list.emplace_back(cell);
453 }
454
455 // TODO: Free memory from toposort, bit_drivers, bit_users
456 }
457
458 for (auto bit : input_bits) {
459 RTLIL::Wire *wire = bit.wire;
460 // If encountering an inout port, or a keep-ed wire, then create a new wire
461 // with $inout.out suffix, make it a PO driven by the existing inout, and
462 // inherit existing inout's drivers
463 if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
464 || wire->attributes.count("\\keep")) {
465 log_assert(input_bits.count(bit) && output_bits.count(bit));
466 RTLIL::IdString wire_name = wire->name.str() + "$inout.out";
467 RTLIL::Wire *new_wire = module->wire(wire_name);
468 if (!new_wire)
469 new_wire = module->addWire(wire_name, GetSize(wire));
470 SigBit new_bit(new_wire, bit.offset);
471 module->connect(new_bit, bit);
472 if (not_map.count(bit))
473 not_map[new_bit] = not_map.at(bit);
474 else if (and_map.count(bit))
475 and_map[new_bit] = and_map.at(bit);
476 else if (alias_map.count(bit))
477 alias_map[new_bit] = alias_map.at(bit);
478 else
479 //log_abort();
480 alias_map[new_bit] = bit;
481 output_bits.erase(bit);
482 output_bits.insert(new_bit);
483 }
484 }
485
486 // Erase all POs that are undriven
487 if (!holes_mode)
488 for (auto bit : undriven_bits)
489 output_bits.erase(bit);
490 for (auto bit : unused_bits)
491 undriven_bits.erase(bit);
492
493 if (!undriven_bits.empty() && !holes_mode) {
494 undriven_bits.sort();
495 for (auto bit : undriven_bits) {
496 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
497 input_bits.insert(bit);
498 }
499 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
500 }
501
502 init_map.sort();
503 if (holes_mode) {
504 struct sort_by_port_id {
505 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
506 return a.wire->port_id < b.wire->port_id;
507 }
508 };
509 input_bits.sort(sort_by_port_id());
510 output_bits.sort(sort_by_port_id());
511 }
512 else {
513 input_bits.sort();
514 output_bits.sort();
515 }
516
517 not_map.sort();
518 ff_map.sort();
519 and_map.sort();
520
521 aig_map[State::S0] = 0;
522 aig_map[State::S1] = 1;
523
524 for (auto bit : input_bits) {
525 aig_m++, aig_i++;
526 log_assert(!aig_map.count(bit));
527 aig_map[bit] = 2*aig_m;
528 }
529
530 for (auto &f : ff_bits) {
531 RTLIL::SigBit bit = f.second;
532 aig_m++, aig_i++;
533 log_assert(!aig_map.count(bit));
534 aig_map[bit] = 2*aig_m;
535 }
536
537 dict<SigBit, int> ff_aig_map;
538 for (auto &c : ci_bits) {
539 RTLIL::SigBit bit = std::get<0>(c);
540 aig_m++, aig_i++;
541 auto r = aig_map.insert(std::make_pair(bit, 2*aig_m));
542 if (!r.second)
543 ff_aig_map[bit] = 2*aig_m;
544 }
545
546 if (imode && input_bits.empty()) {
547 aig_m++, aig_i++;
548 }
549
550 //if (zinit_mode)
551 //{
552 // for (auto it : ff_map) {
553 // if (init_map.count(it.first))
554 // continue;
555 // aig_m++, aig_i++;
556 // init_inputs[it.first] = 2*aig_m;
557 // }
558 //}
559
560 for (auto it : ff_map) {
561 aig_m++, aig_l++;
562 aig_map[it.first] = 2*aig_m;
563 ordered_latches[it.first] = aig_l-1;
564 if (init_map.count(it.first) == 0)
565 aig_latchinit.push_back(2);
566 else
567 aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
568 }
569
570 //if (!initstate_bits.empty() || !init_inputs.empty()) {
571 // aig_m++, aig_l++;
572 // initstate_ff = 2*aig_m+1;
573 // aig_latchinit.push_back(0);
574 //}
575
576 //if (zinit_mode)
577 //{
578 // for (auto it : ff_map)
579 // {
580 // int l = ordered_latches[it.first];
581
582 // if (aig_latchinit.at(l) == 1)
583 // aig_map[it.first] ^= 1;
584
585 // if (aig_latchinit.at(l) == 2)
586 // {
587 // int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
588 // int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
589 // aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
590 // }
591 // }
592 //}
593
594 for (auto it : ff_map) {
595 int a = bit2aig(it.second);
596 int l = ordered_latches[it.first];
597 if (zinit_mode && aig_latchinit.at(l) == 1)
598 aig_latchin.push_back(a ^ 1);
599 else
600 aig_latchin.push_back(a);
601 }
602
603 //if (!initstate_bits.empty() || !init_inputs.empty())
604 // aig_latchin.push_back(1);
605
606 for (auto &c : co_bits) {
607 RTLIL::SigBit bit = std::get<0>(c);
608 std::get<4>(c) = ordered_outputs[bit] = aig_o++;
609 aig_outputs.push_back(bit2aig(bit));
610 }
611
612 for (auto bit : output_bits) {
613 ordered_outputs[bit] = aig_o++;
614 aig_outputs.push_back(bit2aig(bit));
615 }
616
617 for (auto &f : ff_bits) {
618 aig_o++;
619 RTLIL::SigBit bit = f.second;
620 aig_outputs.push_back(ff_aig_map.at(bit));
621 }
622
623 if (omode && output_bits.empty()) {
624 aig_o++;
625 aig_outputs.push_back(0);
626 }
627
628 if (bmode) {
629 //aig_b++;
630 aig_outputs.push_back(0);
631 }
632 }
633
634 void write_aiger(std::ostream &f, bool ascii_mode, bool miter_mode, bool symbols_mode, bool omode)
635 {
636 int aig_obc = aig_o;
637 int aig_obcj = aig_obc;
638 int aig_obcjf = aig_obcj;
639
640 log_assert(aig_m == aig_i + aig_l + aig_a);
641 log_assert(aig_l == GetSize(aig_latchin));
642 log_assert(aig_l == GetSize(aig_latchinit));
643 log_assert(aig_obcjf == GetSize(aig_outputs));
644
645 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
646 f << stringf("\n");
647
648 if (ascii_mode)
649 {
650 for (int i = 0; i < aig_i; i++)
651 f << stringf("%d\n", 2*i+2);
652
653 for (int i = 0; i < aig_l; i++) {
654 if (zinit_mode || aig_latchinit.at(i) == 0)
655 f << stringf("%d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i));
656 else if (aig_latchinit.at(i) == 1)
657 f << stringf("%d %d 1\n", 2*(aig_i+i)+2, aig_latchin.at(i));
658 else if (aig_latchinit.at(i) == 2)
659 f << stringf("%d %d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i), 2*(aig_i+i)+2);
660 }
661
662 for (int i = 0; i < aig_obc; i++)
663 f << stringf("%d\n", aig_outputs.at(i));
664
665 for (int i = aig_obc; i < aig_obcj; i++)
666 f << stringf("1\n");
667
668 for (int i = aig_obc; i < aig_obcj; i++)
669 f << stringf("%d\n", aig_outputs.at(i));
670
671 for (int i = aig_obcj; i < aig_obcjf; i++)
672 f << stringf("%d\n", aig_outputs.at(i));
673
674 for (int i = 0; i < aig_a; i++)
675 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
676 }
677 else
678 {
679 for (int i = 0; i < aig_l; i++) {
680 if (zinit_mode || aig_latchinit.at(i) == 0)
681 f << stringf("%d\n", aig_latchin.at(i));
682 else if (aig_latchinit.at(i) == 1)
683 f << stringf("%d 1\n", aig_latchin.at(i));
684 else if (aig_latchinit.at(i) == 2)
685 f << stringf("%d %d\n", aig_latchin.at(i), 2*(aig_i+i)+2);
686 }
687
688 for (int i = 0; i < aig_obc; i++)
689 f << stringf("%d\n", aig_outputs.at(i));
690
691 for (int i = aig_obc; i < aig_obcj; i++)
692 f << stringf("1\n");
693
694 for (int i = aig_obc; i < aig_obcj; i++)
695 f << stringf("%d\n", aig_outputs.at(i));
696
697 for (int i = aig_obcj; i < aig_obcjf; i++)
698 f << stringf("%d\n", aig_outputs.at(i));
699
700 for (int i = 0; i < aig_a; i++) {
701 int lhs = 2*(aig_i+aig_l+i)+2;
702 int rhs0 = aig_gates.at(i).first;
703 int rhs1 = aig_gates.at(i).second;
704 int delta0 = lhs - rhs0;
705 int delta1 = rhs0 - rhs1;
706 aiger_encode(f, delta0);
707 aiger_encode(f, delta1);
708 }
709 }
710
711 if (symbols_mode)
712 {
713 dict<string, vector<string>> symbols;
714
715 bool output_seen = false;
716 for (auto wire : module->wires())
717 {
718 //if (wire->name[0] == '$')
719 // continue;
720
721 SigSpec sig = sigmap(wire);
722
723 for (int i = 0; i < GetSize(wire); i++)
724 {
725 RTLIL::SigBit b(wire, i);
726 if (input_bits.count(b)) {
727 int a = aig_map.at(sig[i]);
728 log_assert((a & 1) == 0);
729 if (GetSize(wire) != 1)
730 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s[%d]", log_id(wire), i));
731 else
732 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
733 }
734
735 if (output_bits.count(b)) {
736 int o = ordered_outputs.at(b);
737 output_seen = !miter_mode;
738 if (GetSize(wire) != 1)
739 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s[%d]", log_id(wire), i));
740 else
741 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
742 }
743
744 //if (init_inputs.count(sig[i])) {
745 // int a = init_inputs.at(sig[i]);
746 // log_assert((a & 1) == 0);
747 // if (GetSize(wire) != 1)
748 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
749 // else
750 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
751 //}
752
753 if (ordered_latches.count(sig[i])) {
754 int l = ordered_latches.at(sig[i]);
755 const char *p = (zinit_mode && (aig_latchinit.at(l) == 1)) ? "!" : "";
756 if (GetSize(wire) != 1)
757 symbols[stringf("l%d", l)].push_back(stringf("%s%s[%d]", p, log_id(wire), i));
758 else
759 symbols[stringf("l%d", l)].push_back(stringf("%s%s", p, log_id(wire)));
760 }
761 }
762 }
763
764 if (omode && !output_seen)
765 symbols["o0"].push_back("__dummy_o__");
766
767 symbols.sort();
768
769 for (auto &sym : symbols) {
770 f << sym.first;
771 std::sort(sym.second.begin(), sym.second.end());
772 for (auto &s : sym.second)
773 f << " " << s;
774 f << std::endl;
775 }
776 }
777
778 f << "c";
779
780 if (!box_list.empty() || !ff_bits.empty()) {
781 std::stringstream h_buffer;
782 auto write_h_buffer = [&h_buffer](int i32) {
783 // TODO: Don't assume we're on little endian
784 #ifdef _WIN32
785 int i32_be = _byteswap_ulong(i32);
786 #else
787 int i32_be = __builtin_bswap32(i32);
788 #endif
789 h_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
790 };
791 int num_outputs = output_bits.size();
792 if (omode && num_outputs == 0)
793 num_outputs = 1;
794 write_h_buffer(1);
795 log_debug("ciNum = %zu\n", input_bits.size() + ff_bits.size() + ci_bits.size());
796 write_h_buffer(input_bits.size() + ff_bits.size() + ci_bits.size());
797 log_debug("coNum = %zu\n", num_outputs + ff_bits.size() + co_bits.size());
798 write_h_buffer(num_outputs + ff_bits.size()+ co_bits.size());
799 log_debug("piNum = %zu\n", input_bits.size() + ff_bits.size());
800 write_h_buffer(input_bits.size()+ ff_bits.size());
801 log_debug("poNum = %zu\n", num_outputs + ff_bits.size());
802 write_h_buffer(num_outputs + ff_bits.size());
803 log_debug("boxNum = %zu\n", box_list.size());
804 write_h_buffer(box_list.size());
805
806 RTLIL::Module *holes_module = nullptr;
807 holes_module = module->design->addModule("\\__holes__");
808 log_assert(holes_module);
809
810 int port_id = 1;
811 int box_count = 0;
812 for (auto cell : box_list) {
813 RTLIL::Module* box_module = module->design->module(cell->type);
814 int box_inputs = 0, box_outputs = 0;
815 Cell *holes_cell = nullptr;
816 if (box_module->get_bool_attribute("\\whitebox")) {
817 holes_cell = holes_module->addCell(cell->name, cell->type);
818 holes_cell->parameters = cell->parameters;
819 }
820
821 // NB: Assume box_module->ports are sorted alphabetically
822 // (as RTLIL::Module::fixup_ports() would do)
823 for (const auto &port_name : box_module->ports) {
824 RTLIL::Wire *w = box_module->wire(port_name);
825 log_assert(w);
826 RTLIL::Wire *holes_wire;
827 RTLIL::SigSpec port_wire;
828 if (w->port_input) {
829 for (int i = 0; i < GetSize(w); i++) {
830 box_inputs++;
831 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
832 if (!holes_wire) {
833 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
834 holes_wire->port_input = true;
835 holes_wire->port_id = port_id++;
836 holes_module->ports.push_back(holes_wire->name);
837 }
838 if (holes_cell)
839 port_wire.append(holes_wire);
840 }
841 if (!port_wire.empty())
842 holes_cell->setPort(w->name, port_wire);
843 }
844 if (w->port_output) {
845 box_outputs += GetSize(w);
846 for (int i = 0; i < GetSize(w); i++) {
847 if (GetSize(w) == 1)
848 holes_wire = holes_module->addWire(stringf("%s.%s", cell->name.c_str(), w->name.c_str()));
849 else
850 holes_wire = holes_module->addWire(stringf("%s.%s[%d]", cell->name.c_str(), w->name.c_str(), i));
851 holes_wire->port_output = true;
852 holes_wire->port_id = port_id++;
853 holes_module->ports.push_back(holes_wire->name);
854 if (holes_cell)
855 port_wire.append(holes_wire);
856 else
857 holes_module->connect(holes_wire, RTLIL::S0);
858 }
859 if (!port_wire.empty())
860 holes_cell->setPort(w->name, port_wire);
861 }
862 }
863
864 write_h_buffer(box_inputs);
865 write_h_buffer(box_outputs);
866 write_h_buffer(box_module->attributes.at("\\abc_box_id").as_int());
867 write_h_buffer(box_count++);
868 }
869
870 f << "h";
871 std::string buffer_str = h_buffer.str();
872 // TODO: Don't assume we're on little endian
873 #ifdef _WIN32
874 int buffer_size_be = _byteswap_ulong(buffer_str.size());
875 #else
876 int buffer_size_be = __builtin_bswap32(buffer_str.size());
877 #endif
878 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
879 f.write(buffer_str.data(), buffer_str.size());
880
881 /*if (!ff_bits.empty())*/ {
882 std::stringstream r_buffer;
883 auto write_r_buffer = [&r_buffer](int i32) {
884 // TODO: Don't assume we're on little endian
885 #ifdef _WIN32
886 int i32_be = _byteswap_ulong(i32);
887 #else
888 int i32_be = __builtin_bswap32(i32);
889 #endif
890 r_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
891 };
892 log_debug("flopNum = %zu\n", ff_bits.size());
893 write_r_buffer(ff_bits.size());
894 int mergeability_class = 1;
895 for (auto cell : ff_bits)
896 write_r_buffer(mergeability_class++);
897
898 f << "r";
899 std::string buffer_str = r_buffer.str();
900 // TODO: Don't assume we're on little endian
901 #ifdef _WIN32
902 int buffer_size_be = _byteswap_ulong(buffer_str.size());
903 #else
904 int buffer_size_be = __builtin_bswap32(buffer_str.size());
905 #endif
906 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
907 f.write(buffer_str.data(), buffer_str.size());
908 }
909
910 if (holes_module) {
911 // NB: fixup_ports() will sort ports by name
912 //holes_module->fixup_ports();
913 holes_module->check();
914
915 holes_module->design->selection_stack.emplace_back(false);
916 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
917 sel.select(holes_module);
918
919 // TODO: Should not need to opt_merge if we only instantiate
920 // each box type once...
921 Pass::call(holes_module->design, "opt_merge -share_all");
922
923 Pass::call(holes_module->design, "flatten -wb");
924
925 // TODO: Should techmap all lib_whitebox-es once
926 //Pass::call(holes_module->design, "techmap");
927
928 Pass::call(holes_module->design, "aigmap");
929 Pass::call(holes_module->design, "clean -purge");
930
931 holes_module->design->selection_stack.pop_back();
932
933 std::stringstream a_buffer;
934 XAigerWriter writer(holes_module, false /*zinit_mode*/, false /*imode*/, false /*omode*/, false /*bmode*/, true /* holes_mode */);
935 writer.write_aiger(a_buffer, false /*ascii_mode*/, false /*miter_mode*/, false /*symbols_mode*/, false /*omode*/);
936
937 f << "a";
938 std::string buffer_str = a_buffer.str();
939 // TODO: Don't assume we're on little endian
940 #ifdef _WIN32
941 int buffer_size_be = _byteswap_ulong(buffer_str.size());
942 #else
943 int buffer_size_be = __builtin_bswap32(buffer_str.size());
944 #endif
945 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
946 f.write(buffer_str.data(), buffer_str.size());
947 holes_module->design->remove(holes_module);
948 }
949 }
950
951 f << stringf("Generated by %s\n", yosys_version_str);
952 }
953
954 void write_map(std::ostream &f, bool verbose_map, bool omode)
955 {
956 dict<int, string> input_lines;
957 dict<int, string> init_lines;
958 dict<int, string> output_lines;
959 dict<int, string> latch_lines;
960 dict<int, string> wire_lines;
961
962 for (auto wire : module->wires())
963 {
964 //if (!verbose_map && wire->name[0] == '$')
965 // continue;
966
967 SigSpec sig = sigmap(wire);
968
969 for (int i = 0; i < GetSize(wire); i++)
970 {
971 RTLIL::SigBit b(wire, i);
972 if (input_bits.count(b)) {
973 int a = aig_map.at(b);
974 log_assert((a & 1) == 0);
975 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
976 }
977
978 if (output_bits.count(b)) {
979 int o = ordered_outputs.at(b);
980 output_lines[o] += stringf("output %lu %d %s\n", o - co_bits.size(), i, log_id(wire));
981 continue;
982 }
983
984 //if (init_inputs.count(sig[i])) {
985 // int a = init_inputs.at(sig[i]);
986 // log_assert((a & 1) == 0);
987 // init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
988 // continue;
989 //}
990
991 if (ordered_latches.count(sig[i])) {
992 int l = ordered_latches.at(sig[i]);
993 if (zinit_mode && (aig_latchinit.at(l) == 1))
994 latch_lines[l] += stringf("invlatch %d %d %s\n", l, i, log_id(wire));
995 else
996 latch_lines[l] += stringf("latch %d %d %s\n", l, i, log_id(wire));
997 continue;
998 }
999
1000 if (verbose_map) {
1001 if (aig_map.count(sig[i]) == 0)
1002 continue;
1003
1004 int a = aig_map.at(sig[i]);
1005 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
1006 }
1007 }
1008 }
1009
1010 input_lines.sort();
1011 for (auto &it : input_lines)
1012 f << it.second;
1013 log_assert(input_lines.size() == input_bits.size());
1014
1015 init_lines.sort();
1016 for (auto &it : init_lines)
1017 f << it.second;
1018
1019 int box_count = 0;
1020 for (auto cell : box_list)
1021 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
1022
1023 output_lines.sort();
1024 for (auto &it : output_lines)
1025 f << it.second;
1026 log_assert(output_lines.size() == output_bits.size());
1027 if (omode && output_bits.empty())
1028 f << "output " << output_lines.size() << " 0 __dummy_o__\n";
1029
1030 latch_lines.sort();
1031 for (auto &it : latch_lines)
1032 f << it.second;
1033
1034 wire_lines.sort();
1035 for (auto &it : wire_lines)
1036 f << it.second;
1037 }
1038 };
1039
1040 struct XAigerBackend : public Backend {
1041 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
1042 void help() YS_OVERRIDE
1043 {
1044 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1045 log("\n");
1046 log(" write_xaiger [options] [filename]\n");
1047 log("\n");
1048 log("Write the current design to an XAIGER file. The design must be flattened and\n");
1049 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
1050 log("\n");
1051 log(" -ascii\n");
1052 log(" write ASCII version of AIGER format\n");
1053 log("\n");
1054 log(" -zinit\n");
1055 log(" convert FFs to zero-initialized FFs, adding additional inputs for\n");
1056 log(" uninitialized FFs.\n");
1057 log("\n");
1058 log(" -symbols\n");
1059 log(" include a symbol table in the generated AIGER file\n");
1060 log("\n");
1061 log(" -map <filename>\n");
1062 log(" write an extra file with port and latch symbols\n");
1063 log("\n");
1064 log(" -vmap <filename>\n");
1065 log(" like -map, but more verbose\n");
1066 log("\n");
1067 log(" -I, -O, -B\n");
1068 log(" If the design contains no input/output/assert then create one\n");
1069 log(" dummy input/output/bad_state pin to make the tools reading the\n");
1070 log(" AIGER file happy.\n");
1071 log("\n");
1072 }
1073 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
1074 {
1075 bool ascii_mode = false;
1076 bool zinit_mode = false;
1077 bool miter_mode = false;
1078 bool symbols_mode = false;
1079 bool verbose_map = false;
1080 bool imode = false;
1081 bool omode = false;
1082 bool bmode = false;
1083 std::string map_filename;
1084
1085 log_header(design, "Executing XAIGER backend.\n");
1086
1087 size_t argidx;
1088 for (argidx = 1; argidx < args.size(); argidx++)
1089 {
1090 if (args[argidx] == "-ascii") {
1091 ascii_mode = true;
1092 continue;
1093 }
1094 if (args[argidx] == "-zinit") {
1095 zinit_mode = true;
1096 continue;
1097 }
1098 if (args[argidx] == "-symbols") {
1099 symbols_mode = true;
1100 continue;
1101 }
1102 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
1103 map_filename = args[++argidx];
1104 continue;
1105 }
1106 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
1107 map_filename = args[++argidx];
1108 verbose_map = true;
1109 continue;
1110 }
1111 if (args[argidx] == "-I") {
1112 imode = true;
1113 continue;
1114 }
1115 if (args[argidx] == "-O") {
1116 omode = true;
1117 continue;
1118 }
1119 if (args[argidx] == "-B") {
1120 bmode = true;
1121 continue;
1122 }
1123 break;
1124 }
1125 extra_args(f, filename, args, argidx);
1126
1127 Module *top_module = design->top_module();
1128
1129 if (top_module == nullptr)
1130 log_error("Can't find top module in current design!\n");
1131
1132 XAigerWriter writer(top_module, zinit_mode, imode, omode, bmode);
1133 writer.write_aiger(*f, ascii_mode, miter_mode, symbols_mode, omode);
1134
1135 if (!map_filename.empty()) {
1136 std::ofstream mapf;
1137 mapf.open(map_filename.c_str(), std::ofstream::trunc);
1138 if (mapf.fail())
1139 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
1140 writer.write_map(mapf, verbose_map, omode);
1141 }
1142 }
1143 } XAigerBackend;
1144
1145 PRIVATE_NAMESPACE_END