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