Removed debug code from write_smt2
[yosys.git] / backends / smt2 / smt2.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/log.h"
25 #include <string>
26
27 USING_YOSYS_NAMESPACE
28 PRIVATE_NAMESPACE_BEGIN
29
30 struct Smt2Worker
31 {
32 CellTypes ct;
33 SigMap sigmap;
34 RTLIL::Module *module;
35 bool bvmode, memmode, verbose;
36 int idcounter;
37
38 std::vector<std::string> decls, trans;
39 std::map<RTLIL::SigBit, RTLIL::Cell*> bit_driver;
40 std::set<RTLIL::Cell*> exported_cells;
41 pool<Cell*> recursive_cells, registers;
42
43 std::map<RTLIL::SigBit, std::pair<int, int>> fcache;
44 std::map<Cell*, int> memarrays;
45 std::map<int, int> bvsizes;
46
47 Smt2Worker(RTLIL::Module *module, bool bvmode, bool memmode, bool verbose) :
48 ct(module->design), sigmap(module), module(module), bvmode(bvmode), memmode(memmode), verbose(verbose), idcounter(0)
49 {
50 decls.push_back(stringf("(declare-sort |%s_s| 0)\n", log_id(module)));
51
52 for (auto cell : module->cells())
53 for (auto &conn : cell->connections()) {
54 bool is_input = ct.cell_input(cell->type, conn.first);
55 bool is_output = ct.cell_output(cell->type, conn.first);
56 if (is_output && !is_input)
57 for (auto bit : sigmap(conn.second)) {
58 if (bit_driver.count(bit))
59 log_error("Found multiple drivers for %s.\n", log_signal(bit));
60 bit_driver[bit] = cell;
61 }
62 else if (is_output || !is_input)
63 log_error("Unsupported or unknown directionality on port %s of cell %s.%s (%s).\n",
64 log_id(conn.first), log_id(module), log_id(cell), log_id(cell->type));
65 }
66 }
67
68 void register_bool(RTLIL::SigBit bit, int id)
69 {
70 if (verbose) log("%*s-> register_bool: %s %d\n", 2+2*GetSize(recursive_cells), "",
71 log_signal(bit), id);
72
73 sigmap.apply(bit);
74 log_assert(fcache.count(bit) == 0);
75 fcache[bit] = std::pair<int, int>(id, -1);
76 }
77
78 void register_bv(RTLIL::SigSpec sig, int id)
79 {
80 if (verbose) log("%*s-> register_bv: %s %d\n", 2+2*GetSize(recursive_cells), "",
81 log_signal(sig), id);
82
83 log_assert(bvmode);
84 sigmap.apply(sig);
85
86 log_assert(bvsizes.count(id) == 0);
87 bvsizes[id] = GetSize(sig);
88
89 for (int i = 0; i < GetSize(sig); i++) {
90 log_assert(fcache.count(sig[i]) == 0);
91 fcache[sig[i]] = std::pair<int, int>(id, i);
92 }
93 }
94
95 void register_boolvec(RTLIL::SigSpec sig, int id)
96 {
97 if (verbose) log("%*s-> register_boolvec: %s %d\n", 2+2*GetSize(recursive_cells), "",
98 log_signal(sig), id);
99
100 log_assert(bvmode);
101 sigmap.apply(sig);
102 register_bool(sig[0], id);
103
104 for (int i = 1; i < GetSize(sig); i++)
105 sigmap.add(sig[i], RTLIL::State::S0);
106 }
107
108 std::string get_bool(RTLIL::SigBit bit, const char *state_name = "state")
109 {
110 sigmap.apply(bit);
111
112 if (bit.wire == nullptr)
113 return bit == RTLIL::State::S1 ? "true" : "false";
114
115 if (bit_driver.count(bit))
116 export_cell(bit_driver.at(bit));
117 sigmap.apply(bit);
118
119 if (fcache.count(bit) == 0) {
120 if (verbose) log("%*s-> external bool: %s\n", 2+2*GetSize(recursive_cells), "",
121 log_signal(bit));
122 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
123 log_id(module), idcounter, log_id(module), log_signal(bit)));
124 register_bool(bit, idcounter++);
125 }
126
127 auto f = fcache.at(bit);
128 if (f.second >= 0)
129 return stringf("(= ((_ extract %d %d) (|%s#%d| %s)) #b1)", f.second, f.second, log_id(module), f.first, state_name);
130 return stringf("(|%s#%d| %s)", log_id(module), f.first, state_name);
131 }
132
133 std::string get_bool(RTLIL::SigSpec sig, const char *state_name = "state")
134 {
135 return get_bool(sig.to_single_sigbit(), state_name);
136 }
137
138 std::string get_bv(RTLIL::SigSpec sig, const char *state_name = "state")
139 {
140 log_assert(bvmode);
141 sigmap.apply(sig);
142
143 std::vector<std::string> subexpr;
144
145 SigSpec orig_sig;
146 while (orig_sig != sig) {
147 for (auto bit : sig)
148 if (bit_driver.count(bit))
149 export_cell(bit_driver.at(bit));
150 orig_sig = sig;
151 sigmap.apply(sig);
152 }
153
154 for (int i = 0, j = 1; i < GetSize(sig); i += j, j = 1)
155 {
156 if (sig[i].wire == nullptr) {
157 while (i+j < GetSize(sig) && sig[i+j].wire == nullptr) j++;
158 subexpr.push_back("#b");
159 for (int k = i+j-1; k >= i; k--)
160 subexpr.back() += sig[k] == RTLIL::State::S1 ? "1" : "0";
161 continue;
162 }
163
164 if (fcache.count(sig[i]) && fcache.at(sig[i]).second == -1) {
165 subexpr.push_back(stringf("(ite %s #b1 #b0)", get_bool(sig[i], state_name).c_str()));
166 continue;
167 }
168
169 if (fcache.count(sig[i])) {
170 auto t1 = fcache.at(sig[i]);
171 while (i+j < GetSize(sig)) {
172 if (fcache.count(sig[i+j]) == 0)
173 break;
174 auto t2 = fcache.at(sig[i+j]);
175 if (t1.first != t2.first)
176 break;
177 if (t1.second+j != t2.second)
178 break;
179 j++;
180 }
181 if (t1.second == 0 && j == bvsizes.at(t1.first))
182 subexpr.push_back(stringf("(|%s#%d| %s)", log_id(module), t1.first, state_name));
183 else
184 subexpr.push_back(stringf("((_ extract %d %d) (|%s#%d| %s))",
185 t1.second + j - 1, t1.second, log_id(module), t1.first, state_name));
186 continue;
187 }
188
189 std::set<RTLIL::SigBit> seen_bits = { sig[i] };
190 while (i+j < GetSize(sig) && sig[i+j].wire && !fcache.count(sig[i+j]) && !seen_bits.count(sig[i+j]))
191 seen_bits.insert(sig[i+j]), j++;
192
193 if (verbose) log("%*s-> external bv: %s\n", 2+2*GetSize(recursive_cells), "",
194 log_signal(sig.extract(i, j)));
195 for (auto bit : sig.extract(i, j))
196 log_assert(bit_driver.count(bit) == 0);
197 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
198 log_id(module), idcounter, log_id(module), j, log_signal(sig.extract(i, j))));
199 subexpr.push_back(stringf("(|%s#%d| %s)", log_id(module), idcounter, state_name));
200 register_bv(sig.extract(i, j), idcounter++);
201 }
202
203 if (GetSize(subexpr) > 1) {
204 std::string expr = "(concat";
205 for (int i = GetSize(subexpr)-1; i >= 0; i--)
206 expr += " " + subexpr[i];
207 return expr + ")";
208 } else {
209 log_assert(GetSize(subexpr) == 1);
210 return subexpr[0];
211 }
212 }
213
214 void export_gate(RTLIL::Cell *cell, std::string expr)
215 {
216 RTLIL::SigBit bit = sigmap(cell->getPort("\\Y").to_single_sigbit());
217 std::string processed_expr;
218
219 for (char ch : expr) {
220 if (ch == 'A') processed_expr += get_bool(cell->getPort("\\A"));
221 else if (ch == 'B') processed_expr += get_bool(cell->getPort("\\B"));
222 else if (ch == 'C') processed_expr += get_bool(cell->getPort("\\C"));
223 else if (ch == 'D') processed_expr += get_bool(cell->getPort("\\D"));
224 else if (ch == 'S') processed_expr += get_bool(cell->getPort("\\S"));
225 else processed_expr += ch;
226 }
227
228 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
229 log_id(cell));
230 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
231 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(bit)));
232 register_bool(bit, idcounter++);
233 recursive_cells.erase(cell);
234 }
235
236 void export_bvop(RTLIL::Cell *cell, std::string expr, char type = 0)
237 {
238 RTLIL::SigSpec sig_a, sig_b;
239 RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y"));
240 bool is_signed = cell->getParam("\\A_SIGNED").as_bool();
241 int width = GetSize(sig_y);
242
243 if (type == 's' || type == 'd' || type == 'b') {
244 width = std::max(width, GetSize(cell->getPort("\\A")));
245 width = std::max(width, GetSize(cell->getPort("\\B")));
246 }
247
248 if (cell->hasPort("\\A")) {
249 sig_a = cell->getPort("\\A");
250 sig_a.extend_u0(width, is_signed);
251 }
252
253 if (cell->hasPort("\\B")) {
254 sig_b = cell->getPort("\\B");
255 sig_b.extend_u0(width, is_signed && !(type == 's'));
256 }
257
258 std::string processed_expr;
259
260 for (char ch : expr) {
261 if (ch == 'A') processed_expr += get_bv(sig_a);
262 else if (ch == 'B') processed_expr += get_bv(sig_b);
263 else if (ch == 'L') processed_expr += is_signed ? "a" : "l";
264 else if (ch == 'U') processed_expr += is_signed ? "s" : "u";
265 else processed_expr += ch;
266 }
267
268 if (width != GetSize(sig_y) && type != 'b')
269 processed_expr = stringf("((_ extract %d 0) %s)", GetSize(sig_y)-1, processed_expr.c_str());
270
271 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
272 log_id(cell));
273
274 if (type == 'b') {
275 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
276 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(sig_y)));
277 register_boolvec(sig_y, idcounter++);
278 } else {
279 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
280 log_id(module), idcounter, log_id(module), GetSize(sig_y), processed_expr.c_str(), log_signal(sig_y)));
281 register_bv(sig_y, idcounter++);
282 }
283
284 recursive_cells.erase(cell);
285 }
286
287 void export_reduce(RTLIL::Cell *cell, std::string expr, bool identity_val)
288 {
289 RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y"));
290 std::string processed_expr;
291
292 for (char ch : expr)
293 if (ch == 'A' || ch == 'B') {
294 RTLIL::SigSpec sig = sigmap(cell->getPort(stringf("\\%c", ch)));
295 for (auto bit : sig)
296 processed_expr += " " + get_bool(bit);
297 if (GetSize(sig) == 1)
298 processed_expr += identity_val ? " true" : " false";
299 } else
300 processed_expr += ch;
301
302 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
303 log_id(cell));
304 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
305 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(sig_y)));
306 register_boolvec(sig_y, idcounter++);
307 recursive_cells.erase(cell);
308 }
309
310 void export_cell(RTLIL::Cell *cell)
311 {
312 if (verbose) log("%*s=> export_cell %s (%s) [%s]\n", 2+2*GetSize(recursive_cells), "",
313 log_id(cell), log_id(cell->type), exported_cells.count(cell) ? "old" : "new");
314
315 if (recursive_cells.count(cell))
316 log_error("Found logic loop in module %s! See cell %s.\n", log_id(module), log_id(cell));
317
318 if (exported_cells.count(cell))
319 return;
320
321 exported_cells.insert(cell);
322 recursive_cells.insert(cell);
323
324 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_")
325 {
326 registers.insert(cell);
327 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
328 log_id(module), idcounter, log_id(module), log_signal(cell->getPort("\\Q"))));
329 register_bool(cell->getPort("\\Q"), idcounter++);
330 recursive_cells.erase(cell);
331 return;
332 }
333
334 if (cell->type == "$_BUF_") return export_gate(cell, "A");
335 if (cell->type == "$_NOT_") return export_gate(cell, "(not A)");
336 if (cell->type == "$_AND_") return export_gate(cell, "(and A B)");
337 if (cell->type == "$_NAND_") return export_gate(cell, "(not (and A B))");
338 if (cell->type == "$_OR_") return export_gate(cell, "(or A B)");
339 if (cell->type == "$_NOR_") return export_gate(cell, "(not (or A B))");
340 if (cell->type == "$_XOR_") return export_gate(cell, "(xor A B)");
341 if (cell->type == "$_XNOR_") return export_gate(cell, "(not (xor A B))");
342 if (cell->type == "$_MUX_") return export_gate(cell, "(ite S B A)");
343 if (cell->type == "$_AOI3_") return export_gate(cell, "(not (or (and A B) C))");
344 if (cell->type == "$_OAI3_") return export_gate(cell, "(not (and (or A B) C))");
345 if (cell->type == "$_AOI4_") return export_gate(cell, "(not (or (and A B) (and C D)))");
346 if (cell->type == "$_OAI4_") return export_gate(cell, "(not (and (or A B) (or C D)))");
347
348 // FIXME: $lut
349
350 if (bvmode)
351 {
352 if (cell->type == "$dff")
353 {
354 registers.insert(cell);
355 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
356 log_id(module), idcounter, log_id(module), GetSize(cell->getPort("\\Q")), log_signal(cell->getPort("\\Q"))));
357 register_bv(cell->getPort("\\Q"), idcounter++);
358 recursive_cells.erase(cell);
359 return;
360 }
361
362 if (cell->type == "$and") return export_bvop(cell, "(bvand A B)");
363 if (cell->type == "$or") return export_bvop(cell, "(bvor A B)");
364 if (cell->type == "$xor") return export_bvop(cell, "(bvxor A B)");
365 if (cell->type == "$xnor") return export_bvop(cell, "(bvxnor A B)");
366
367 if (cell->type == "$shl") return export_bvop(cell, "(bvshl A B)", 's');
368 if (cell->type == "$shr") return export_bvop(cell, "(bvlshr A B)", 's');
369 if (cell->type == "$sshl") return export_bvop(cell, "(bvshl A B)", 's');
370 if (cell->type == "$sshr") return export_bvop(cell, "(bvLshr A B)", 's');
371
372 // FIXME: $shift $shiftx
373
374 if (cell->type == "$lt") return export_bvop(cell, "(bvUlt A B)", 'b');
375 if (cell->type == "$le") return export_bvop(cell, "(bvUle A B)", 'b');
376 if (cell->type == "$ge") return export_bvop(cell, "(bvUge A B)", 'b');
377 if (cell->type == "$gt") return export_bvop(cell, "(bvUgt A B)", 'b');
378
379 if (cell->type == "$ne") return export_bvop(cell, "(distinct A B)", 'b');
380 if (cell->type == "$nex") return export_bvop(cell, "(distinct A B)", 'b');
381 if (cell->type == "$eq") return export_bvop(cell, "(= A B)", 'b');
382 if (cell->type == "$eqx") return export_bvop(cell, "(= A B)", 'b');
383
384 if (cell->type == "$not") return export_bvop(cell, "(bvnot A)");
385 if (cell->type == "$pos") return export_bvop(cell, "A");
386 if (cell->type == "$neg") return export_bvop(cell, "(bvneg A)");
387
388 if (cell->type == "$add") return export_bvop(cell, "(bvadd A B)");
389 if (cell->type == "$sub") return export_bvop(cell, "(bvsub A B)");
390 if (cell->type == "$mul") return export_bvop(cell, "(bvmul A B)");
391 if (cell->type == "$div") return export_bvop(cell, "(bvUdiv A B)", 'd');
392 if (cell->type == "$mod") return export_bvop(cell, "(bvUrem A B)", 'd');
393
394 if (cell->type == "$reduce_and") return export_reduce(cell, "(and A)", true);
395 if (cell->type == "$reduce_or") return export_reduce(cell, "(or A)", false);
396 if (cell->type == "$reduce_xor") return export_reduce(cell, "(xor A)", false);
397 if (cell->type == "$reduce_xnor") return export_reduce(cell, "(not (xor A))", false);
398 if (cell->type == "$reduce_bool") return export_reduce(cell, "(or A)", false);
399
400 if (cell->type == "$logic_not") return export_reduce(cell, "(not (or A))", false);
401 if (cell->type == "$logic_and") return export_reduce(cell, "(and (or A) (or B))", false);
402 if (cell->type == "$logic_or") return export_reduce(cell, "(or A B)", false);
403
404 if (cell->type == "$mux" || cell->type == "$pmux")
405 {
406 int width = GetSize(cell->getPort("\\Y"));
407 std::string processed_expr = get_bv(cell->getPort("\\A"));
408
409 RTLIL::SigSpec sig_b = cell->getPort("\\B");
410 RTLIL::SigSpec sig_s = cell->getPort("\\S");
411 get_bv(sig_b);
412 get_bv(sig_s);
413
414 for (int i = 0; i < GetSize(sig_s); i++)
415 processed_expr = stringf("(ite %s %s %s)", get_bool(sig_s[i]).c_str(),
416 get_bv(sig_b.extract(i*width, width)).c_str(), processed_expr.c_str());
417
418 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
419 log_id(cell));
420 RTLIL::SigSpec sig = sigmap(cell->getPort("\\Y"));
421 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
422 log_id(module), idcounter, log_id(module), width, processed_expr.c_str(), log_signal(sig)));
423 register_bv(sig, idcounter++);
424 recursive_cells.erase(cell);
425 return;
426 }
427
428 // FIXME: $slice $concat
429 }
430
431 if (memmode && cell->type == "$mem")
432 {
433 int arrayid = idcounter++;
434 memarrays[cell] = arrayid;
435
436 int abits = cell->getParam("\\ABITS").as_int();
437 int width = cell->getParam("\\WIDTH").as_int();
438 int rd_ports = cell->getParam("\\RD_PORTS").as_int();
439
440 decls.push_back(stringf("(declare-fun |%s#%d#0| (|%s_s|) (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
441 log_id(module), arrayid, log_id(module), abits, width, log_id(cell)));
442
443 for (int i = 0; i < rd_ports; i++)
444 {
445 std::string addr = get_bv(cell->getPort("\\RD_ADDR").extract(abits*i, abits));
446 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(width*i, width);
447
448 if (cell->getParam("\\RD_CLK_ENABLE").extract(i).as_bool())
449 log_error("Read port %d (%s) of memory %s.%s is clocked. This is not supported by \"write_smt2\"! "
450 "Call \"memory\" with -nordff to avoid this error.\n", i, log_signal(data_sig), log_id(cell), log_id(module));
451
452 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) (select (|%s#%d#0| state) %s)) ; %s\n",
453 log_id(module), idcounter, log_id(module), width, log_id(module), arrayid, addr.c_str(), log_signal(data_sig)));
454 register_bv(data_sig, idcounter++);
455 }
456
457 registers.insert(cell);
458 recursive_cells.erase(cell);
459 return;
460 }
461
462 log_error("Unsupported cell type %s for cell %s.%s. (Maybe this cell type would be supported in -bv or -mem mode?)\n",
463 log_id(cell->type), log_id(module), log_id(cell));
464 }
465
466 void run()
467 {
468 if (verbose) log("=> export logic driving outputs\n");
469
470 for (auto wire : module->wires())
471 if (wire->port_id || wire->get_bool_attribute("\\keep")) {
472 RTLIL::SigSpec sig = sigmap(wire);
473 if (bvmode && GetSize(sig) > 1) {
474 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) (_ BitVec %d) %s)\n",
475 log_id(module), log_id(wire), log_id(module), GetSize(sig), get_bv(sig).c_str()));
476 } else {
477 for (int i = 0; i < GetSize(sig); i++)
478 if (GetSize(sig) > 1)
479 decls.push_back(stringf("(define-fun |%s_n %s %d| ((state |%s_s|)) Bool %s)\n",
480 log_id(module), log_id(wire), i, log_id(module), get_bool(sig[i]).c_str()));
481 else
482 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) Bool %s)\n",
483 log_id(module), log_id(wire), log_id(module), get_bool(sig[i]).c_str()));
484 }
485 }
486
487 if (verbose) log("=> export logic associated with the initial state\n");
488
489 vector<string> init_list;
490 for (auto wire : module->wires())
491 if (wire->attributes.count("\\init")) {
492 RTLIL::SigSpec sig = sigmap(wire);
493 Const val = wire->attributes.at("\\init");
494 val.bits.resize(GetSize(sig));
495 if (bvmode && GetSize(sig) > 1) {
496 init_list.push_back(stringf("(= %s #b%s) ; %s", get_bv(sig).c_str(), val.as_string().c_str(), log_id(wire)));
497 } else {
498 for (int i = 0; i < GetSize(sig); i++)
499 init_list.push_back(stringf("(= %s %s) ; %s", get_bool(sig[i]).c_str(), val.bits[i] == State::S1 ? "true" : "false", log_id(wire)));
500 }
501 }
502
503 if (verbose) log("=> export logic driving asserts\n");
504
505 vector<int> assert_list, assume_list;
506 for (auto cell : module->cells())
507 if (cell->type.in("$assert", "$assume")) {
508 string name_a = get_bool(cell->getPort("\\A"));
509 string name_en = get_bool(cell->getPort("\\EN"));
510 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool (or %s (not %s))) ; %s\n",
511 log_id(module), idcounter, log_id(module), name_a.c_str(), name_en.c_str(), log_id(cell)));
512 if (cell->type == "$assert")
513 assert_list.push_back(idcounter++);
514 else
515 assume_list.push_back(idcounter++);
516 }
517
518 for (int iter = 1; !registers.empty(); iter++)
519 {
520 pool<Cell*> this_regs;
521 this_regs.swap(registers);
522
523 if (verbose) log("=> export logic driving registers [iteration %d]\n", iter);
524
525 for (auto cell : this_regs)
526 {
527 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_")
528 {
529 std::string expr_d = get_bool(cell->getPort("\\D"));
530 std::string expr_q = get_bool(cell->getPort("\\Q"), "next_state");
531 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell), log_signal(cell->getPort("\\Q"))));
532 }
533
534 if (cell->type == "$dff")
535 {
536 std::string expr_d = get_bv(cell->getPort("\\D"));
537 std::string expr_q = get_bv(cell->getPort("\\Q"), "next_state");
538 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell), log_signal(cell->getPort("\\Q"))));
539 }
540
541 if (cell->type == "$mem")
542 {
543 int arrayid = memarrays.at(cell);
544
545 int abits = cell->getParam("\\ABITS").as_int();
546 int width = cell->getParam("\\WIDTH").as_int();
547 int wr_ports = cell->getParam("\\WR_PORTS").as_int();
548
549 for (int i = 0; i < wr_ports; i++)
550 {
551 std::string addr = get_bv(cell->getPort("\\WR_ADDR").extract(abits*i, abits));
552 std::string data = get_bv(cell->getPort("\\WR_DATA").extract(width*i, width));
553 std::string mask = get_bv(cell->getPort("\\WR_EN").extract(width*i, width));
554
555 data = stringf("(bvor (bvand %s %s) (bvand (select (|%s#%d#%d| state) %s) (bvnot %s)))",
556 data.c_str(), mask.c_str(), log_id(module), arrayid, i, addr.c_str(), mask.c_str());
557
558 decls.push_back(stringf("(define-fun |%s#%d#%d| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) "
559 "(store (|%s#%d#%d| state) %s %s)) ; %s\n",
560 log_id(module), arrayid, i+1, log_id(module), abits, width,
561 log_id(module), arrayid, i, addr.c_str(), data.c_str(), log_id(cell)));
562 }
563
564 std::string expr_d = stringf("(|%s#%d#%d| state)", log_id(module), arrayid, wr_ports);
565 std::string expr_q = stringf("(|%s#%d#0| next_state)", log_id(module), arrayid);
566 trans.push_back(stringf(" (= %s %s) ; %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell)));
567 }
568 }
569 }
570
571 string assert_expr = assert_list.empty() ? "true" : "(and";
572 if (!assert_list.empty()) {
573 for (int i : assert_list)
574 assert_expr += stringf(" (|%s#%d| state)", log_id(module), i);
575 assert_expr += ")";
576 }
577 decls.push_back(stringf("(define-fun |%s_a| ((state |%s_s|)) Bool %s)\n",
578 log_id(module), log_id(module), assert_expr.c_str()));
579
580 string assume_expr = assume_list.empty() ? "true" : "(and";
581 if (!assume_list.empty()) {
582 for (int i : assume_list)
583 assume_expr += stringf(" (|%s#%d| state)", log_id(module), i);
584 assume_expr += ")";
585 }
586 decls.push_back(stringf("(define-fun |%s_u| ((state |%s_s|)) Bool %s)\n",
587 log_id(module), log_id(module), assume_expr.c_str()));
588
589 string init_expr = init_list.empty() ? "true" : "(and";
590 if (!init_list.empty()) {
591 for (auto &str : init_list)
592 init_expr += stringf("\n\t%s", str.c_str());
593 init_expr += "\n)";
594 }
595 decls.push_back(stringf("(define-fun |%s_i| ((state |%s_s|)) Bool %s)\n",
596 log_id(module), log_id(module), init_expr.c_str()));
597 }
598
599 void write(std::ostream &f)
600 {
601 for (auto it : decls)
602 f << it;
603
604 f << stringf("(define-fun |%s_t| ((state |%s_s|) (next_state |%s_s|)) Bool ", log_id(module), log_id(module), log_id(module));
605 if (GetSize(trans) > 1) {
606 f << "(and\n";
607 for (auto it : trans)
608 f << it;
609 f << "))";
610 } else
611 if (GetSize(trans) == 1)
612 f << "\n" + trans.front() + ")";
613 else
614 f << "true)";
615 f << stringf(" ; end of module %s\n", log_id(module));
616 }
617 };
618
619 struct Smt2Backend : public Backend {
620 Smt2Backend() : Backend("smt2", "write design to SMT-LIBv2 file") { }
621 virtual void help()
622 {
623 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
624 log("\n");
625 log(" write_smt2 [options] [filename]\n");
626 log("\n");
627 log("Write a SMT-LIBv2 [1] description of the current design. For a module with name\n");
628 log("'<mod>' this will declare the sort '<mod>_s' (state of the module) and the\n");
629 log("functions operating on that state.\n");
630 log("\n");
631 log("The '<mod>_s' sort represents a module state. Additional '<mod>_n' functions\n");
632 log("are provided that can be used to access the values of the signals in the module.\n");
633 log("Only ports, and signals with the 'keep' attribute set are made available via\n");
634 log("such functions. Without the -bv option, multi-bit wires are exported as\n");
635 log("separate functions of type Bool for the individual bits. With the -bv option\n");
636 log("multi-bit wires are exported as single functions of type BitVec.\n");
637 log("\n");
638 log("The '<mod>_t' function evaluates to 'true' when the given pair of states\n");
639 log("describes a valid state transition.\n");
640 log("\n");
641 log("The '<mod>_a' function evaluates to 'true' when the given state satisfies\n");
642 log("the asserts in the module.\n");
643 log("\n");
644 log("The '<mod>_u' function evaluates to 'true' when the given state satisfies\n");
645 log("the assumptions in the module.\n");
646 log("\n");
647 log("The '<mod>_i' function evaluates to 'true' when the given state conforms\n");
648 log("to the initial state.\n");
649 log("\n");
650 log(" -verbose\n");
651 log(" this will print the recursive walk used to export the modules.\n");
652 log("\n");
653 log(" -bv\n");
654 log(" enable support for BitVec (FixedSizeBitVectors theory). with this\n");
655 log(" option set multi-bit wires are represented using the BitVec sort and\n");
656 log(" support for coarse grain cells (incl. arithmetic) is enabled.\n");
657 log("\n");
658 log(" -mem\n");
659 log(" enable support for memories (via ArraysEx theory). this option\n");
660 log(" also implies -bv. only $mem cells without merged registers in\n");
661 log(" read ports are supported. call \"memory\" with -nordff to make sure\n");
662 log(" that no registers are merged into $mem read ports.\n");
663 log("\n");
664 log(" -tpl <template_file>\n");
665 log(" use the given template file. the line containing only the token '%%%%'\n");
666 log(" is replaced with the regular output of this command.\n");
667 log("\n");
668 log("[1] For more information on SMT-LIBv2 visit http://smt-lib.org/ or read David\n");
669 log("R. Cok's tutorial: http://www.grammatech.com/resources/smt/SMTLIBTutorial.pdf\n");
670 log("\n");
671 log("---------------------------------------------------------------------------\n");
672 log("\n");
673 log("Example:\n");
674 log("\n");
675 log("Consider the following module (test.v). We want to prove that the output can\n");
676 log("never transition from a non-zero value to a zero value.\n");
677 log("\n");
678 log(" module test(input clk, output reg [3:0] y);\n");
679 log(" always @(posedge clk)\n");
680 log(" y <= (y << 1) | ^y;\n");
681 log(" endmodule\n");
682 log("\n");
683 log("For this proof we create the following template (test.tpl).\n");
684 log("\n");
685 log(" ; we need QF_UFBV for this poof\n");
686 log(" (set-logic QF_UFBV)\n");
687 log("\n");
688 log(" ; insert the auto-generated code here\n");
689 log(" %%%%\n");
690 log("\n");
691 log(" ; declare two state variables s1 and s2\n");
692 log(" (declare-fun s1 () test_s)\n");
693 log(" (declare-fun s2 () test_s)\n");
694 log("\n");
695 log(" ; state s2 is the successor of state s1\n");
696 log(" (assert (test_t s1 s2))\n");
697 log("\n");
698 log(" ; we are looking for a model with y non-zero in s1\n");
699 log(" (assert (distinct (|test_n y| s1) #b0000))\n");
700 log("\n");
701 log(" ; we are looking for a model with y zero in s2\n");
702 log(" (assert (= (|test_n y| s2) #b0000))\n");
703 log("\n");
704 log(" ; is there such a model?\n");
705 log(" (check-sat)\n");
706 log("\n");
707 log("The following yosys script will create a 'test.smt2' file for our proof:\n");
708 log("\n");
709 log(" read_verilog test.v\n");
710 log(" hierarchy -check; proc; opt; check -assert\n");
711 log(" write_smt2 -bv -tpl test.tpl test.smt2\n");
712 log("\n");
713 log("Running 'cvc4 test.smt2' will print 'unsat' because y can never transition\n");
714 log("from non-zero to zero in the test design.\n");
715 log("\n");
716 }
717 virtual void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
718 {
719 std::ifstream template_f;
720 bool bvmode = false, memmode = false, verbose = false;
721
722 log_header("Executing SMT2 backend.\n");
723
724 size_t argidx;
725 for (argidx = 1; argidx < args.size(); argidx++)
726 {
727 if (args[argidx] == "-tpl" && argidx+1 < args.size()) {
728 template_f.open(args[++argidx]);
729 if (template_f.fail())
730 log_error("Can't open template file `%s'.\n", args[argidx].c_str());
731 continue;
732 }
733 if (args[argidx] == "-bv") {
734 bvmode = true;
735 continue;
736 }
737 if (args[argidx] == "-mem") {
738 bvmode = true;
739 memmode = true;
740 continue;
741 }
742 if (args[argidx] == "-verbose") {
743 verbose = true;
744 continue;
745 }
746 break;
747 }
748 extra_args(f, filename, args, argidx);
749
750 if (template_f.is_open()) {
751 std::string line;
752 while (std::getline(template_f, line)) {
753 int indent = 0;
754 while (indent < GetSize(line) && (line[indent] == ' ' || line[indent] == '\t'))
755 indent++;
756 if (line.substr(indent, 2) == "%%")
757 break;
758 *f << line << std::endl;
759 }
760 }
761
762 *f << stringf("; SMT-LIBv2 description generated by %s\n", yosys_version_str);
763
764 for (auto module : design->modules())
765 {
766 if (module->get_bool_attribute("\\blackbox") || module->has_memories_warn() || module->has_processes_warn())
767 continue;
768
769 log("Creating SMT-LIBv2 representation of module %s.\n", log_id(module));
770
771 Smt2Worker worker(module, bvmode, memmode, verbose);
772 worker.run();
773 worker.write(*f);
774 }
775
776 *f << stringf("; end of yosys output\n");
777
778 if (template_f.is_open()) {
779 std::string line;
780 while (std::getline(template_f, line))
781 *f << line << std::endl;
782 }
783 }
784 } Smt2Backend;
785
786 PRIVATE_NAMESPACE_END