16ec88fe01e4532512772d9f9e086df2ab682d45
[yosys.git] / passes / sat / sat.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 // [[CITE]] Temporal Induction by Incremental SAT Solving
21 // Niklas Een and Niklas Sörensson (2003)
22 // http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.8161
23
24 #include "kernel/register.h"
25 #include "kernel/celltypes.h"
26 #include "kernel/consteval.h"
27 #include "kernel/sigtools.h"
28 #include "kernel/log.h"
29 #include "kernel/satgen.h"
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <algorithm>
33 #include <errno.h>
34 #include <string.h>
35
36 USING_YOSYS_NAMESPACE
37 PRIVATE_NAMESPACE_BEGIN
38
39 struct SatHelper
40 {
41 RTLIL::Design *design;
42 RTLIL::Module *module;
43
44 SigMap sigmap;
45 CellTypes ct;
46
47 ezSatPtr ez;
48 SatGen satgen;
49
50 // additional constraints
51 std::vector<std::pair<std::string, std::string>> sets, prove, prove_x, sets_init;
52 std::map<int, std::vector<std::pair<std::string, std::string>>> sets_at;
53 std::map<int, std::vector<std::string>> unsets_at;
54 bool prove_asserts, set_assumes;
55
56 // undef constraints
57 bool enable_undef, set_init_def, set_init_undef, set_init_zero, ignore_unknown_cells;
58 std::vector<std::string> sets_def, sets_any_undef, sets_all_undef;
59 std::map<int, std::vector<std::string>> sets_def_at, sets_any_undef_at, sets_all_undef_at;
60
61 // model variables
62 std::vector<std::string> shows;
63 SigPool show_signal_pool;
64 SigSet<RTLIL::Cell*> show_drivers;
65 int max_timestep, timeout;
66 bool gotTimeout;
67
68 SatHelper(RTLIL::Design *design, RTLIL::Module *module, bool enable_undef) :
69 design(design), module(module), sigmap(module), ct(design), satgen(ez.get(), &sigmap)
70 {
71 this->enable_undef = enable_undef;
72 satgen.model_undef = enable_undef;
73 set_init_def = false;
74 set_init_undef = false;
75 set_init_zero = false;
76 ignore_unknown_cells = false;
77 max_timestep = -1;
78 timeout = 0;
79 gotTimeout = false;
80 }
81
82 void check_undef_enabled(const RTLIL::SigSpec &sig)
83 {
84 if (enable_undef)
85 return;
86
87 std::vector<RTLIL::SigBit> sigbits = sig.to_sigbit_vector();
88 for (size_t i = 0; i < sigbits.size(); i++)
89 if (sigbits[i].wire == NULL && sigbits[i].data == RTLIL::State::Sx)
90 log_cmd_error("Bit %d of %s is undef but option -enable_undef is missing!\n", int(i), log_signal(sig));
91 }
92
93 void setup_init()
94 {
95 log ("\nSetting up initial state:\n");
96
97 RTLIL::SigSpec big_lhs, big_rhs;
98
99 for (auto &it : module->wires_)
100 {
101 if (it.second->attributes.count("\\init") == 0)
102 continue;
103
104 RTLIL::SigSpec lhs = sigmap(it.second);
105 RTLIL::SigSpec rhs = it.second->attributes.at("\\init");
106 log_assert(lhs.size() == rhs.size());
107
108 RTLIL::SigSpec removed_bits;
109 for (int i = 0; i < lhs.size(); i++) {
110 RTLIL::SigSpec bit = lhs.extract(i, 1);
111 if (!satgen.initial_state.check_all(bit)) {
112 removed_bits.append(bit);
113 lhs.remove(i, 1);
114 rhs.remove(i, 1);
115 i--;
116 }
117 }
118
119 if (removed_bits.size())
120 log_warning("ignoring initial value on non-register: %s\n", log_signal(removed_bits));
121
122 if (lhs.size()) {
123 log("Import set-constraint from init attribute: %s = %s\n", log_signal(lhs), log_signal(rhs));
124 big_lhs.remove2(lhs, &big_rhs);
125 big_lhs.append(lhs);
126 big_rhs.append(rhs);
127 }
128 }
129
130 for (auto &s : sets_init)
131 {
132 RTLIL::SigSpec lhs, rhs;
133
134 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
135 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
136 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
137 log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
138 show_signal_pool.add(sigmap(lhs));
139 show_signal_pool.add(sigmap(rhs));
140
141 if (lhs.size() != rhs.size())
142 log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
143 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
144
145 log("Import set-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
146 big_lhs.remove2(lhs, &big_rhs);
147 big_lhs.append(lhs);
148 big_rhs.append(rhs);
149 }
150
151 if (!satgen.initial_state.check_all(big_lhs)) {
152 RTLIL::SigSpec rem = satgen.initial_state.remove(big_lhs);
153 log_cmd_error("Found -set-init bits that are not part of the initial_state: %s\n", log_signal(rem));
154 }
155
156 if (set_init_def) {
157 RTLIL::SigSpec rem = satgen.initial_state.export_all();
158 std::vector<int> undef_rem = satgen.importUndefSigSpec(rem, 1);
159 ez->assume(ez->NOT(ez->expression(ezSAT::OpOr, undef_rem)));
160 }
161
162 if (set_init_undef) {
163 RTLIL::SigSpec rem = satgen.initial_state.export_all();
164 rem.remove(big_lhs);
165 big_lhs.append(rem);
166 big_rhs.append(RTLIL::SigSpec(RTLIL::State::Sx, rem.size()));
167 }
168
169 if (set_init_zero) {
170 RTLIL::SigSpec rem = satgen.initial_state.export_all();
171 rem.remove(big_lhs);
172 big_lhs.append(rem);
173 big_rhs.append(RTLIL::SigSpec(RTLIL::State::S0, rem.size()));
174 }
175
176 if (big_lhs.size() == 0) {
177 log("No constraints for initial state found.\n\n");
178 return;
179 }
180
181 log("Final constraint equation: %s = %s\n\n", log_signal(big_lhs), log_signal(big_rhs));
182 check_undef_enabled(big_lhs), check_undef_enabled(big_rhs);
183 ez->assume(satgen.signals_eq(big_lhs, big_rhs, 1));
184 }
185
186 void setup(int timestep = -1)
187 {
188 if (timestep > 0)
189 log ("\nSetting up time step %d:\n", timestep);
190 else
191 log ("\nSetting up SAT problem:\n");
192
193 if (timestep > max_timestep)
194 max_timestep = timestep;
195
196 RTLIL::SigSpec big_lhs, big_rhs;
197
198 for (auto &s : sets)
199 {
200 RTLIL::SigSpec lhs, rhs;
201
202 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
203 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
204 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
205 log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
206 show_signal_pool.add(sigmap(lhs));
207 show_signal_pool.add(sigmap(rhs));
208
209 if (lhs.size() != rhs.size())
210 log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
211 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
212
213 log("Import set-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
214 big_lhs.remove2(lhs, &big_rhs);
215 big_lhs.append(lhs);
216 big_rhs.append(rhs);
217 }
218
219 for (auto &s : sets_at[timestep])
220 {
221 RTLIL::SigSpec lhs, rhs;
222
223 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
224 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
225 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
226 log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
227 show_signal_pool.add(sigmap(lhs));
228 show_signal_pool.add(sigmap(rhs));
229
230 if (lhs.size() != rhs.size())
231 log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
232 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
233
234 log("Import set-constraint for this timestep: %s = %s\n", log_signal(lhs), log_signal(rhs));
235 big_lhs.remove2(lhs, &big_rhs);
236 big_lhs.append(lhs);
237 big_rhs.append(rhs);
238 }
239
240 for (auto &s : unsets_at[timestep])
241 {
242 RTLIL::SigSpec lhs;
243
244 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s))
245 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.c_str());
246 show_signal_pool.add(sigmap(lhs));
247
248 log("Import unset-constraint for this timestep: %s\n", log_signal(lhs));
249 big_lhs.remove2(lhs, &big_rhs);
250 }
251
252 log("Final constraint equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
253 check_undef_enabled(big_lhs), check_undef_enabled(big_rhs);
254 ez->assume(satgen.signals_eq(big_lhs, big_rhs, timestep));
255
256 // 0 = sets_def
257 // 1 = sets_any_undef
258 // 2 = sets_all_undef
259 std::set<RTLIL::SigSpec> sets_def_undef[3];
260
261 for (auto &s : sets_def) {
262 RTLIL::SigSpec sig;
263 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
264 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
265 sets_def_undef[0].insert(sig);
266 }
267
268 for (auto &s : sets_any_undef) {
269 RTLIL::SigSpec sig;
270 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
271 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
272 sets_def_undef[1].insert(sig);
273 }
274
275 for (auto &s : sets_all_undef) {
276 RTLIL::SigSpec sig;
277 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
278 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
279 sets_def_undef[2].insert(sig);
280 }
281
282 for (auto &s : sets_def_at[timestep]) {
283 RTLIL::SigSpec sig;
284 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
285 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
286 sets_def_undef[0].insert(sig);
287 sets_def_undef[1].erase(sig);
288 sets_def_undef[2].erase(sig);
289 }
290
291 for (auto &s : sets_any_undef_at[timestep]) {
292 RTLIL::SigSpec sig;
293 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
294 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
295 sets_def_undef[0].erase(sig);
296 sets_def_undef[1].insert(sig);
297 sets_def_undef[2].erase(sig);
298 }
299
300 for (auto &s : sets_all_undef_at[timestep]) {
301 RTLIL::SigSpec sig;
302 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
303 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
304 sets_def_undef[0].erase(sig);
305 sets_def_undef[1].erase(sig);
306 sets_def_undef[2].insert(sig);
307 }
308
309 for (int t = 0; t < 3; t++)
310 for (auto &sig : sets_def_undef[t]) {
311 log("Import %s constraint for this timestep: %s\n", t == 0 ? "def" : t == 1 ? "any_undef" : "all_undef", log_signal(sig));
312 std::vector<int> undef_sig = satgen.importUndefSigSpec(sig, timestep);
313 if (t == 0)
314 ez->assume(ez->NOT(ez->expression(ezSAT::OpOr, undef_sig)));
315 if (t == 1)
316 ez->assume(ez->expression(ezSAT::OpOr, undef_sig));
317 if (t == 2)
318 ez->assume(ez->expression(ezSAT::OpAnd, undef_sig));
319 }
320
321 int import_cell_counter = 0;
322 for (auto cell : module->cells())
323 if (design->selected(module, cell)) {
324 // log("Import cell: %s\n", RTLIL::id2cstr(cell->name));
325 if (satgen.importCell(cell, timestep)) {
326 for (auto &p : cell->connections())
327 if (ct.cell_output(cell->type, p.first))
328 show_drivers.insert(sigmap(p.second), cell);
329 import_cell_counter++;
330 } else if (ignore_unknown_cells)
331 log_warning("Failed to import cell %s (type %s) to SAT database.\n", RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
332 else
333 log_error("Failed to import cell %s (type %s) to SAT database.\n", RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
334 }
335 log("Imported %d cells to SAT database.\n", import_cell_counter);
336
337 if (set_assumes) {
338 RTLIL::SigSpec assumes_a, assumes_en;
339 satgen.getAssumes(assumes_a, assumes_en, timestep);
340 for (int i = 0; i < GetSize(assumes_a); i++)
341 log("Import constraint from assume cell: %s when %s.\n", log_signal(assumes_a[i]), log_signal(assumes_en[i]));
342 ez->assume(satgen.importAssumes(timestep));
343 }
344 }
345
346 int setup_proof(int timestep = -1)
347 {
348 log_assert(prove.size() || prove_x.size() || prove_asserts);
349
350 RTLIL::SigSpec big_lhs, big_rhs;
351 std::vector<int> prove_bits;
352
353 if (prove.size() > 0)
354 {
355 for (auto &s : prove)
356 {
357 RTLIL::SigSpec lhs, rhs;
358
359 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
360 log_cmd_error("Failed to parse lhs proof expression `%s'.\n", s.first.c_str());
361 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
362 log_cmd_error("Failed to parse rhs proof expression `%s'.\n", s.second.c_str());
363 show_signal_pool.add(sigmap(lhs));
364 show_signal_pool.add(sigmap(rhs));
365
366 if (lhs.size() != rhs.size())
367 log_cmd_error("Proof expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
368 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
369
370 log("Import proof-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
371 big_lhs.remove2(lhs, &big_rhs);
372 big_lhs.append(lhs);
373 big_rhs.append(rhs);
374 }
375
376 log("Final proof equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
377 check_undef_enabled(big_lhs), check_undef_enabled(big_rhs);
378 prove_bits.push_back(satgen.signals_eq(big_lhs, big_rhs, timestep));
379 }
380
381 if (prove_x.size() > 0)
382 {
383 for (auto &s : prove_x)
384 {
385 RTLIL::SigSpec lhs, rhs;
386
387 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
388 log_cmd_error("Failed to parse lhs proof-x expression `%s'.\n", s.first.c_str());
389 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
390 log_cmd_error("Failed to parse rhs proof-x expression `%s'.\n", s.second.c_str());
391 show_signal_pool.add(sigmap(lhs));
392 show_signal_pool.add(sigmap(rhs));
393
394 if (lhs.size() != rhs.size())
395 log_cmd_error("Proof-x expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
396 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
397
398 log("Import proof-x-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
399 big_lhs.remove2(lhs, &big_rhs);
400 big_lhs.append(lhs);
401 big_rhs.append(rhs);
402 }
403
404 log("Final proof-x equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
405
406 std::vector<int> value_lhs = satgen.importDefSigSpec(big_lhs, timestep);
407 std::vector<int> value_rhs = satgen.importDefSigSpec(big_rhs, timestep);
408
409 std::vector<int> undef_lhs = satgen.importUndefSigSpec(big_lhs, timestep);
410 std::vector<int> undef_rhs = satgen.importUndefSigSpec(big_rhs, timestep);
411
412 for (size_t i = 0; i < value_lhs.size(); i++)
413 prove_bits.push_back(ez->OR(undef_lhs.at(i), ez->AND(ez->NOT(undef_rhs.at(i)), ez->NOT(ez->XOR(value_lhs.at(i), value_rhs.at(i))))));
414 }
415
416 if (prove_asserts) {
417 RTLIL::SigSpec asserts_a, asserts_en;
418 satgen.getAsserts(asserts_a, asserts_en, timestep);
419 for (int i = 0; i < GetSize(asserts_a); i++)
420 log("Import proof for assert: %s when %s.\n", log_signal(asserts_a[i]), log_signal(asserts_en[i]));
421 prove_bits.push_back(satgen.importAsserts(timestep));
422 }
423
424 return ez->expression(ezSAT::OpAnd, prove_bits);
425 }
426
427 void force_unique_state(int timestep_from, int timestep_to)
428 {
429 RTLIL::SigSpec state_signals = satgen.initial_state.export_all();
430 for (int i = timestep_from; i < timestep_to; i++)
431 ez->assume(ez->NOT(satgen.signals_eq(state_signals, state_signals, i, timestep_to)));
432 }
433
434 bool solve(const std::vector<int> &assumptions)
435 {
436 log_assert(gotTimeout == false);
437 ez->setSolverTimeout(timeout);
438 bool success = ez->solve(modelExpressions, modelValues, assumptions);
439 if (ez->getSolverTimoutStatus())
440 gotTimeout = true;
441 return success;
442 }
443
444 bool solve(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0, int f = 0)
445 {
446 log_assert(gotTimeout == false);
447 ez->setSolverTimeout(timeout);
448 bool success = ez->solve(modelExpressions, modelValues, a, b, c, d, e, f);
449 if (ez->getSolverTimoutStatus())
450 gotTimeout = true;
451 return success;
452 }
453
454 struct ModelBlockInfo {
455 int timestep, offset, width;
456 std::string description;
457 bool operator < (const ModelBlockInfo &other) const {
458 if (timestep != other.timestep)
459 return timestep < other.timestep;
460 if (description != other.description)
461 return description < other.description;
462 if (offset != other.offset)
463 return offset < other.offset;
464 if (width != other.width)
465 return width < other.width;
466 return false;
467 }
468 };
469
470 std::vector<int> modelExpressions;
471 std::vector<bool> modelValues;
472 std::set<ModelBlockInfo> modelInfo;
473
474 void maximize_undefs()
475 {
476 log_assert(enable_undef);
477 std::vector<bool> backupValues;
478
479 while (1)
480 {
481 std::vector<int> must_undef, maybe_undef;
482
483 for (size_t i = 0; i < modelExpressions.size()/2; i++)
484 if (modelValues.at(modelExpressions.size()/2 + i))
485 must_undef.push_back(modelExpressions.at(modelExpressions.size()/2 + i));
486 else
487 maybe_undef.push_back(modelExpressions.at(modelExpressions.size()/2 + i));
488
489 backupValues.swap(modelValues);
490 if (!solve(ez->expression(ezSAT::OpAnd, must_undef), ez->expression(ezSAT::OpOr, maybe_undef)))
491 break;
492 }
493
494 backupValues.swap(modelValues);
495 }
496
497 void generate_model()
498 {
499 RTLIL::SigSpec modelSig;
500 modelExpressions.clear();
501 modelInfo.clear();
502
503 // Add "show" signals or alternatively the leaves on the input cone on all set and prove signals
504
505 if (shows.size() == 0)
506 {
507 SigPool queued_signals, handled_signals, final_signals;
508 queued_signals = show_signal_pool;
509 while (queued_signals.size() > 0) {
510 RTLIL::SigSpec sig = queued_signals.export_one();
511 queued_signals.del(sig);
512 handled_signals.add(sig);
513 std::set<RTLIL::Cell*> drivers = show_drivers.find(sig);
514 if (drivers.size() == 0) {
515 final_signals.add(sig);
516 } else {
517 for (auto &d : drivers)
518 for (auto &p : d->connections()) {
519 if (d->type == "$dff" && p.first == "\\CLK")
520 continue;
521 if (d->type.substr(0, 6) == "$_DFF_" && p.first == "\\C")
522 continue;
523 queued_signals.add(handled_signals.remove(sigmap(p.second)));
524 }
525 }
526 }
527 modelSig = final_signals.export_all();
528
529 // additionally add all set and prove signals directly
530 // (it improves user confidence if we write the constraints back ;-)
531 modelSig.append(show_signal_pool.export_all());
532 }
533 else
534 {
535 for (auto &s : shows) {
536 RTLIL::SigSpec sig;
537 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
538 log_cmd_error("Failed to parse show expression `%s'.\n", s.c_str());
539 log("Import show expression: %s\n", log_signal(sig));
540 modelSig.append(sig);
541 }
542 }
543
544 modelSig.sort_and_unify();
545 // log("Model signals: %s\n", log_signal(modelSig));
546
547 std::vector<int> modelUndefExpressions;
548
549 for (auto &c : modelSig.chunks())
550 if (c.wire != NULL)
551 {
552 ModelBlockInfo info;
553 RTLIL::SigSpec chunksig = c;
554 info.width = chunksig.size();
555 info.description = log_signal(chunksig);
556
557 for (int timestep = -1; timestep <= max_timestep; timestep++)
558 {
559 if ((timestep == -1 && max_timestep > 0) || timestep == 0)
560 continue;
561
562 info.timestep = timestep;
563 info.offset = modelExpressions.size();
564 modelInfo.insert(info);
565
566 std::vector<int> vec = satgen.importSigSpec(chunksig, timestep);
567 modelExpressions.insert(modelExpressions.end(), vec.begin(), vec.end());
568
569 if (enable_undef) {
570 std::vector<int> undef_vec = satgen.importUndefSigSpec(chunksig, timestep);
571 modelUndefExpressions.insert(modelUndefExpressions.end(), undef_vec.begin(), undef_vec.end());
572 }
573 }
574 }
575
576 // Add initial state signals as collected by satgen
577 //
578 modelSig = satgen.initial_state.export_all();
579 for (auto &c : modelSig.chunks())
580 if (c.wire != NULL)
581 {
582 ModelBlockInfo info;
583 RTLIL::SigSpec chunksig = c;
584
585 info.timestep = 0;
586 info.offset = modelExpressions.size();
587 info.width = chunksig.size();
588 info.description = log_signal(chunksig);
589 modelInfo.insert(info);
590
591 std::vector<int> vec = satgen.importSigSpec(chunksig, 1);
592 modelExpressions.insert(modelExpressions.end(), vec.begin(), vec.end());
593
594 if (enable_undef) {
595 std::vector<int> undef_vec = satgen.importUndefSigSpec(chunksig, 1);
596 modelUndefExpressions.insert(modelUndefExpressions.end(), undef_vec.begin(), undef_vec.end());
597 }
598 }
599
600 modelExpressions.insert(modelExpressions.end(), modelUndefExpressions.begin(), modelUndefExpressions.end());
601 }
602
603 void print_model()
604 {
605 int maxModelName = 10;
606 int maxModelWidth = 10;
607
608 for (auto &info : modelInfo) {
609 maxModelName = std::max(maxModelName, int(info.description.size()));
610 maxModelWidth = std::max(maxModelWidth, info.width);
611 }
612
613 log("\n");
614
615 int last_timestep = -2;
616 for (auto &info : modelInfo)
617 {
618 RTLIL::Const value;
619 bool found_undef = false;
620
621 for (int i = 0; i < info.width; i++) {
622 value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
623 if (enable_undef && modelValues.at(modelExpressions.size()/2 + info.offset + i))
624 value.bits.back() = RTLIL::State::Sx, found_undef = true;
625 }
626
627 if (info.timestep != last_timestep) {
628 const char *hline = "---------------------------------------------------------------------------------------------------"
629 "---------------------------------------------------------------------------------------------------"
630 "---------------------------------------------------------------------------------------------------";
631 if (last_timestep == -2) {
632 log(max_timestep > 0 ? " Time " : " ");
633 log("%-*s %10s %10s %*s\n", maxModelName+10, "Signal Name", "Dec", "Hex", maxModelWidth+5, "Bin");
634 }
635 log(max_timestep > 0 ? " ---- " : " ");
636 log("%*.*s %10.10s %10.10s %*.*s\n", maxModelName+10, maxModelName+10,
637 hline, hline, hline, maxModelWidth+5, maxModelWidth+5, hline);
638 last_timestep = info.timestep;
639 }
640
641 if (max_timestep > 0) {
642 if (info.timestep > 0)
643 log(" %4d ", info.timestep);
644 else
645 log(" init ");
646 } else
647 log(" ");
648
649 if (info.width <= 32 && !found_undef)
650 log("%-*s %10d %10x %*s\n", maxModelName+10, info.description.c_str(), value.as_int(), value.as_int(), maxModelWidth+5, value.as_string().c_str());
651 else
652 log("%-*s %10s %10s %*s\n", maxModelName+10, info.description.c_str(), "--", "--", maxModelWidth+5, value.as_string().c_str());
653 }
654
655 if (last_timestep == -2)
656 log(" no model variables selected for display.\n");
657 }
658
659 void dump_model_to_vcd(std::string vcd_file_name)
660 {
661 FILE *f = fopen(vcd_file_name.c_str(), "w");
662 if (!f)
663 log_cmd_error("Can't open output file `%s' for writing: %s\n", vcd_file_name.c_str(), strerror(errno));
664
665 log("Dumping SAT model to VCD file %s\n", vcd_file_name.c_str());
666
667 time_t timestamp;
668 struct tm* now;
669 char stime[128] = {};
670 time(&timestamp);
671 now = localtime(&timestamp);
672 strftime(stime, sizeof(stime), "%c", now);
673
674 std::string module_fname = "unknown";
675 auto apos = module->attributes.find("\\src");
676 if(apos != module->attributes.end())
677 module_fname = module->attributes["\\src"].decode_string();
678
679 fprintf(f, "$date\n");
680 fprintf(f, " %s\n", stime);
681 fprintf(f, "$end\n");
682 fprintf(f, "$version\n");
683 fprintf(f, " Generated by %s\n", yosys_version_str);
684 fprintf(f, "$end\n");
685 fprintf(f, "$comment\n");
686 fprintf(f, " Generated from SAT problem in module %s (declared at %s)\n",
687 module->name.c_str(), module_fname.c_str());
688 fprintf(f, "$end\n");
689
690 // VCD has some limits on internal (non-display) identifier names, so make legal ones
691 std::map<std::string, std::string> vcdnames;
692
693 fprintf(f, "$timescale 1ns\n"); // arbitrary time scale since actual clock period is unknown/unimportant
694 fprintf(f, "$scope module %s $end\n", module->name.c_str());
695 for (auto &info : modelInfo)
696 {
697 if (vcdnames.find(info.description) != vcdnames.end())
698 continue;
699
700 char namebuf[16];
701 snprintf(namebuf, sizeof(namebuf), "v%d", static_cast<int>(vcdnames.size()));
702 vcdnames[info.description] = namebuf;
703
704 // Even display identifiers can't use some special characters
705 std::string legal_desc = info.description.c_str();
706 for (auto &c : legal_desc) {
707 if(c == '$')
708 c = '_';
709 if(c == ':')
710 c = '_';
711 }
712
713 fprintf(f, "$var wire %d %s %s $end\n", info.width, namebuf, legal_desc.c_str());
714
715 // Need to look at first *two* cycles!
716 // We need to put a name on all variables but those without an initialization clause
717 // have no value at timestep 0
718 if(info.timestep > 1)
719 break;
720 }
721 fprintf(f, "$upscope $end\n");
722 fprintf(f, "$enddefinitions $end\n");
723 fprintf(f, "$dumpvars\n");
724
725 static const char bitvals[] = "01xzxx";
726
727 int last_timestep = -2;
728 for (auto &info : modelInfo)
729 {
730 RTLIL::Const value;
731
732 for (int i = 0; i < info.width; i++) {
733 value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
734 if (enable_undef && modelValues.at(modelExpressions.size()/2 + info.offset + i))
735 value.bits.back() = RTLIL::State::Sx;
736 }
737
738 if (info.timestep != last_timestep) {
739 if(last_timestep == 0)
740 fprintf(f, "$end\n");
741 else
742 fprintf(f, "#%d\n", info.timestep);
743 last_timestep = info.timestep;
744 }
745
746 if(info.width == 1) {
747 fprintf(f, "%c%s\n", bitvals[value.bits[0]], vcdnames[info.description].c_str());
748 } else {
749 fprintf(f, "b");
750 for(int k=info.width-1; k >= 0; k --) //need to flip bit ordering for VCD
751 fprintf(f, "%c", bitvals[value.bits[k]]);
752 fprintf(f, " %s\n", vcdnames[info.description].c_str());
753 }
754 }
755
756 if (last_timestep == -2)
757 log(" no model variables selected for display.\n");
758
759 fclose(f);
760 }
761
762 void dump_model_to_json(std::string json_file_name)
763 {
764 FILE *f = fopen(json_file_name.c_str(), "w");
765 if (!f)
766 log_cmd_error("Can't open output file `%s' for writing: %s\n", json_file_name.c_str(), strerror(errno));
767
768 log("Dumping SAT model to WaveJSON file '%s'.\n", json_file_name.c_str());
769
770 int mintime = 1, maxtime = 0, maxwidth = 0;;
771 dict<string, pair<int, dict<int, Const>>> wavedata;
772
773 for (auto &info : modelInfo)
774 {
775 Const value;
776 for (int i = 0; i < info.width; i++) {
777 value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
778 if (enable_undef && modelValues.at(modelExpressions.size()/2 + info.offset + i))
779 value.bits.back() = RTLIL::State::Sx;
780 }
781
782 wavedata[info.description].first = info.width;
783 wavedata[info.description].second[info.timestep] = value;
784 mintime = std::min(mintime, info.timestep);
785 maxtime = std::max(maxtime, info.timestep);
786 maxwidth = std::max(maxwidth, info.width);
787 }
788
789 fprintf(f, "{ \"signal\": [");
790 bool fist_wavedata = true;
791 for (auto &wd : wavedata)
792 {
793 fprintf(f, "%s", fist_wavedata ? "\n" : ",\n");
794 fist_wavedata = false;
795
796 vector<string> data;
797 string name = wd.first.c_str();
798 while (name.substr(0, 1) == "\\")
799 name = name.substr(1);
800
801 fprintf(f, " { \"name\": \"%s\", \"wave\": \"", name.c_str());
802 for (int i = mintime; i <= maxtime; i++) {
803 if (wd.second.second.count(i)) {
804 string this_data = wd.second.second[i].as_string();
805 char ch = '=';
806 if (wd.second.first == 1)
807 ch = this_data[0];
808 if (!data.empty() && data.back() == this_data) {
809 fprintf(f, ".");
810 } else {
811 data.push_back(this_data);
812 fprintf(f, "%c", ch);
813 }
814 } else {
815 data.push_back("");
816 fprintf(f, "4");
817 }
818 }
819 if (wd.second.first != 1) {
820 fprintf(f, "\", \"data\": [");
821 for (int i = 0; i < GetSize(data); i++)
822 fprintf(f, "%s\"%s\"", i ? ", " : "", data[i].c_str());
823 fprintf(f, "] }");
824 } else {
825 fprintf(f, "\" }");
826 }
827 }
828 fprintf(f, "\n ],\n");
829 fprintf(f, " \"config\": {\n");
830 fprintf(f, " \"hscale\": %.2f\n", maxwidth / 4.0);
831 fprintf(f, " }\n");
832 fprintf(f, "}\n");
833 fclose(f);
834 }
835
836 void invalidate_model(bool max_undef)
837 {
838 std::vector<int> clause;
839 if (enable_undef) {
840 for (size_t i = 0; i < modelExpressions.size()/2; i++) {
841 int bit = modelExpressions.at(i), bit_undef = modelExpressions.at(modelExpressions.size()/2 + i);
842 bool val = modelValues.at(i), val_undef = modelValues.at(modelExpressions.size()/2 + i);
843 if (!max_undef || !val_undef)
844 clause.push_back(val_undef ? ez->NOT(bit_undef) : val ? ez->NOT(bit) : bit);
845 }
846 } else
847 for (size_t i = 0; i < modelExpressions.size(); i++)
848 clause.push_back(modelValues.at(i) ? ez->NOT(modelExpressions.at(i)) : modelExpressions.at(i));
849 ez->assume(ez->expression(ezSAT::OpOr, clause));
850 }
851 };
852
853 void print_proof_failed()
854 {
855 log("\n");
856 log(" ______ ___ ___ _ _ _ _ \n");
857 log(" (_____ \\ / __) / __) (_) | | | |\n");
858 log(" _____) )___ ___ ___ _| |__ _| |__ _____ _| | _____ __| | |\n");
859 log(" | ____/ ___) _ \\ / _ (_ __) (_ __|____ | | || ___ |/ _ |_|\n");
860 log(" | | | | | |_| | |_| || | | | / ___ | | || ____( (_| |_ \n");
861 log(" |_| |_| \\___/ \\___/ |_| |_| \\_____|_|\\_)_____)\\____|_|\n");
862 log("\n");
863 }
864
865 void print_timeout()
866 {
867 log("\n");
868 log(" _____ _ _ _____ ____ _ _____\n");
869 log(" /__ __\\/ \\/ \\__/|/ __// _ \\/ \\ /\\/__ __\\\n");
870 log(" / \\ | || |\\/||| \\ | / \\|| | || / \\\n");
871 log(" | | | || | ||| /_ | \\_/|| \\_/| | |\n");
872 log(" \\_/ \\_/\\_/ \\|\\____\\\\____/\\____/ \\_/\n");
873 log("\n");
874 }
875
876 void print_qed()
877 {
878 log("\n");
879 log(" /$$$$$$ /$$$$$$$$ /$$$$$$$ \n");
880 log(" /$$__ $$ | $$_____/ | $$__ $$ \n");
881 log(" | $$ \\ $$ | $$ | $$ \\ $$ \n");
882 log(" | $$ | $$ | $$$$$ | $$ | $$ \n");
883 log(" | $$ | $$ | $$__/ | $$ | $$ \n");
884 log(" | $$/$$ $$ | $$ | $$ | $$ \n");
885 log(" | $$$$$$/ /$$| $$$$$$$$ /$$| $$$$$$$//$$\n");
886 log(" \\____ $$$|__/|________/|__/|_______/|__/\n");
887 log(" \\__/ \n");
888 log("\n");
889 }
890
891 struct SatPass : public Pass {
892 SatPass() : Pass("sat", "solve a SAT problem in the circuit") { }
893 virtual void help()
894 {
895 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
896 log("\n");
897 log(" sat [options] [selection]\n");
898 log("\n");
899 log("This command solves a SAT problem defined over the currently selected circuit\n");
900 log("and additional constraints passed as parameters.\n");
901 log("\n");
902 log(" -all\n");
903 log(" show all solutions to the problem (this can grow exponentially, use\n");
904 log(" -max <N> instead to get <N> solutions)\n");
905 log("\n");
906 log(" -max <N>\n");
907 log(" like -all, but limit number of solutions to <N>\n");
908 log("\n");
909 log(" -enable_undef\n");
910 log(" enable modeling of undef value (aka 'x-bits')\n");
911 log(" this option is implied by -set-def, -set-undef et. cetera\n");
912 log("\n");
913 log(" -max_undef\n");
914 log(" maximize the number of undef bits in solutions, giving a better\n");
915 log(" picture of which input bits are actually vital to the solution.\n");
916 log("\n");
917 log(" -set <signal> <value>\n");
918 log(" set the specified signal to the specified value.\n");
919 log("\n");
920 log(" -set-def <signal>\n");
921 log(" add a constraint that all bits of the given signal must be defined\n");
922 log("\n");
923 log(" -set-any-undef <signal>\n");
924 log(" add a constraint that at least one bit of the given signal is undefined\n");
925 log("\n");
926 log(" -set-all-undef <signal>\n");
927 log(" add a constraint that all bits of the given signal are undefined\n");
928 log("\n");
929 log(" -set-def-inputs\n");
930 log(" add -set-def constraints for all module inputs\n");
931 log("\n");
932 log(" -show <signal>\n");
933 log(" show the model for the specified signal. if no -show option is\n");
934 log(" passed then a set of signals to be shown is automatically selected.\n");
935 log("\n");
936 log(" -show-inputs, -show-outputs, -show-ports\n");
937 log(" add all module (input/output) ports to the list of shown signals\n");
938 log("\n");
939 log(" -ignore_div_by_zero\n");
940 log(" ignore all solutions that involve a division by zero\n");
941 log("\n");
942 log(" -ignore_unknown_cells\n");
943 log(" ignore all cells that can not be matched to a SAT model\n");
944 log("\n");
945 log("The following options can be used to set up a sequential problem:\n");
946 log("\n");
947 log(" -seq <N>\n");
948 log(" set up a sequential problem with <N> time steps. The steps will\n");
949 log(" be numbered from 1 to N.\n");
950 log("\n");
951 log(" note: for large <N> it can be significantly faster to use\n");
952 log(" -tempinduct-baseonly -maxsteps <N> instead of -seq <N>.\n");
953 log("\n");
954 log(" -set-at <N> <signal> <value>\n");
955 log(" -unset-at <N> <signal>\n");
956 log(" set or unset the specified signal to the specified value in the\n");
957 log(" given timestep. this has priority over a -set for the same signal.\n");
958 log("\n");
959 log(" -set-assumes\n");
960 log(" set all assumptions provided via $assume cells\n");
961 log("\n");
962 log(" -set-def-at <N> <signal>\n");
963 log(" -set-any-undef-at <N> <signal>\n");
964 log(" -set-all-undef-at <N> <signal>\n");
965 log(" add undef constraints in the given timestep.\n");
966 log("\n");
967 log(" -set-init <signal> <value>\n");
968 log(" set the initial value for the register driving the signal to the value\n");
969 log("\n");
970 log(" -set-init-undef\n");
971 log(" set all initial states (not set using -set-init) to undef\n");
972 log("\n");
973 log(" -set-init-def\n");
974 log(" do not force a value for the initial state but do not allow undef\n");
975 log("\n");
976 log(" -set-init-zero\n");
977 log(" set all initial states (not set using -set-init) to zero\n");
978 log("\n");
979 log(" -dump_vcd <vcd-file-name>\n");
980 log(" dump SAT model (counter example in proof) to VCD file\n");
981 log("\n");
982 log(" -dump_json <json-file-name>\n");
983 log(" dump SAT model (counter example in proof) to a WaveJSON file.\n");
984 log("\n");
985 log(" -dump_cnf <cnf-file-name>\n");
986 log(" dump CNF of SAT problem (in DIMACS format). in temporal induction\n");
987 log(" proofs this is the CNF of the first induction step.\n");
988 log("\n");
989 log("The following additional options can be used to set up a proof. If also -seq\n");
990 log("is passed, a temporal induction proof is performed.\n");
991 log("\n");
992 log(" -tempinduct\n");
993 log(" Perform a temporal induction proof. In a temporalinduction proof it is\n");
994 log(" proven that the condition holds forever after the number of time steps\n");
995 log(" specified using -seq.\n");
996 log("\n");
997 log(" -tempinduct-def\n");
998 log(" Perform a temporal induction proof. Assume an initial state with all\n");
999 log(" registers set to defined values for the induction step.\n");
1000 log("\n");
1001 log(" -tempinduct-baseonly\n");
1002 log(" Run only the basecase half of temporal induction (requires -maxsteps)\n");
1003 log("\n");
1004 log(" -tempinduct-inductonly\n");
1005 log(" Run only the induction half of temporal induction\n");
1006 log("\n");
1007 log(" -tempinduct-skip <N>\n");
1008 log(" Skip the first <N> steps of the induction proof.\n");
1009 log("\n");
1010 log(" note: this will assume that the base case holds for <N> steps.\n");
1011 log(" this must be proven independently with \"-tempinduct-baseonly\n");
1012 log(" -maxsteps <N>\". Use -initsteps if you just want to set a\n");
1013 log(" minimal induction length.\n");
1014 log("\n");
1015 log(" -prove <signal> <value>\n");
1016 log(" Attempt to proof that <signal> is always <value>.\n");
1017 log("\n");
1018 log(" -prove-x <signal> <value>\n");
1019 log(" Like -prove, but an undef (x) bit in the lhs matches any value on\n");
1020 log(" the right hand side. Useful for equivialence checking.\n");
1021 log("\n");
1022 log(" -prove-asserts\n");
1023 log(" Prove that all asserts in the design hold.\n");
1024 log("\n");
1025 log(" -prove-skip <N>\n");
1026 log(" Do not enforce the prove-condition for the first <N> time steps.\n");
1027 log("\n");
1028 log(" -maxsteps <N>\n");
1029 log(" Set a maximum length for the induction.\n");
1030 log("\n");
1031 log(" -initsteps <N>\n");
1032 log(" Set initial length for the induction.\n");
1033 log(" This will speed up the search of the right induction length\n");
1034 log(" for deep induction proofs.\n");
1035 log("\n");
1036 log(" -stepsize <N>\n");
1037 log(" Increase the size of the induction proof in steps of <N>.\n");
1038 log(" This will speed up the search of the right induction length\n");
1039 log(" for deep induction proofs.\n");
1040 log("\n");
1041 log(" -timeout <N>\n");
1042 log(" Maximum number of seconds a single SAT instance may take.\n");
1043 log("\n");
1044 log(" -verify\n");
1045 log(" Return an error and stop the synthesis script if the proof fails.\n");
1046 log("\n");
1047 log(" -verify-no-timeout\n");
1048 log(" Like -verify but do not return an error for timeouts.\n");
1049 log("\n");
1050 log(" -falsify\n");
1051 log(" Return an error and stop the synthesis script if the proof succeeds.\n");
1052 log("\n");
1053 log(" -falsify-no-timeout\n");
1054 log(" Like -falsify but do not return an error for timeouts.\n");
1055 log("\n");
1056 }
1057 virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
1058 {
1059 std::vector<std::pair<std::string, std::string>> sets, sets_init, prove, prove_x;
1060 std::map<int, std::vector<std::pair<std::string, std::string>>> sets_at;
1061 std::map<int, std::vector<std::string>> unsets_at, sets_def_at, sets_any_undef_at, sets_all_undef_at;
1062 std::vector<std::string> shows, sets_def, sets_any_undef, sets_all_undef;
1063 int loopcount = 0, seq_len = 0, maxsteps = 0, initsteps = 0, timeout = 0, prove_skip = 0;
1064 bool verify = false, fail_on_timeout = false, enable_undef = false, set_def_inputs = false;
1065 bool ignore_div_by_zero = false, set_init_undef = false, set_init_zero = false, max_undef = false;
1066 bool tempinduct = false, prove_asserts = false, show_inputs = false, show_outputs = false;
1067 bool ignore_unknown_cells = false, falsify = false, tempinduct_def = false, set_init_def = false;
1068 bool tempinduct_baseonly = false, tempinduct_inductonly = false, set_assumes = false;
1069 int tempinduct_skip = 0, stepsize = 1;
1070 std::string vcd_file_name, json_file_name, cnf_file_name;
1071
1072 log_header("Executing SAT pass (solving SAT problems in the circuit).\n");
1073
1074 size_t argidx;
1075 for (argidx = 1; argidx < args.size(); argidx++) {
1076 if (args[argidx] == "-all") {
1077 loopcount = -1;
1078 continue;
1079 }
1080 if (args[argidx] == "-verify") {
1081 fail_on_timeout = true;
1082 verify = true;
1083 continue;
1084 }
1085 if (args[argidx] == "-verify-no-timeout") {
1086 verify = true;
1087 continue;
1088 }
1089 if (args[argidx] == "-falsify") {
1090 fail_on_timeout = true;
1091 falsify = true;
1092 continue;
1093 }
1094 if (args[argidx] == "-falsify-no-timeout") {
1095 falsify = true;
1096 continue;
1097 }
1098 if (args[argidx] == "-timeout" && argidx+1 < args.size()) {
1099 timeout = atoi(args[++argidx].c_str());
1100 continue;
1101 }
1102 if (args[argidx] == "-max" && argidx+1 < args.size()) {
1103 loopcount = atoi(args[++argidx].c_str());
1104 continue;
1105 }
1106 if (args[argidx] == "-maxsteps" && argidx+1 < args.size()) {
1107 maxsteps = atoi(args[++argidx].c_str());
1108 continue;
1109 }
1110 if (args[argidx] == "-initsteps" && argidx+1 < args.size()) {
1111 initsteps = atoi(args[++argidx].c_str());
1112 continue;
1113 }
1114 if (args[argidx] == "-stepsize" && argidx+1 < args.size()) {
1115 stepsize = std::max(1, atoi(args[++argidx].c_str()));
1116 continue;
1117 }
1118 if (args[argidx] == "-ignore_div_by_zero") {
1119 ignore_div_by_zero = true;
1120 continue;
1121 }
1122 if (args[argidx] == "-enable_undef") {
1123 enable_undef = true;
1124 continue;
1125 }
1126 if (args[argidx] == "-max_undef") {
1127 enable_undef = true;
1128 max_undef = true;
1129 continue;
1130 }
1131 if (args[argidx] == "-set-def-inputs") {
1132 enable_undef = true;
1133 set_def_inputs = true;
1134 continue;
1135 }
1136 if (args[argidx] == "-set" && argidx+2 < args.size()) {
1137 std::string lhs = args[++argidx];
1138 std::string rhs = args[++argidx];
1139 sets.push_back(std::pair<std::string, std::string>(lhs, rhs));
1140 continue;
1141 }
1142 if (args[argidx] == "-set-def" && argidx+1 < args.size()) {
1143 sets_def.push_back(args[++argidx]);
1144 enable_undef = true;
1145 continue;
1146 }
1147 if (args[argidx] == "-set-any-undef" && argidx+1 < args.size()) {
1148 sets_any_undef.push_back(args[++argidx]);
1149 enable_undef = true;
1150 continue;
1151 }
1152 if (args[argidx] == "-set-all-undef" && argidx+1 < args.size()) {
1153 sets_all_undef.push_back(args[++argidx]);
1154 enable_undef = true;
1155 continue;
1156 }
1157 if (args[argidx] == "-set-assumes") {
1158 set_assumes = true;
1159 continue;
1160 }
1161 if (args[argidx] == "-tempinduct") {
1162 tempinduct = true;
1163 continue;
1164 }
1165 if (args[argidx] == "-tempinduct-def") {
1166 tempinduct = true;
1167 tempinduct_def = true;
1168 continue;
1169 }
1170 if (args[argidx] == "-tempinduct-baseonly") {
1171 tempinduct = true;
1172 tempinduct_baseonly = true;
1173 continue;
1174 }
1175 if (args[argidx] == "-tempinduct-inductonly") {
1176 tempinduct = true;
1177 tempinduct_inductonly = true;
1178 continue;
1179 }
1180 if (args[argidx] == "-tempinduct-skip" && argidx+1 < args.size()) {
1181 tempinduct_skip = atoi(args[++argidx].c_str());
1182 continue;
1183 }
1184 if (args[argidx] == "-prove" && argidx+2 < args.size()) {
1185 std::string lhs = args[++argidx];
1186 std::string rhs = args[++argidx];
1187 prove.push_back(std::pair<std::string, std::string>(lhs, rhs));
1188 continue;
1189 }
1190 if (args[argidx] == "-prove-x" && argidx+2 < args.size()) {
1191 std::string lhs = args[++argidx];
1192 std::string rhs = args[++argidx];
1193 prove_x.push_back(std::pair<std::string, std::string>(lhs, rhs));
1194 enable_undef = true;
1195 continue;
1196 }
1197 if (args[argidx] == "-prove-asserts") {
1198 prove_asserts = true;
1199 continue;
1200 }
1201 if (args[argidx] == "-prove-skip" && argidx+1 < args.size()) {
1202 prove_skip = atoi(args[++argidx].c_str());
1203 continue;
1204 }
1205 if (args[argidx] == "-seq" && argidx+1 < args.size()) {
1206 seq_len = atoi(args[++argidx].c_str());
1207 continue;
1208 }
1209 if (args[argidx] == "-set-at" && argidx+3 < args.size()) {
1210 int timestep = atoi(args[++argidx].c_str());
1211 std::string lhs = args[++argidx];
1212 std::string rhs = args[++argidx];
1213 sets_at[timestep].push_back(std::pair<std::string, std::string>(lhs, rhs));
1214 continue;
1215 }
1216 if (args[argidx] == "-unset-at" && argidx+2 < args.size()) {
1217 int timestep = atoi(args[++argidx].c_str());
1218 unsets_at[timestep].push_back(args[++argidx]);
1219 continue;
1220 }
1221 if (args[argidx] == "-set-def-at" && argidx+2 < args.size()) {
1222 int timestep = atoi(args[++argidx].c_str());
1223 sets_def_at[timestep].push_back(args[++argidx]);
1224 enable_undef = true;
1225 continue;
1226 }
1227 if (args[argidx] == "-set-any-undef-at" && argidx+2 < args.size()) {
1228 int timestep = atoi(args[++argidx].c_str());
1229 sets_any_undef_at[timestep].push_back(args[++argidx]);
1230 enable_undef = true;
1231 continue;
1232 }
1233 if (args[argidx] == "-set-all-undef-at" && argidx+2 < args.size()) {
1234 int timestep = atoi(args[++argidx].c_str());
1235 sets_all_undef_at[timestep].push_back(args[++argidx]);
1236 enable_undef = true;
1237 continue;
1238 }
1239 if (args[argidx] == "-set-init" && argidx+2 < args.size()) {
1240 std::string lhs = args[++argidx];
1241 std::string rhs = args[++argidx];
1242 sets_init.push_back(std::pair<std::string, std::string>(lhs, rhs));
1243 continue;
1244 }
1245 if (args[argidx] == "-set-init-undef") {
1246 set_init_undef = true;
1247 enable_undef = true;
1248 continue;
1249 }
1250 if (args[argidx] == "-set-init-def") {
1251 set_init_def = true;
1252 continue;
1253 }
1254 if (args[argidx] == "-set-init-zero") {
1255 set_init_zero = true;
1256 continue;
1257 }
1258 if (args[argidx] == "-show" && argidx+1 < args.size()) {
1259 shows.push_back(args[++argidx]);
1260 continue;
1261 }
1262 if (args[argidx] == "-show-inputs") {
1263 show_inputs = true;
1264 continue;
1265 }
1266 if (args[argidx] == "-show-outputs") {
1267 show_outputs = true;
1268 continue;
1269 }
1270 if (args[argidx] == "-show-ports") {
1271 show_inputs = true;
1272 show_outputs = true;
1273 continue;
1274 }
1275 if (args[argidx] == "-ignore_unknown_cells") {
1276 ignore_unknown_cells = true;
1277 continue;
1278 }
1279 if (args[argidx] == "-dump_vcd" && argidx+1 < args.size()) {
1280 vcd_file_name = args[++argidx];
1281 continue;
1282 }
1283 if (args[argidx] == "-dump_json" && argidx+1 < args.size()) {
1284 json_file_name = args[++argidx];
1285 continue;
1286 }
1287 if (args[argidx] == "-dump_cnf" && argidx+1 < args.size()) {
1288 cnf_file_name = args[++argidx];
1289 continue;
1290 }
1291 break;
1292 }
1293 extra_args(args, argidx, design);
1294
1295 RTLIL::Module *module = NULL;
1296 for (auto mod : design->selected_modules()) {
1297 if (module)
1298 log_cmd_error("Only one module must be selected for the SAT pass! (selected: %s and %s)\n", log_id(module), log_id(mod));
1299 module = mod;
1300 }
1301 if (module == NULL)
1302 log_cmd_error("Can't perform SAT on an empty selection!\n");
1303
1304 if (!prove.size() && !prove_x.size() && !prove_asserts && tempinduct)
1305 log_cmd_error("Got -tempinduct but nothing to prove!\n");
1306
1307 if (prove_skip && tempinduct)
1308 log_cmd_error("Options -prove-skip and -tempinduct don't work with each other. Use -seq instead of -prove-skip.\n");
1309
1310 if (prove_skip >= seq_len && prove_skip > 0)
1311 log_cmd_error("The value of -prove-skip must be smaller than the one of -seq.\n");
1312
1313 if (set_init_undef + set_init_zero + set_init_def > 1)
1314 log_cmd_error("The options -set-init-undef, -set-init-def, and -set-init-zero are exclusive!\n");
1315
1316 if (set_def_inputs) {
1317 for (auto &it : module->wires_)
1318 if (it.second->port_input)
1319 sets_def.push_back(it.second->name.str());
1320 }
1321
1322 if (show_inputs) {
1323 for (auto &it : module->wires_)
1324 if (it.second->port_input)
1325 shows.push_back(it.second->name.str());
1326 }
1327
1328 if (show_outputs) {
1329 for (auto &it : module->wires_)
1330 if (it.second->port_output)
1331 shows.push_back(it.second->name.str());
1332 }
1333
1334 if (tempinduct)
1335 {
1336 if (loopcount > 0 || max_undef)
1337 log_cmd_error("The options -max, -all, and -max_undef are not supported for temporal induction proofs!\n");
1338
1339 SatHelper basecase(design, module, enable_undef);
1340 SatHelper inductstep(design, module, enable_undef);
1341 bool basecase_setup_init = true;
1342
1343 basecase.sets = sets;
1344 basecase.set_assumes = set_assumes;
1345 basecase.prove = prove;
1346 basecase.prove_x = prove_x;
1347 basecase.prove_asserts = prove_asserts;
1348 basecase.sets_at = sets_at;
1349 basecase.unsets_at = unsets_at;
1350 basecase.shows = shows;
1351 basecase.timeout = timeout;
1352 basecase.sets_def = sets_def;
1353 basecase.sets_any_undef = sets_any_undef;
1354 basecase.sets_all_undef = sets_all_undef;
1355 basecase.sets_def_at = sets_def_at;
1356 basecase.sets_any_undef_at = sets_any_undef_at;
1357 basecase.sets_all_undef_at = sets_all_undef_at;
1358 basecase.sets_init = sets_init;
1359 basecase.set_init_def = set_init_def;
1360 basecase.set_init_undef = set_init_undef;
1361 basecase.set_init_zero = set_init_zero;
1362 basecase.satgen.ignore_div_by_zero = ignore_div_by_zero;
1363 basecase.ignore_unknown_cells = ignore_unknown_cells;
1364
1365 for (int timestep = 1; timestep <= seq_len; timestep++)
1366 if (!tempinduct_inductonly)
1367 basecase.setup(timestep);
1368
1369 inductstep.sets = sets;
1370 inductstep.set_assumes = set_assumes;
1371 inductstep.prove = prove;
1372 inductstep.prove_x = prove_x;
1373 inductstep.prove_asserts = prove_asserts;
1374 inductstep.shows = shows;
1375 inductstep.timeout = timeout;
1376 inductstep.sets_def = sets_def;
1377 inductstep.sets_any_undef = sets_any_undef;
1378 inductstep.sets_all_undef = sets_all_undef;
1379 inductstep.satgen.ignore_div_by_zero = ignore_div_by_zero;
1380 inductstep.ignore_unknown_cells = ignore_unknown_cells;
1381
1382 if (!tempinduct_baseonly) {
1383 inductstep.setup(1);
1384 inductstep.ez->assume(inductstep.setup_proof(1));
1385 }
1386
1387 if (tempinduct_def) {
1388 std::vector<int> undef_state = inductstep.satgen.importUndefSigSpec(inductstep.satgen.initial_state.export_all(), 1);
1389 inductstep.ez->assume(inductstep.ez->NOT(inductstep.ez->expression(ezSAT::OpOr, undef_state)));
1390 }
1391
1392 for (int inductlen = 1; inductlen <= maxsteps || maxsteps == 0; inductlen++)
1393 {
1394 log("\n** Trying induction with length %d **\n", inductlen);
1395
1396 // phase 1: proving base case
1397
1398 if (!tempinduct_inductonly)
1399 {
1400 basecase.setup(seq_len + inductlen);
1401 int property = basecase.setup_proof(seq_len + inductlen);
1402 basecase.generate_model();
1403
1404 if (basecase_setup_init) {
1405 basecase.setup_init();
1406 basecase_setup_init = false;
1407 }
1408
1409 if (inductlen > 1)
1410 basecase.force_unique_state(seq_len + 1, seq_len + inductlen);
1411
1412 if (tempinduct_skip < inductlen)
1413 {
1414 log("\n[base case %d] Solving problem with %d variables and %d clauses..\n",
1415 inductlen, basecase.ez->numCnfVariables(), basecase.ez->numCnfClauses());
1416
1417 if (basecase.solve(basecase.ez->NOT(property))) {
1418 log("SAT temporal induction proof finished - model found for base case: FAIL!\n");
1419 print_proof_failed();
1420 basecase.print_model();
1421 if(!vcd_file_name.empty())
1422 basecase.dump_model_to_vcd(vcd_file_name);
1423 if(!json_file_name.empty())
1424 basecase.dump_model_to_json(json_file_name);
1425 goto tip_failed;
1426 }
1427
1428 if (basecase.gotTimeout)
1429 goto timeout;
1430
1431 log("Base case for induction length %d proven.\n", inductlen);
1432 }
1433 else
1434 {
1435 log("\n[base case %d] Skipping prove for this step (-tempinduct-skip %d).",
1436 inductlen, tempinduct_skip);
1437 log("\n[base case %d] Problem size so far: %d variables and %d clauses.\n",
1438 inductlen, basecase.ez->numCnfVariables(), basecase.ez->numCnfClauses());
1439 }
1440 basecase.ez->assume(property);
1441 }
1442
1443 // phase 2: proving induction step
1444
1445 if (!tempinduct_baseonly)
1446 {
1447 inductstep.setup(inductlen + 1);
1448 int property = inductstep.setup_proof(inductlen + 1);
1449 inductstep.generate_model();
1450
1451 if (inductlen > 1)
1452 inductstep.force_unique_state(1, inductlen + 1);
1453
1454 if (inductlen <= tempinduct_skip || inductlen <= initsteps || inductlen % stepsize != 0)
1455 {
1456 if (inductlen < tempinduct_skip)
1457 log("\n[induction step %d] Skipping prove for this step (-tempinduct-skip %d).",
1458 inductlen, tempinduct_skip);
1459 if (inductlen < initsteps)
1460 log("\n[induction step %d] Skipping prove for this step (-initsteps %d).",
1461 inductlen, tempinduct_skip);
1462 if (inductlen % stepsize != 0)
1463 log("\n[induction step %d] Skipping prove for this step (-stepsize %d).",
1464 inductlen, stepsize);
1465 log("\n[induction step %d] Problem size so far: %d variables and %d clauses.\n",
1466 inductlen, inductstep.ez->numCnfVariables(), inductstep.ez->numCnfClauses());
1467 inductstep.ez->assume(property);
1468 }
1469 else
1470 {
1471 if (!cnf_file_name.empty())
1472 {
1473 FILE *f = fopen(cnf_file_name.c_str(), "w");
1474 if (!f)
1475 log_cmd_error("Can't open output file `%s' for writing: %s\n", cnf_file_name.c_str(), strerror(errno));
1476
1477 log("Dumping CNF to file `%s'.\n", cnf_file_name.c_str());
1478 cnf_file_name.clear();
1479
1480 inductstep.ez->printDIMACS(f, false);
1481 fclose(f);
1482 }
1483
1484 log("\n[induction step %d] Solving problem with %d variables and %d clauses..\n",
1485 inductlen, inductstep.ez->numCnfVariables(), inductstep.ez->numCnfClauses());
1486
1487 if (!inductstep.solve(inductstep.ez->NOT(property))) {
1488 if (inductstep.gotTimeout)
1489 goto timeout;
1490 log("Induction step proven: SUCCESS!\n");
1491 print_qed();
1492 goto tip_success;
1493 }
1494
1495 log("Induction step failed. Incrementing induction length.\n");
1496 inductstep.ez->assume(property);
1497 inductstep.print_model();
1498 }
1499 }
1500 }
1501
1502 if (tempinduct_baseonly) {
1503 log("\nReached maximum number of time steps -> proved base case for %d steps: SUCCESS!\n", maxsteps);
1504 goto tip_success;
1505 }
1506
1507 log("\nReached maximum number of time steps -> proof failed.\n");
1508 if(!vcd_file_name.empty())
1509 inductstep.dump_model_to_vcd(vcd_file_name);
1510 if(!json_file_name.empty())
1511 inductstep.dump_model_to_json(json_file_name);
1512 print_proof_failed();
1513
1514 tip_failed:
1515 if (verify) {
1516 log("\n");
1517 log_error("Called with -verify and proof did fail!\n");
1518 }
1519
1520 if (0)
1521 tip_success:
1522 if (falsify) {
1523 log("\n");
1524 log_error("Called with -falsify and proof did succeed!\n");
1525 }
1526 }
1527 else
1528 {
1529 if (maxsteps > 0)
1530 log_cmd_error("The options -maxsteps is only supported for temporal induction proofs!\n");
1531
1532 SatHelper sathelper(design, module, enable_undef);
1533
1534 sathelper.sets = sets;
1535 sathelper.set_assumes = set_assumes;
1536 sathelper.prove = prove;
1537 sathelper.prove_x = prove_x;
1538 sathelper.prove_asserts = prove_asserts;
1539 sathelper.sets_at = sets_at;
1540 sathelper.unsets_at = unsets_at;
1541 sathelper.shows = shows;
1542 sathelper.timeout = timeout;
1543 sathelper.sets_def = sets_def;
1544 sathelper.sets_any_undef = sets_any_undef;
1545 sathelper.sets_all_undef = sets_all_undef;
1546 sathelper.sets_def_at = sets_def_at;
1547 sathelper.sets_any_undef_at = sets_any_undef_at;
1548 sathelper.sets_all_undef_at = sets_all_undef_at;
1549 sathelper.sets_init = sets_init;
1550 sathelper.set_init_def = set_init_def;
1551 sathelper.set_init_undef = set_init_undef;
1552 sathelper.set_init_zero = set_init_zero;
1553 sathelper.satgen.ignore_div_by_zero = ignore_div_by_zero;
1554 sathelper.ignore_unknown_cells = ignore_unknown_cells;
1555
1556 if (seq_len == 0) {
1557 sathelper.setup();
1558 if (sathelper.prove.size() || sathelper.prove_x.size() || sathelper.prove_asserts)
1559 sathelper.ez->assume(sathelper.ez->NOT(sathelper.setup_proof()));
1560 } else {
1561 std::vector<int> prove_bits;
1562 for (int timestep = 1; timestep <= seq_len; timestep++) {
1563 sathelper.setup(timestep);
1564 if (sathelper.prove.size() || sathelper.prove_x.size() || sathelper.prove_asserts)
1565 if (timestep > prove_skip)
1566 prove_bits.push_back(sathelper.setup_proof(timestep));
1567 }
1568 if (sathelper.prove.size() || sathelper.prove_x.size() || sathelper.prove_asserts)
1569 sathelper.ez->assume(sathelper.ez->NOT(sathelper.ez->expression(ezSAT::OpAnd, prove_bits)));
1570 sathelper.setup_init();
1571 }
1572 sathelper.generate_model();
1573
1574 if (!cnf_file_name.empty())
1575 {
1576 FILE *f = fopen(cnf_file_name.c_str(), "w");
1577 if (!f)
1578 log_cmd_error("Can't open output file `%s' for writing: %s\n", cnf_file_name.c_str(), strerror(errno));
1579
1580 log("Dumping CNF to file `%s'.\n", cnf_file_name.c_str());
1581 cnf_file_name.clear();
1582
1583 sathelper.ez->printDIMACS(f, false);
1584 fclose(f);
1585 }
1586
1587 int rerun_counter = 0;
1588
1589 rerun_solver:
1590 log("\nSolving problem with %d variables and %d clauses..\n",
1591 sathelper.ez->numCnfVariables(), sathelper.ez->numCnfClauses());
1592
1593 if (sathelper.solve())
1594 {
1595 if (max_undef) {
1596 log("SAT model found. maximizing number of undefs.\n");
1597 sathelper.maximize_undefs();
1598 }
1599
1600 if (!prove.size() && !prove_x.size() && !prove_asserts) {
1601 log("SAT solving finished - model found:\n");
1602 } else {
1603 log("SAT proof finished - model found: FAIL!\n");
1604 print_proof_failed();
1605 }
1606
1607 sathelper.print_model();
1608
1609 if(!vcd_file_name.empty())
1610 sathelper.dump_model_to_vcd(vcd_file_name);
1611 if(!json_file_name.empty())
1612 sathelper.dump_model_to_json(json_file_name);
1613
1614 if (loopcount != 0) {
1615 loopcount--, rerun_counter++;
1616 sathelper.invalidate_model(max_undef);
1617 goto rerun_solver;
1618 }
1619
1620 if (!prove.size() && !prove_x.size() && !prove_asserts) {
1621 if (falsify) {
1622 log("\n");
1623 log_error("Called with -falsify and found a model!\n");
1624 }
1625 } else {
1626 if (verify) {
1627 log("\n");
1628 log_error("Called with -verify and proof did fail!\n");
1629 }
1630 }
1631 }
1632 else
1633 {
1634 if (sathelper.gotTimeout)
1635 goto timeout;
1636 if (rerun_counter)
1637 log("SAT solving finished - no more models found (after %d distinct solutions).\n", rerun_counter);
1638 else if (!prove.size() && !prove_x.size() && !prove_asserts) {
1639 log("SAT solving finished - no model found.\n");
1640 if (verify) {
1641 log("\n");
1642 log_error("Called with -verify and found no model!\n");
1643 }
1644 } else {
1645 log("SAT proof finished - no model found: SUCCESS!\n");
1646 print_qed();
1647 if (falsify) {
1648 log("\n");
1649 log_error("Called with -falsify and proof did succeed!\n");
1650 }
1651 }
1652 }
1653
1654 if (!prove.size() && !prove_x.size() && !prove_asserts) {
1655 if (falsify && rerun_counter) {
1656 log("\n");
1657 log_error("Called with -falsify and found a model!\n");
1658 }
1659 } else {
1660 if (verify && rerun_counter) {
1661 log("\n");
1662 log_error("Called with -verify and proof did fail!\n");
1663 }
1664 }
1665 }
1666
1667 if (0) {
1668 timeout:
1669 log("Interrupted SAT solver: TIMEOUT!\n");
1670 print_timeout();
1671 if (fail_on_timeout)
1672 log_error("Called with -verify and proof did time out!\n");
1673 }
1674 }
1675 } SatPass;
1676
1677 PRIVATE_NAMESPACE_END