Add ConstEvalAig specialised for AIGs
[yosys.git] / frontends / aiger / aigerparse.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 // [[CITE]] The AIGER And-Inverter Graph (AIG) Format Version 20071012
22 // Armin Biere. The AIGER And-Inverter Graph (AIG) Format Version 20071012. Technical Report 07/1, October 2011, FMV Reports Series, Institute for Formal Models and Verification, Johannes Kepler University, Altenbergerstr. 69, 4040 Linz, Austria.
23 // http://fmv.jku.at/papers/Biere-FMV-TR-07-1.pdf
24
25 #ifdef _WIN32
26 #include <libgen.h>
27 #include <stdlib.h>
28 #endif
29 #include <array>
30
31 #include "kernel/yosys.h"
32 #include "kernel/sigtools.h"
33 #include "kernel/consteval.h"
34 #include "aigerparse.h"
35
36 YOSYS_NAMESPACE_BEGIN
37
38 AigerReader::AigerReader(RTLIL::Design *design, std::istream &f, RTLIL::IdString module_name, RTLIL::IdString clk_name, std::string map_filename, bool wideports)
39 : design(design), f(f), clk_name(clk_name), map_filename(map_filename), wideports(wideports)
40 {
41 module = new RTLIL::Module;
42 module->name = module_name;
43 if (design->module(module->name))
44 log_error("Duplicate definition of module %s!\n", log_id(module->name));
45 }
46
47 void AigerReader::parse_aiger()
48 {
49 std::string header;
50 f >> header;
51 if (header != "aag" && header != "aig")
52 log_error("Unsupported AIGER file!\n");
53
54 // Parse rest of header
55 if (!(f >> M >> I >> L >> O >> A))
56 log_error("Invalid AIGER header\n");
57
58 // Optional values
59 B = C = J = F = 0;
60 if (f.peek() != ' ') goto end_of_header;
61 if (!(f >> B)) log_error("Invalid AIGER header\n");
62 if (f.peek() != ' ') goto end_of_header;
63 if (!(f >> C)) log_error("Invalid AIGER header\n");
64 if (f.peek() != ' ') goto end_of_header;
65 if (!(f >> J)) log_error("Invalid AIGER header\n");
66 if (f.peek() != ' ') goto end_of_header;
67 if (!(f >> F)) log_error("Invalid AIGER header\n");
68 end_of_header:
69
70 std::string line;
71 std::getline(f, line); // Ignore up to start of next line, as standard
72 // says anything that follows could be used for
73 // optional sections
74
75 log_debug("M=%u I=%u L=%u O=%u A=%u B=%u C=%u J=%u F=%u\n", M, I, L, O, A, B, C, J, F);
76
77 line_count = 1;
78 piNum = 0;
79 flopNum = 0;
80
81 if (header == "aag")
82 parse_aiger_ascii();
83 else if (header == "aig")
84 parse_aiger_binary();
85 else
86 log_abort();
87
88 RTLIL::Wire* n0 = module->wire("\\__0__");
89 if (n0)
90 module->connect(n0, RTLIL::S0);
91
92 // Parse footer (symbol table, comments, etc.)
93 unsigned l1;
94 std::string s;
95 for (int c = f.peek(); c != EOF; c = f.peek(), ++line_count) {
96 if (c == 'i' || c == 'l' || c == 'o' || c == 'b') {
97 f.ignore(1);
98 if (!(f >> l1 >> s))
99 log_error("Line %u cannot be interpreted as a symbol entry!\n", line_count);
100
101 if ((c == 'i' && l1 > inputs.size()) || (c == 'l' && l1 > latches.size()) || (c == 'o' && l1 > outputs.size()))
102 log_error("Line %u has invalid symbol position!\n", line_count);
103
104 RTLIL::Wire* wire;
105 if (c == 'i') wire = inputs[l1];
106 else if (c == 'l') wire = latches[l1];
107 else if (c == 'o') wire = outputs[l1];
108 else if (c == 'b') wire = bad_properties[l1];
109 else log_abort();
110
111 module->rename(wire, stringf("\\%s", s.c_str()));
112 }
113 else if (c == 'j' || c == 'f') {
114 // TODO
115 }
116 else if (c == 'c') {
117 f.ignore(1);
118 if (f.peek() == '\n')
119 break;
120 // Else constraint (TODO)
121 }
122 else
123 log_error("Line %u: cannot interpret first character '%c'!\n", line_count, c);
124 std::getline(f, line); // Ignore up to start of next line
125 }
126
127 post_process();
128 }
129
130 static uint32_t parse_xaiger_literal(std::istream &f)
131 {
132 uint32_t l;
133 f.read(reinterpret_cast<char*>(&l), sizeof(l));
134 if (f.gcount() != sizeof(l))
135 log_error("Offset %ld: unable to read literal!\n", static_cast<int64_t>(f.tellg()));
136 // TODO: Don't assume we're on little endian
137 #ifdef _WIN32
138 return _byteswap_ulong(l);
139 #else
140 return __builtin_bswap32(l);
141 #endif
142 }
143
144 static RTLIL::Wire* createWireIfNotExists(RTLIL::Module *module, unsigned literal)
145 {
146 const unsigned variable = literal >> 1;
147 const bool invert = literal & 1;
148 RTLIL::IdString wire_name(stringf("\\__%d%s__", variable, invert ? "b" : "")); // FIXME: is "b" the right suffix?
149 RTLIL::Wire *wire = module->wire(wire_name);
150 if (wire) return wire;
151 log_debug("Creating %s\n", wire_name.c_str());
152 wire = module->addWire(wire_name);
153 wire->port_input = wire->port_output = false;
154 if (!invert) return wire;
155 RTLIL::IdString wire_inv_name(stringf("\\__%d__", variable));
156 RTLIL::Wire *wire_inv = module->wire(wire_inv_name);
157 if (wire_inv) {
158 if (module->cell(wire_inv_name)) return wire;
159 }
160 else {
161 log_debug("Creating %s\n", wire_inv_name.c_str());
162 wire_inv = module->addWire(wire_inv_name);
163 wire_inv->port_input = wire_inv->port_output = false;
164 }
165
166 log_debug("Creating %s = ~%s\n", wire_name.c_str(), wire_inv_name.c_str());
167 module->addNotGate(stringf("\\__%d__$not", variable), wire_inv, wire); // FIXME: is "$not" the right suffix?
168
169 return wire;
170 }
171
172 void AigerReader::parse_xaiger()
173 {
174 std::string header;
175 f >> header;
176 if (header != "aag" && header != "aig")
177 log_error("Unsupported AIGER file!\n");
178
179 // Parse rest of header
180 if (!(f >> M >> I >> L >> O >> A))
181 log_error("Invalid AIGER header\n");
182
183 // Optional values
184 B = C = J = F = 0;
185
186 std::string line;
187 std::getline(f, line); // Ignore up to start of next line, as standard
188 // says anything that follows could be used for
189 // optional sections
190
191 log_debug("M=%u I=%u L=%u O=%u A=%u\n", M, I, L, O, A);
192
193 line_count = 1;
194 piNum = 0;
195 flopNum = 0;
196
197 if (header == "aag")
198 parse_aiger_ascii();
199 else if (header == "aig")
200 parse_aiger_binary();
201 else
202 log_abort();
203
204 RTLIL::Wire* n0 = module->wire("\\__0__");
205 if (n0)
206 module->connect(n0, RTLIL::S0);
207
208 dict<int,IdString> box_lookup;
209 for (auto m : design->modules()) {
210 auto it = m->attributes.find("\\abc_box_id");
211 if (it == m->attributes.end())
212 continue;
213 if (m->name[0] == '$') continue;
214 auto r = box_lookup.insert(std::make_pair(it->second.as_int(), m->name));
215 log_assert(r.second);
216 }
217
218 // Parse footer (symbol table, comments, etc.)
219 std::string s;
220 bool comment_seen = false;
221 for (int c = f.peek(); c != EOF; c = f.peek()) {
222 if (comment_seen || c == 'c') {
223 if (!comment_seen) {
224 f.ignore(1);
225 c = f.peek();
226 comment_seen = true;
227 }
228 if (c == '\n')
229 break;
230 f.ignore(1);
231 // XAIGER extensions
232 if (c == 'm') {
233 uint32_t dataSize = parse_xaiger_literal(f);
234 uint32_t lutNum = parse_xaiger_literal(f);
235 uint32_t lutSize = parse_xaiger_literal(f);
236 log_debug("m: dataSize=%u lutNum=%u lutSize=%u\n", dataSize, lutNum, lutSize);
237 ConstEvalAig ce(module);
238 for (unsigned i = 0; i < lutNum; ++i) {
239 uint32_t rootNodeID = parse_xaiger_literal(f);
240 uint32_t cutLeavesM = parse_xaiger_literal(f);
241 log_debug("rootNodeID=%d cutLeavesM=%d\n", rootNodeID, cutLeavesM);
242 RTLIL::Wire *output_sig = module->wire(stringf("\\__%d__", rootNodeID));
243 uint32_t nodeID;
244 RTLIL::SigSpec input_sig;
245 for (unsigned j = 0; j < cutLeavesM; ++j) {
246 nodeID = parse_xaiger_literal(f);
247 log_debug("\t%u\n", nodeID);
248 RTLIL::Wire *wire = module->wire(stringf("\\__%d__", nodeID));
249 log_assert(wire);
250 input_sig.append(wire);
251 }
252 RTLIL::Const lut_mask(RTLIL::State::Sx, 1 << input_sig.size());
253 for (int j = 0; j < (1 << cutLeavesM); ++j) {
254 ce.clear();
255 ce.set(input_sig, RTLIL::Const{j, static_cast<int>(cutLeavesM)});
256 RTLIL::SigSpec o(output_sig);
257 ce.eval(o);
258 lut_mask[j] = o.as_const()[0];
259 }
260 RTLIL::Cell *output_cell = module->cell(stringf("\\__%d__$and", rootNodeID));
261 log_assert(output_cell);
262 module->remove(output_cell);
263 module->addLut(stringf("\\__%d__$lut", rootNodeID), input_sig, output_sig, std::move(lut_mask));
264 }
265 }
266 else if (c == 'r') {
267 uint32_t dataSize = parse_xaiger_literal(f);
268 flopNum = parse_xaiger_literal(f);
269 log_assert(dataSize == (flopNum+1) * sizeof(uint32_t));
270 f.ignore(flopNum * sizeof(uint32_t));
271 }
272 else if (c == 'n') {
273 parse_xaiger_literal(f);
274 f >> s;
275 log_debug("n: '%s'\n", s.c_str());
276 }
277 else if (c == 'h') {
278 f.ignore(sizeof(uint32_t));
279 uint32_t version = parse_xaiger_literal(f);
280 log_assert(version == 1);
281 uint32_t ciNum = parse_xaiger_literal(f);
282 log_debug("ciNum = %u\n", ciNum);
283 uint32_t coNum = parse_xaiger_literal(f);
284 log_debug("coNum = %u\n", coNum);
285 piNum = parse_xaiger_literal(f);
286 log_debug("piNum = %u\n", piNum);
287 uint32_t poNum = parse_xaiger_literal(f);
288 log_debug("poNum = %u\n", poNum);
289 uint32_t boxNum = parse_xaiger_literal(f);
290 log_debug("boxNum = %u\n", poNum);
291 for (unsigned i = 0; i < boxNum; i++) {
292 f.ignore(2*sizeof(uint32_t));
293 uint32_t boxUniqueId = parse_xaiger_literal(f);
294 log_assert(boxUniqueId > 0);
295 uint32_t oldBoxNum = parse_xaiger_literal(f);
296 RTLIL::Cell* cell = module->addCell(stringf("$__box%u__", oldBoxNum), box_lookup.at(boxUniqueId));
297 boxes.emplace_back(cell);
298 }
299 }
300 else if (c == 'a' || c == 'i' || c == 'o') {
301 uint32_t dataSize = parse_xaiger_literal(f);
302 f.ignore(dataSize);
303 }
304 else {
305 break;
306 }
307 }
308 else
309 log_error("Line %u: cannot interpret first character '%c'!\n", line_count, c);
310 }
311
312 post_process();
313 }
314
315 void AigerReader::parse_aiger_ascii()
316 {
317 std::string line;
318 std::stringstream ss;
319
320 unsigned l1, l2, l3;
321
322 // Parse inputs
323 for (unsigned i = 1; i <= I; ++i, ++line_count) {
324 if (!(f >> l1))
325 log_error("Line %u cannot be interpreted as an input!\n", line_count);
326 log_debug("%d is an input\n", l1);
327 log_assert(!(l1 & 1)); // Inputs can't be inverted
328 RTLIL::Wire *wire = createWireIfNotExists(module, l1);
329 wire->port_input = true;
330 inputs.push_back(wire);
331 }
332
333 // Parse latches
334 RTLIL::Wire *clk_wire = nullptr;
335 if (L > 0) {
336 log_assert(clk_name != "");
337 clk_wire = module->wire(clk_name);
338 log_assert(!clk_wire);
339 log_debug("Creating %s\n", clk_name.c_str());
340 clk_wire = module->addWire(clk_name);
341 clk_wire->port_input = true;
342 clk_wire->port_output = false;
343 }
344 for (unsigned i = 0; i < L; ++i, ++line_count) {
345 if (!(f >> l1 >> l2))
346 log_error("Line %u cannot be interpreted as a latch!\n", line_count);
347 log_debug("%d %d is a latch\n", l1, l2);
348 log_assert(!(l1 & 1)); // TODO: Latch outputs can't be inverted?
349 RTLIL::Wire *q_wire = createWireIfNotExists(module, l1);
350 RTLIL::Wire *d_wire = createWireIfNotExists(module, l2);
351
352 module->addDffGate(NEW_ID, clk_wire, d_wire, q_wire);
353
354 // Reset logic is optional in AIGER 1.9
355 if (f.peek() == ' ') {
356 if (!(f >> l3))
357 log_error("Line %u cannot be interpreted as a latch!\n", line_count);
358
359 if (l3 == 0)
360 q_wire->attributes["\\init"] = RTLIL::S0;
361 else if (l3 == 1)
362 q_wire->attributes["\\init"] = RTLIL::S1;
363 else if (l3 == l1) {
364 //q_wire->attributes["\\init"] = RTLIL::Sx;
365 }
366 else
367 log_error("Line %u has invalid reset literal for latch!\n", line_count);
368 }
369 else {
370 // AIGER latches are assumed to be initialized to zero
371 q_wire->attributes["\\init"] = RTLIL::S0;
372 }
373 latches.push_back(q_wire);
374 }
375
376 // Parse outputs
377 for (unsigned i = 0; i < O; ++i, ++line_count) {
378 if (!(f >> l1))
379 log_error("Line %u cannot be interpreted as an output!\n", line_count);
380
381 log_debug("%d is an output\n", l1);
382 const unsigned variable = l1 >> 1;
383 const bool invert = l1 & 1;
384 RTLIL::IdString wire_name(stringf("\\__%d%s__", variable, invert ? "b" : "")); // FIXME: is "b" the right suffix?
385 RTLIL::Wire *wire = module->wire(wire_name);
386 if (!wire)
387 wire = createWireIfNotExists(module, l1);
388 else if (wire->port_input || wire->port_output) {
389 RTLIL::Wire *new_wire = module->addWire(NEW_ID);
390 module->connect(new_wire, wire);
391 wire = new_wire;
392 }
393 wire->port_output = true;
394 outputs.push_back(wire);
395 }
396
397 // Parse bad properties
398 for (unsigned i = 0; i < B; ++i, ++line_count) {
399 if (!(f >> l1))
400 log_error("Line %u cannot be interpreted as a bad state property!\n", line_count);
401
402 log_debug("%d is a bad state property\n", l1);
403 RTLIL::Wire *wire = createWireIfNotExists(module, l1);
404 wire->port_output = true;
405 bad_properties.push_back(wire);
406 }
407
408 // TODO: Parse invariant constraints
409 for (unsigned i = 0; i < C; ++i, ++line_count)
410 std::getline(f, line); // Ignore up to start of next line
411
412 // TODO: Parse justice properties
413 for (unsigned i = 0; i < J; ++i, ++line_count)
414 std::getline(f, line); // Ignore up to start of next line
415
416 // TODO: Parse fairness constraints
417 for (unsigned i = 0; i < F; ++i, ++line_count)
418 std::getline(f, line); // Ignore up to start of next line
419
420 // Parse AND
421 for (unsigned i = 0; i < A; ++i) {
422 if (!(f >> l1 >> l2 >> l3))
423 log_error("Line %u cannot be interpreted as an AND!\n", line_count);
424
425 log_debug("%d %d %d is an AND\n", l1, l2, l3);
426 log_assert(!(l1 & 1));
427 RTLIL::Wire *o_wire = createWireIfNotExists(module, l1);
428 RTLIL::Wire *i1_wire = createWireIfNotExists(module, l2);
429 RTLIL::Wire *i2_wire = createWireIfNotExists(module, l3);
430 module->addAndGate(o_wire->name.str() + "$and", i1_wire, i2_wire, o_wire);
431 }
432 std::getline(f, line); // Ignore up to start of next line
433 }
434
435 static unsigned parse_next_delta_literal(std::istream &f, unsigned ref)
436 {
437 unsigned x = 0, i = 0;
438 unsigned char ch;
439 while ((ch = f.get()) & 0x80)
440 x |= (ch & 0x7f) << (7 * i++);
441 return ref - (x | (ch << (7 * i)));
442 }
443
444 void AigerReader::parse_aiger_binary()
445 {
446 unsigned l1, l2, l3;
447 std::string line;
448
449 // Parse inputs
450 for (unsigned i = 1; i <= I; ++i) {
451 log_debug("%d is an input\n", i);
452 RTLIL::Wire *wire = createWireIfNotExists(module, i << 1);
453 wire->port_input = true;
454 log_assert(!wire->port_output);
455 inputs.push_back(wire);
456 }
457
458 // Parse latches
459 RTLIL::Wire *clk_wire = nullptr;
460 if (L > 0) {
461 log_assert(clk_name != "");
462 clk_wire = module->wire(clk_name);
463 log_assert(!clk_wire);
464 log_debug("Creating %s\n", clk_name.c_str());
465 clk_wire = module->addWire(clk_name);
466 clk_wire->port_input = true;
467 clk_wire->port_output = false;
468 }
469 l1 = (I+1) * 2;
470 for (unsigned i = 0; i < L; ++i, ++line_count, l1 += 2) {
471 if (!(f >> l2))
472 log_error("Line %u cannot be interpreted as a latch!\n", line_count);
473 log_debug("%d %d is a latch\n", l1, l2);
474 RTLIL::Wire *q_wire = createWireIfNotExists(module, l1);
475 RTLIL::Wire *d_wire = createWireIfNotExists(module, l2);
476
477 module->addDff(NEW_ID, clk_wire, d_wire, q_wire);
478
479 // Reset logic is optional in AIGER 1.9
480 if (f.peek() == ' ') {
481 if (!(f >> l3))
482 log_error("Line %u cannot be interpreted as a latch!\n", line_count);
483
484 if (l3 == 0)
485 q_wire->attributes["\\init"] = RTLIL::S0;
486 else if (l3 == 1)
487 q_wire->attributes["\\init"] = RTLIL::S1;
488 else if (l3 == l1) {
489 //q_wire->attributes["\\init"] = RTLIL::Sx;
490 }
491 else
492 log_error("Line %u has invalid reset literal for latch!\n", line_count);
493 }
494 else {
495 // AIGER latches are assumed to be initialized to zero
496 q_wire->attributes["\\init"] = RTLIL::S0;
497 }
498 latches.push_back(q_wire);
499 }
500
501 // Parse outputs
502 for (unsigned i = 0; i < O; ++i, ++line_count) {
503 if (!(f >> l1))
504 log_error("Line %u cannot be interpreted as an output!\n", line_count);
505
506 log_debug("%d is an output\n", l1);
507 const unsigned variable = l1 >> 1;
508 const bool invert = l1 & 1;
509 RTLIL::IdString wire_name(stringf("\\__%d%s__", variable, invert ? "b" : "")); // FIXME: is "_b" the right suffix?
510 RTLIL::Wire *wire = module->wire(wire_name);
511 if (!wire)
512 wire = createWireIfNotExists(module, l1);
513 else if (wire->port_input || wire->port_output) {
514 RTLIL::Wire *new_wire = module->addWire(NEW_ID);
515 module->connect(new_wire, wire);
516 wire = new_wire;
517 }
518 wire->port_output = true;
519 outputs.push_back(wire);
520 }
521 std::getline(f, line); // Ignore up to start of next line
522
523 // Parse bad properties
524 for (unsigned i = 0; i < B; ++i, ++line_count) {
525 if (!(f >> l1))
526 log_error("Line %u cannot be interpreted as a bad state property!\n", line_count);
527
528 log_debug("%d is a bad state property\n", l1);
529 RTLIL::Wire *wire = createWireIfNotExists(module, l1);
530 wire->port_output = true;
531 bad_properties.push_back(wire);
532 }
533 if (B > 0)
534 std::getline(f, line); // Ignore up to start of next line
535
536 // TODO: Parse invariant constraints
537 for (unsigned i = 0; i < C; ++i, ++line_count)
538 std::getline(f, line); // Ignore up to start of next line
539
540 // TODO: Parse justice properties
541 for (unsigned i = 0; i < J; ++i, ++line_count)
542 std::getline(f, line); // Ignore up to start of next line
543
544 // TODO: Parse fairness constraints
545 for (unsigned i = 0; i < F; ++i, ++line_count)
546 std::getline(f, line); // Ignore up to start of next line
547
548 // Parse AND
549 l1 = (I+L+1) << 1;
550 for (unsigned i = 0; i < A; ++i, ++line_count, l1 += 2) {
551 l2 = parse_next_delta_literal(f, l1);
552 l3 = parse_next_delta_literal(f, l2);
553
554 log_debug("%d %d %d is an AND\n", l1, l2, l3);
555 log_assert(!(l1 & 1));
556 RTLIL::Wire *o_wire = createWireIfNotExists(module, l1);
557 RTLIL::Wire *i1_wire = createWireIfNotExists(module, l2);
558 RTLIL::Wire *i2_wire = createWireIfNotExists(module, l3);
559 module->addAndGate(o_wire->name.str() + "$and", i1_wire, i2_wire, o_wire);
560 }
561 }
562
563 void AigerReader::post_process()
564 {
565 pool<RTLIL::Module*> abc_carry_modules;
566 unsigned ci_count = 0, co_count = 0, flop_count = 0;
567 for (auto cell : boxes) {
568 RTLIL::Module* box_module = design->module(cell->type);
569 log_assert(box_module);
570
571 if (box_module->attributes.count("\\abc_carry") && !abc_carry_modules.count(box_module)) {
572 RTLIL::Wire* carry_in = nullptr, *carry_out = nullptr;
573 RTLIL::Wire* last_in = nullptr, *last_out = nullptr;
574 for (const auto &port_name : box_module->ports) {
575 RTLIL::Wire* w = box_module->wire(port_name);
576 log_assert(w);
577 if (w->port_input) {
578 if (w->attributes.count("\\abc_carry_in")) {
579 log_assert(!carry_in);
580 carry_in = w;
581 }
582 log_assert(!last_in || last_in->port_id < w->port_id);
583 last_in = w;
584 }
585 if (w->port_output) {
586 if (w->attributes.count("\\abc_carry_out")) {
587 log_assert(!carry_out);
588 carry_out = w;
589 }
590 log_assert(!last_out || last_out->port_id < w->port_id);
591 last_out = w;
592 }
593 }
594
595 if (carry_in != last_in) {
596 std::swap(box_module->ports[carry_in->port_id], box_module->ports[last_in->port_id]);
597 std::swap(carry_in->port_id, last_in->port_id);
598 }
599 if (carry_out != last_out) {
600 log_assert(last_out);
601 std::swap(box_module->ports[carry_out->port_id], box_module->ports[last_out->port_id]);
602 std::swap(carry_out->port_id, last_out->port_id);
603 }
604 }
605
606 bool flop = box_module->attributes.count("\\abc_flop");
607 log_assert(!flop || flop_count < flopNum);
608
609 // NB: Assume box_module->ports are sorted alphabetically
610 // (as RTLIL::Module::fixup_ports() would do)
611 for (auto port_name : box_module->ports) {
612 RTLIL::Wire* w = box_module->wire(port_name);
613 log_assert(w);
614 RTLIL::SigSpec rhs;
615 RTLIL::Wire* wire = nullptr;
616 for (int i = 0; i < GetSize(w); i++) {
617 if (w->port_input) {
618 log_assert(co_count < outputs.size());
619 wire = outputs[co_count++];
620 log_assert(wire);
621 log_assert(wire->port_output);
622 wire->port_output = false;
623
624 if (flop && w->attributes.count("\\abc_flop_d")) {
625 RTLIL::Wire* d = outputs[outputs.size() - flopNum + flop_count];
626 log_assert(d);
627 log_assert(d->port_output);
628 d->port_output = false;
629 }
630 }
631 if (w->port_output) {
632 log_assert((piNum + ci_count) < inputs.size());
633 wire = inputs[piNum + ci_count++];
634 log_assert(wire);
635 log_assert(wire->port_input);
636 wire->port_input = false;
637
638 if (flop && w->attributes.count("\\abc_flop_q")) {
639 wire = inputs[piNum - flopNum + flop_count];
640 log_assert(wire);
641 log_assert(wire->port_input);
642 wire->port_input = false;
643 }
644 }
645 rhs.append(wire);
646 }
647 cell->setPort(port_name, rhs);
648 }
649
650 if (flop) flop_count++;
651 }
652
653 dict<RTLIL::IdString, int> wideports_cache;
654
655 if (!map_filename.empty()) {
656 std::ifstream mf(map_filename);
657 std::string type, symbol;
658 int variable, index;
659 while (mf >> type >> variable >> index >> symbol) {
660 RTLIL::IdString escaped_s = RTLIL::escape_id(symbol);
661 if (type == "input") {
662 log_assert(static_cast<unsigned>(variable) < inputs.size());
663 RTLIL::Wire* wire = inputs[variable];
664 log_assert(wire);
665 log_assert(wire->port_input);
666
667 if (index == 0) {
668 // Cope with the fact that a CI might be identical
669 // to a PI (necessary due to ABC); in those cases
670 // simply connect the latter to the former
671 RTLIL::Wire* existing = module->wire(escaped_s);
672 if (!existing)
673 module->rename(wire, escaped_s);
674 else {
675 wire->port_input = false;
676 module->connect(wire, existing);
677 }
678 }
679 else if (index > 0) {
680 std::string indexed_name = stringf("%s[%d]", escaped_s.c_str(), index);
681 RTLIL::Wire* existing = module->wire(indexed_name);
682 if (!existing) {
683 module->rename(wire, indexed_name);
684 if (wideports)
685 wideports_cache[escaped_s] = std::max(wideports_cache[escaped_s], index);
686 }
687 else {
688 module->connect(wire, existing);
689 wire->port_input = false;
690 }
691 }
692 }
693 else if (type == "output") {
694 log_assert(static_cast<unsigned>(variable + co_count) < outputs.size());
695 RTLIL::Wire* wire = outputs[variable + co_count];
696 log_assert(wire);
697 log_assert(wire->port_output);
698
699 if (index == 0) {
700 // Cope with the fact that a CO might be identical
701 // to a PO (necessary due to ABC); in those cases
702 // simply connect the latter to the former
703 RTLIL::Wire* existing = module->wire(escaped_s);
704 if (!existing) {
705 if (escaped_s.ends_with("$inout.out")) {
706 wire->port_output = false;
707 RTLIL::Wire *in_wire = module->wire(escaped_s.substr(0, escaped_s.size()-10));
708 log_assert(in_wire);
709 log_assert(in_wire->port_input && !in_wire->port_output);
710 in_wire->port_output = true;
711 module->connect(in_wire, wire);
712 }
713 else
714 module->rename(wire, escaped_s);
715 }
716 else {
717 wire->port_output = false;
718 module->connect(wire, existing);
719 }
720 }
721 else if (index > 0) {
722 std::string indexed_name = stringf("%s[%d]", escaped_s.c_str(), index);
723 RTLIL::Wire* existing = module->wire(indexed_name);
724 if (!existing) {
725 if (escaped_s.ends_with("$inout.out")) {
726 wire->port_output = false;
727 RTLIL::Wire *in_wire = module->wire(stringf("%s[%d]", escaped_s.substr(0, escaped_s.size()-10).c_str(), index));
728 log_assert(in_wire);
729 log_assert(in_wire->port_input && !in_wire->port_output);
730 in_wire->port_output = true;
731 module->connect(in_wire, wire);
732 }
733 else {
734 module->rename(wire, indexed_name);
735 if (wideports)
736 wideports_cache[escaped_s] = std::max(wideports_cache[escaped_s], index);
737 }
738 }
739 else {
740 module->connect(wire, existing);
741 wire->port_output = false;
742 }
743 }
744 }
745 else if (type == "box") {
746 RTLIL::Cell* cell = module->cell(stringf("$__box%d__", variable));
747 if (cell) { // ABC could have optimised this box away
748 module->rename(cell, escaped_s);
749 RTLIL::Module* box_module = design->module(cell->type);
750 log_assert(box_module);
751
752 for (const auto &i : cell->connections()) {
753 RTLIL::IdString port_name = i.first;
754 RTLIL::SigSpec rhs = i.second;
755 int index = 0;
756 for (auto bit : rhs.bits()) {
757 RTLIL::Wire* wire = bit.wire;
758 RTLIL::IdString escaped_s = RTLIL::escape_id(stringf("%s.%s", log_id(cell), log_id(port_name)));
759 if (index == 0)
760 module->rename(wire, escaped_s);
761 else if (index > 0) {
762 module->rename(wire, stringf("%s[%d]", escaped_s.c_str(), index));
763 if (wideports)
764 wideports_cache[escaped_s] = std::max(wideports_cache[escaped_s], index);
765 }
766 index++;
767 }
768 }
769 }
770 }
771 else
772 log_error("Symbol type '%s' not recognised.\n", type.c_str());
773 }
774 }
775
776 for (auto &wp : wideports_cache) {
777 auto name = wp.first;
778 int width = wp.second + 1;
779
780 RTLIL::Wire *wire = module->wire(name);
781 if (wire)
782 module->rename(wire, RTLIL::escape_id(stringf("%s[%d]", name.c_str(), 0)));
783
784 // Do not make ports with a mix of input/output into
785 // wide ports
786 bool port_input = false, port_output = false;
787 for (int i = 0; i < width; i++) {
788 RTLIL::IdString other_name = name.str() + stringf("[%d]", i);
789 RTLIL::Wire *other_wire = module->wire(other_name);
790 if (other_wire) {
791 port_input = port_input || other_wire->port_input;
792 port_output = port_output || other_wire->port_output;
793 }
794 }
795
796 wire = module->addWire(name, width);
797 wire->port_input = port_input;
798 wire->port_output = port_output;
799
800 for (int i = 0; i < width; i++) {
801 RTLIL::IdString other_name = name.str() + stringf("[%d]", i);
802 RTLIL::Wire *other_wire = module->wire(other_name);
803 if (other_wire) {
804 other_wire->port_input = false;
805 other_wire->port_output = false;
806 if (wire->port_input)
807 module->connect(other_wire, SigSpec(wire, i));
808 else
809 module->connect(SigSpec(wire, i), other_wire);
810 }
811 }
812 }
813
814 module->fixup_ports();
815 design->add(module);
816
817 design->selection_stack.emplace_back(false);
818 RTLIL::Selection& sel = design->selection_stack.back();
819 sel.select(module);
820
821 Pass::call(design, "clean");
822
823 design->selection_stack.pop_back();
824
825 for (auto cell : module->cells().to_vector()) {
826 if (cell->type != "$lut") continue;
827 auto y_port = cell->getPort("\\Y").as_bit();
828 if (y_port.wire->width == 1)
829 module->rename(cell, stringf("%s$lut", y_port.wire->name.c_str()));
830 else
831 module->rename(cell, stringf("%s[%d]$lut", y_port.wire->name.c_str(), y_port.offset));
832 }
833 }
834
835 struct AigerFrontend : public Frontend {
836 AigerFrontend() : Frontend("aiger", "read AIGER file") { }
837 void help() YS_OVERRIDE
838 {
839 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
840 log("\n");
841 log(" read_aiger [options] [filename]\n");
842 log("\n");
843 log("Load module from an AIGER file into the current design.\n");
844 log("\n");
845 log(" -module_name <module_name>\n");
846 log(" Name of module to be created (default: <filename>)\n");
847 log("\n");
848 log(" -clk_name <wire_name>\n");
849 log(" AIGER latches to be transformed into posedge DFFs clocked by wire of");
850 log(" this name (default: clk)\n");
851 log("\n");
852 log(" -map <filename>\n");
853 log(" read file with port and latch symbols\n");
854 log("\n");
855 log(" -wideports\n");
856 log(" Merge ports that match the pattern 'name[int]' into a single\n");
857 log(" multi-bit port 'name'.\n");
858 log("\n");
859 }
860 void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
861 {
862 log_header(design, "Executing AIGER frontend.\n");
863
864 RTLIL::IdString clk_name = "\\clk";
865 RTLIL::IdString module_name;
866 std::string map_filename;
867 bool wideports = false;
868
869 size_t argidx;
870 for (argidx = 1; argidx < args.size(); argidx++) {
871 std::string arg = args[argidx];
872 if (arg == "-module_name" && argidx+1 < args.size()) {
873 module_name = RTLIL::escape_id(args[++argidx]);
874 continue;
875 }
876 if (arg == "-clk_name" && argidx+1 < args.size()) {
877 clk_name = RTLIL::escape_id(args[++argidx]);
878 continue;
879 }
880 if (map_filename.empty() && arg == "-map" && argidx+1 < args.size()) {
881 map_filename = args[++argidx];
882 continue;
883 }
884 if (arg == "-wideports") {
885 wideports = true;
886 continue;
887 }
888 break;
889 }
890 extra_args(f, filename, args, argidx);
891
892 if (module_name.empty()) {
893 #ifdef _WIN32
894 char fname[_MAX_FNAME];
895 _splitpath(filename.c_str(), NULL /* drive */, NULL /* dir */, fname, NULL /* ext */)
896 module_name = fname;
897 #else
898 char* bn = strdup(filename.c_str());
899 module_name = RTLIL::escape_id(bn);
900 free(bn);
901 #endif
902 }
903
904 AigerReader reader(design, *f, module_name, clk_name, map_filename, wideports);
905 reader.parse_aiger();
906 }
907 } AigerFrontend;
908
909 YOSYS_NAMESPACE_END