aboutsummaryrefslogtreecommitdiffstats
path: root/passes/equiv/equiv_simple.cc
blob: c2fab26f2bc411c62c03572a1fdd601c9de76554 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/satgen.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct EquivSimpleWorker
{
	Module *module;
	const vector<Cell*> &equiv_cells;
	Cell *equiv_cell;

	SigMap &sigmap;
	dict<SigBit, Cell*> &bit2driver;

	ezSatPtr ez;
	SatGen satgen;
	int max_seq;
	bool short_cones;
	bool verbose;

	pool<pair<Cell*, int>> imported_cells_cache;

	EquivSimpleWorker(const vector<Cell*> &equiv_cells, SigMap &sigmap, dict<SigBit, Cell*> &bit2driver, int max_seq, bool short_cones, bool verbose, bool model_undef) :
			module(equiv_cells.front()->module), equiv_cells(equiv_cells), equiv_cell(nullptr),
			sigmap(sigmap), bit2driver(bit2driver), satgen(ez.get(), &sigmap), max_seq(max_seq), short_cones(short_cones), verbose(verbose)
	{
		satgen.model_undef = model_undef;
	}

	bool find_input_cone(pool<SigBit> &next_seed, pool<Cell*> &cells_cone, pool<SigBit> &bits_cone, const pool<Cell*> &cells_stop, const pool<SigBit> &bits_stop, pool<SigBit> *input_bits, Cell *cell)
	{
		if (cells_cone.count(cell))
			return false;

		cells_cone.insert(cell);

		if (cells_stop.count(cell))
			return true;

		for (auto &conn : cell->connections())
			if (yosys_celltypes.cell_input(cell->type, conn.first))
				for (auto bit : sigmap(conn.second)) {
					if (cell->type.in("$dff", "$_DFF_P_", "$_DFF_N_", "$ff", "$_FF_")) {
						if (!conn.first.in("\\CLK", "\\C"))
							next_seed.insert(bit);
					} else
						find_input_cone(next_seed, cells_cone, bits_cone, cells_stop, bits_stop, input_bits, bit);
				}
		return false;
	}

	void find_input_cone(pool<SigBit> &next_seed, pool<Cell*> &cells_cone, pool<SigBit> &bits_cone, const pool<Cell*> &cells_stop, const pool<SigBit> &bits_stop, pool<SigBit> *input_bits, SigBit bit)
	{
		if (bits_cone.count(bit))
			return;

		bits_cone.insert(bit);

		if (bits_stop.count(bit)) {
			if (input_bits != nullptr) input_bits->insert(bit);
			return;
		}

		if (!bit2driver.count(bit))
			return;

		if (find_input_cone(next_seed, cells_cone, bits_cone, cells_stop, bits_stop, input_bits, bit2driver.at(bit)))
			if (input_bits != nullptr) input_bits->insert(bit);
	}

	bool run_cell()
	{
		SigBit bit_a = sigmap(equiv_cell->getPort("\\A")).as_bit();
		SigBit bit_b = sigmap(equiv_cell->getPort("\\B")).as_bit();
		int ez_context = ez->frozen_literal();

		if (satgen.model_undef)
		{
			int ez_a = satgen.importSigBit(bit_a, max_seq+1);
			int ez_b = satgen.importDefSigBit(bit_b, max_seq+1);
			int ez_undef_a = satgen.importUndefSigBit(bit_a, max_seq+1);

			ez->assume(ez->XOR(ez_a, ez_b), ez_context);
			ez->assume(ez->NOT(ez_undef_a), ez_context);
		}
		else
		{
			int ez_a = satgen.importSigBit(bit_a, max_seq+1);
			int ez_b = satgen.importSigBit(bit_b, max_seq+1);
			ez->assume(ez->XOR(ez_a, ez_b), ez_context);
		}

		pool<SigBit> seed_a = { bit_a };
		pool<SigBit> seed_b = { bit_b };

		if (verbose) {
			log("  Trying to prove $equiv cell %s:\n", log_id(equiv_cell));
			log("    A = %s, B = %s, Y = %s\n", log_signal(bit_a), log_signal(bit_b), log_signal(equiv_cell->getPort("\\Y")));
		} else {
			log("  Trying to prove $equiv for %s:", log_signal(equiv_cell->getPort("\\Y")));
		}

		int step = max_seq;
		while (1)
		{
			pool<Cell*> no_stop_cells;
			pool<SigBit> no_stop_bits;

			pool<Cell*> full_cells_cone_a, full_cells_cone_b;
			pool<SigBit> full_bits_cone_a, full_bits_cone_b;

			pool<SigBit> next_seed_a, next_seed_b;

			for (auto bit_a : seed_a)
				find_input_cone(next_seed_a, full_cells_cone_a, full_bits_cone_a, no_stop_cells, no_stop_bits, nullptr, bit_a);
			next_seed_a.clear();

			for (auto bit_b : seed_b)
				find_input_cone(next_seed_b, full_cells_cone_b, full_bits_cone_b, no_stop_cells, no_stop_bits, nullptr, bit_b);
			next_seed_b.clear();

			pool<Cell*> short_cells_cone_a, short_cells_cone_b;
			pool<SigBit> short_bits_cone_a, short_bits_cone_b;
			pool<SigBit> input_bits;

			if (short_cones)
			{
				for (auto bit_a : seed_a)
					find_input_cone(next_seed_a, short_cells_cone_a, short_bits_cone_a, full_cells_cone_b, full_bits_cone_b, &input_bits, bit_a);
				next_seed_a.swap(seed_a);

				for (auto bit_b : seed_b)
					find_input_cone(next_seed_b, short_cells_cone_b, short_bits_cone_b, full_cells_cone_a, full_bits_cone_a, &input_bits, bit_b);
				next_seed_b.swap(seed_b);
			}
			else
			{
				short_cells_cone_a = full_cells_cone_a;
				short_bits_cone_a = full_bits_cone_a;
				next_seed_a.swap(seed_a);

				short_cells_cone_b = full_cells_cone_b;
				short_bits_cone_b = full_bits_cone_b;
				next_seed_b.swap(seed_b);
			}

			pool<Cell*> problem_cells;
			problem_cells.insert(short_cells_cone_a.begin(), short_cells_cone_a.end());
			problem_cells.insert(short_cells_cone_b.begin(), short_cells_cone_b.end());

			if (verbose)
			{
				log("    Adding %d new cells to the problem (%d A, %d B, %d shared).\n",
						GetSize(problem_cells), GetSize(short_cells_cone_a), GetSize(short_cells_cone_b),
						(GetSize(short_cells_cone_a) + GetSize(short_cells_cone_b)) - GetSize(problem_cells));
			#if 0
				for (auto cell : short_cells_cone_a)
					log("      A-side cell: %s\n", log_id(cell));

				for (auto cell : short_cells_cone_b)
					log("      B-side cell: %s\n", log_id(cell));
			#endif
			}

			for (auto cell : problem_cells) {
				auto key = pair<Cell*, int>(cell, step+1);
				if (!imported_cells_cache.count(key) && !satgen.importCell(cell, step+1))
					log_cmd_error("No SAT model available for cell %s (%s).\n", log_id(cell), log_id(cell->type));
				imported_cells_cache.insert(key);
			}

			if (satgen.model_undef) {
				for (auto bit : input_bits)
					ez->assume(ez->NOT(satgen.importUndefSigBit(bit, step+1)));
			}

			if (verbose)
				log("    Problem size at t=%d: %d literals, %d clauses\n", step, ez->numCnfVariables(), ez->numCnfClauses());

			if (!ez->solve(ez_context)) {
				log(verbose ? "    Proved equivalence! Marking $equiv cell as proven.\n" : " success!\n");
				equiv_cell->setPort("\\B", equiv_cell->getPort("\\A"));
				ez->assume(ez->NOT(ez_context));
				return true;
			}

			if (verbose)
				log("    Failed to prove equivalence with sequence length %d.\n", max_seq - step);

			if (--step < 0) {
				if (verbose)
					log("    Reached sequence limit.\n");
				break;
			}

			if (seed_a.empty() && seed_b.empty()) {
				if (verbose)
					log("    No nets to continue in previous time step.\n");
				break;
			}

			if (seed_a.empty()) {
				if (verbose)
					log("    No nets on A-side to continue in previous time step.\n");
				break;
			}

			if (seed_b.empty()) {
				if (verbose)
					log("    No nets on B-side to continue in previous time step.\n");
				break;
			}

			if (verbose) {
			#if 0
				log("    Continuing analysis in previous time step with the following nets:\n");
				for (auto bit : seed_a)
					log("      A: %s\n", log_signal(bit));
				for (auto bit : seed_b)
					log("      B: %s\n", log_signal(bit));
			#else
				log("    Continuing analysis in previous time step with %d A- and %d B-nets.\n", GetSize(seed_a), GetSize(seed_b));
			#endif
			}
		}

		if (!verbose)
			log(" failed.\n");

		ez->assume(ez->NOT(ez_context));
		return false;
	}

	int run()
	{
		if (GetSize(equiv_cells) > 1) {
			SigSpec sig;
			for (auto c : equiv_cells)
				sig.append(sigmap(c->getPort("\\Y")));
			log(" Grouping SAT models for %s:\n", log_signal(sig));
		}

		int counter = 0;
		for (auto c : equiv_cells) {
			equiv_cell = c;
			if (run_cell())
				counter++;
		}
		return counter;
	}

};

struct EquivSimplePass : public Pass {
	EquivSimplePass() : Pass("equiv_simple", "try proving simple $equiv instances") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    equiv_simple [options] [selection]\n");
		log("\n");
		log("This command tries to prove $equiv cells using a simple direct SAT approach.\n");
		log("\n");
		log("    -v\n");
		log("        verbose output\n");
		log("\n");
		log("    -undef\n");
		log("        enable modelling of undef states\n");
		log("\n");
		log("    -short\n");
		log("        create shorter input cones that stop at shared nodes. This yields\n");
		log("        simpler SAT problems but sometimes fails to prove equivalence.\n");
		log("\n");
		log("    -nogroup\n");
		log("        disabling grouping of $equiv cells by output wire\n");
		log("\n");
		log("    -seq <N>\n");
		log("        the max. number of time steps to be considered (default = 1)\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, Design *design) YS_OVERRIDE
	{
		bool verbose = false, short_cones = false, model_undef = false, nogroup = false;
		int success_counter = 0;
		int max_seq = 1;

		log_header(design, "Executing EQUIV_SIMPLE pass.\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			if (args[argidx] == "-v") {
				verbose = true;
				continue;
			}
			if (args[argidx] == "-short") {
				short_cones = true;
				continue;
			}
			if (args[argidx] == "-undef") {
				model_undef = true;
				continue;
			}
			if (args[argidx] == "-nogroup") {
				nogroup = true;
				continue;
			}
			if (args[argidx] == "-seq" && argidx+1 < args.size()) {
				max_seq = atoi(args[++argidx].c_str());
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		CellTypes ct;
		ct.setup_internals();
		ct.setup_stdcells();

		for (auto module : design->selected_modules())
		{
			SigMap sigmap(module);
			dict<SigBit, Cell*> bit2driver;
			dict<SigBit, dict<SigBit, Cell*>> unproven_equiv_cells;
			int unproven_cells_counter = 0;

			for (auto cell : module->selected_cells())
				if (cell->type == "$equiv" && cell->getPort("\\A") != cell->getPort("\\B")) {
					auto bit = sigmap(cell->getPort("\\Y").as_bit());
					auto bit_group = bit;
					if (!nogroup && bit_group.wire)
						bit_group.offset = 0;
					unproven_equiv_cells[bit_group][bit] = cell;
					unproven_cells_counter++;
				}

			if (unproven_equiv_cells.empty())
				continue;

			log("Found %d unproven $equiv cells (%d groups) in %s:\n",
					unproven_cells_counter, GetSize(unproven_equiv_cells), log_id(module));

			for (auto cell : module->cells()) {
				if (!ct.cell_known(cell->type) && !cell->type.in("$dff", "$_DFF_P_", "$_DFF_N_", "$ff", "$_FF_"))
					continue;
				for (auto &conn : cell->connections())
					if (yosys_celltypes.cell_output(cell->type, conn.first))
						for (auto bit : sigmap(conn.second))
							bit2driver[bit] = cell;
			}

			unproven_equiv_cells.sort();
			for (auto it : unproven_equiv_cells)
			{
				it.second.sort();

				vector<Cell*> cells;
				for (auto it2 : it.second)
					cells.push_back(it2.second);

				EquivSimpleWorker worker(cells, sigmap, bit2driver, max_seq, short_cones, verbose, model_undef);
				success_counter += worker.run();
			}
		}

		log("Proved %d previously unproven $equiv cells.\n", success_counter);
	}
} EquivSimplePass;

PRIVATE_NAMESPACE_END