File size: 22,903 Bytes
107d124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Claire Xenia Wolf <claire@yosyshq.com>
 *
 *  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/sigtools.h"
#include "kernel/gzip.h"
#include "kernel/newcelltypes.h"
#include "libparse.h"
#include <string.h>
#include <errno.h>

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct cell_mapping {
	std::string cell_name;
	std::map<std::string, char> ports;
};
typedef std::map<RTLIL::IdString, cell_mapping> cell_mappings_t;

static void logmap(const cell_mappings_t &cell_mappings, IdString dff)
{
	if (cell_mappings.count(dff) == 0) {
		log("    unmapped dff/dlatch cell: %s\n", ID::str(dff));
	} else {
		std::string message = stringf("    %s %s (", cell_mappings.at(dff).cell_name, ID::str(dff).substr(1));
		bool first = true;
		for (auto &port : cell_mappings.at(dff).ports) {
			char arg[3] = { port.second, 0, 0 };
			if ('a' <= arg[0] && arg[0] <= 'z')
				arg[1] = arg[0] - ('a' - 'A'), arg[0] = '~';
			else
				arg[1] = arg[0], arg[0] = ' ';
			message += stringf("%s.%s(%s)", first ? "" : ", ", port.first, arg);
			first = false;
		}
		log("%s);\n", message);
	}
}

static bool parse_next_state(pool<std::string> &warned_cells, const LibertyAst *cell, const LibertyAst *attr, std::string &data_name, bool &data_not_inverted, std::string &enable_name, bool &enable_not_inverted)
{
	if (cell == nullptr || attr == nullptr || attr->value.empty())
		return false;

	auto expr = attr->value;
	auto cell_name = cell->args[0];

	for (size_t pos = expr.find_first_of("\"\t"); pos != std::string::npos; pos = expr.find_first_of("\"\t"))
		expr.erase(pos, 1);

	// if this isn't an enable flop, the next_state variable is usually just the input pin name.
	if (expr[expr.size()-1] == '\'') {
		data_name = expr.substr(0, expr.size()-1);
		data_not_inverted = false;
	} else if (expr[0] == '!') {
		data_name = expr.substr(1, expr.size()-1);
		data_not_inverted = false;
	} else if (expr[0] == '(' && expr[expr.size() - 1] == ')') {
		data_name = expr.substr(1, expr.size() - 2);
		data_not_inverted = true;
	} else {
		data_name = expr;
		data_not_inverted = true;
	}

	for (auto child : cell->children)
		if (child->id == "pin" && child->args.size() == 1 && child->args[0] == data_name)
			return true;

	// the next_state variable isn't just a pin name; perhaps this is an enable?
	auto helper = LibertyExpression::Lexer(expr);
	auto tree = LibertyExpression::parse(helper);
	// log_debug("liberty expression:\n%s\n", tree.str());

	if (tree.kind == LibertyExpression::Kind::EMPTY) {
		if (!warned_cells.count(cell_name)) {
			log_debug("Invalid expression '%s' in next_state attribute of cell '%s' - skipping.\n", expr, cell_name);
			warned_cells.insert(cell_name);
		}
		return false;
	}

	auto pin_names = std::unordered_set<std::string>{};
	tree.get_pin_names(pin_names);

	// from the `ff` block, we know the flop output signal name for loopback.
	auto ff = cell->find("ff");
	if (ff == nullptr || ff->args.size() != 2)
		return false;
	auto ff_output = ff->args.at(0);

	// This test is redundant with the one in enable_pin, but we're in a
	// position that gives better diagnostics here.
	if (!pin_names.count(ff_output)) {
		if (!warned_cells.count(cell_name)) {
			log_debug("Inference failed on expression '%s' in next_state attribute of cell '%s' because it does not contain ff output '%s' - skipping.\n", expr, cell_name, ff_output);
			warned_cells.insert(cell_name);
		}
		return false;
	}

	data_not_inverted = true;
	data_name = "";
	enable_not_inverted = true;
	enable_name = "";

	if (pin_names.size() == 3 && pin_names.count(ff_output)) {
		pin_names.erase(ff_output);
		auto pins = std::vector<std::string>(pin_names.begin(), pin_names.end());
		int lut = 0;
		for (int n = 0; n < 8; n++) {
			auto values = std::unordered_map<std::string, bool>{};
			values.insert(std::make_pair(pins[0], (n & 1) == 1));
			values.insert(std::make_pair(pins[1], (n & 2) == 2));
			values.insert(std::make_pair(ff_output, (n & 4) == 4));
			if (tree.eval(values))
				lut |= 1 << n;
		}
		// the ff output Q is in a known bit location, so we now just have to compare the LUT mask to known values to find the enable pin and polarity.
		if (lut == 0xD8) {
			data_name = pins[1];
			enable_name = pins[0];
			return true;
		}
		if (lut == 0xB8) {
			data_name = pins[0];
			enable_name = pins[1];
			return true;
		}
		enable_not_inverted = false;
		if (lut == 0xE4) {
			data_name = pins[1];
			enable_name = pins[0];
			return true;
		}
		if (lut == 0xE2) {
			data_name = pins[0];
			enable_name = pins[1];
			return true;
		}
		// this does not match an enable flop.
	}

	if (!warned_cells.count(cell_name)) {
		log_debug("Inference failed on expression '%s' in next_state attribute of cell '%s' because it does not evaluate to an enable flop - skipping.\n", expr, cell_name);
		warned_cells.insert(cell_name);
	}
	return false;
}

static bool parse_pin(const LibertyAst *cell, const LibertyAst *attr, std::string &pin_name, bool &pin_pol)
{
	if (cell == nullptr || attr == nullptr || attr->value.empty())
		return false;

	std::string value = attr->value;

	for (size_t pos = value.find_first_of("\" \t()"); pos != std::string::npos; pos = value.find_first_of("\" \t()"))
		value.erase(pos, 1);

	if (value[value.size()-1] == '\'') {
		pin_name = value.substr(0, value.size()-1);
		pin_pol = false;
	} else if (value[0] == '!') {
		pin_name = value.substr(1, value.size()-1);
		pin_pol = false;
	} else {
		pin_name = value;
		pin_pol = true;
	}

	for (auto child : cell->children)
		if (child->id == "pin" && child->args.size() == 1 && child->args[0] == pin_name)
			return true;

	/* If we end up here, the pin specified in the attribute does not exist, which is an error,
	   or, the attribute contains an expression which we do not yet support.
       For now, we'll simply produce a warning to let the user know something is up.
	*/
	if (pin_name.find_first_of("^*|&") == std::string::npos) {
		log_debug("Malformed liberty file - cannot find pin '%s' in cell '%s' - skipping.\n", pin_name, cell->args[0]);
	}
	else {
		log_debug("Found unsupported expression '%s' in pin attribute of cell '%s' - skipping.\n", pin_name, cell->args[0]);
	}

	return false;
}

struct FfSpec {
	bool is_latch = false;
	bool ctrlpol = false; // clock for ff, enable for latch
	bool has_reset = false, rstpol = false, rstval = false;
	bool has_sr = false, setpol = false, clrpol = false;
	bool dff_has_enable = false, dff_enapol = false;
};

struct FfType {
	IdString type;
	FfSpec spec;
};

// how good a candidate cell is, in decreasing order of importance
struct CellRank {
	bool inv = false; // the cell only drives the inverted output, so it needs an output inverter
	int pins = 0;
	double area = 0;

	auto operator<=>(const CellRank &other) const = default;

	std::string description() const { return stringf("%sinv, pins=%d, area=%.2f", inv ? "" : "non", pins, area); }
};

struct BestCell {
	const LibertyAst *cell = nullptr;
	std::map<std::string, char> ports;
	CellRank rank;
};

static bool is_dont_use(const LibertyAst *cell, std::vector<std::string> &dont_use_cells)
{
	const LibertyAst *dn = cell->find("dont_use");
	if (dn != nullptr && dn->value == "true")
		return true;
	for (std::string &pat : dont_use_cells)
		if (patmatch(pat.c_str(), cell->args[0].c_str()))
			return true;
	return false;
}

// scan the cell pins, and if the cell is a better match than the current best, record it
static void find_better_cell(BestCell &best, const LibertyAst *cell, const LibertyAst *storage, bool data_pol, std::map<std::string, char> &this_cell_ports)
{
	double area = 0;
	const LibertyAst *ar = cell->find("area");
	if (ar != nullptr && !ar->value.empty())
		area = atof(ar->value.c_str());

	int num_pins = 0;
	bool found_output = false;
	bool found_noninv_output = false;
	for (auto pin : cell->children)
	{
		if (pin->id != "pin" || pin->args.size() != 1)
			continue;

		const LibertyAst *dir = pin->find("direction");
		if (dir == nullptr || dir->value == "internal")
			continue;
		num_pins++;

		if (dir->value == "input" && this_cell_ports.count(pin->args[0]) == 0)
			return;

		const LibertyAst *func = pin->find("function");
		if (dir->value == "output" && func != nullptr) {
			std::string value = func->value;
			for (size_t pos = value.find_first_of("\" \t"); pos != std::string::npos; pos = value.find_first_of("\" \t"))
				value.erase(pos, 1);
			if (value == storage->args[0]) {
				this_cell_ports[pin->args[0]] = data_pol ? 'Q' : 'q';
				if (data_pol)
					found_noninv_output = true;
				found_output = true;
			} else
			if (value == storage->args[1]) {
				this_cell_ports[pin->args[0]] = data_pol ? 'q' : 'Q';
				if (!data_pol)
					found_noninv_output = true;
				found_output = true;
			}
		}

		if (this_cell_ports.count(pin->args[0]) == 0)
			this_cell_ports[pin->args[0]] = 0;
	}

	if (!found_output)
		return;

	CellRank rank;
	rank.inv = !found_noninv_output;
	rank.pins = num_pins;
	rank.area = area;

	// on a tie keep the cell we found first, so the result does not depend on the cell order
	if (best.cell != nullptr && !(rank < best.rank))
		return;

	best.cell = cell;
	best.rank = rank;
	best.ports.swap(this_cell_ports);
}

struct CellFinder
{
	const std::vector<const LibertyAst *> &cells;
	std::vector<std::string> &dont_use_cells;
	cell_mappings_t &cell_mappings;
	pool<std::string> warned_cells;

	CellFinder(const std::vector<const LibertyAst *> &cells, std::vector<std::string> &dont_use_cells, cell_mappings_t &cell_mappings) :
			cells(cells), dont_use_cells(dont_use_cells), cell_mappings(cell_mappings) { }

	void find(IdString cell_type, FfSpec spec);
};

void CellFinder::find(IdString cell_type, FfSpec spec)
{
	BestCell best;

	log_assert(!(spec.has_sr && spec.dff_enapol) && "set/reset cell with enable is unimplemented due to lack of cells for testing");

	// ff stores its state in a "ff" group with a "clocked_on" control pin, latch in a "latch" group with an "enable"
	const char *group = spec.is_latch ? "latch" : "ff";
	const char *ctrl_attr = spec.is_latch ? "enable" : "clocked_on";

	for (auto cell : cells)
	{
		if (is_dont_use(cell, dont_use_cells))
			continue;

		const LibertyAst *storage = cell->find(group);
		if (storage == nullptr)
			continue;

		std::string cell_ctrl_pin, cell_rst_pin, cell_set_pin, cell_clr_pin, cell_data_pin, cell_enable_pin;
		bool cell_ctrl_pol, cell_rst_pol, cell_set_pol, cell_clr_pol, cell_data_pol, cell_enable_pol;

		if (!parse_pin(cell, storage->find(ctrl_attr), cell_ctrl_pin, cell_ctrl_pol) || cell_ctrl_pol != spec.ctrlpol)
			continue;
		if (spec.is_latch) {
			if (!parse_pin(cell, storage->find("data_in"), cell_data_pin, cell_data_pol))
				continue;
		} else {
			if (!parse_next_state(warned_cells, cell, storage->find("next_state"), cell_data_pin, cell_data_pol, cell_enable_pin, cell_enable_pol) || (spec.dff_has_enable && (cell_enable_pin.empty() || cell_enable_pol != spec.dff_enapol)))
				continue;
		}

		std::map<std::string, char> this_cell_ports;
		this_cell_ports[cell_ctrl_pin] = spec.is_latch ? 'E' : 'C';

		if (spec.has_reset) {
			// a negated data path is propagated to the output, which requires negating the reset value
			const char *rst_attr = (spec.rstval == cell_data_pol) ? "preset" : "clear";
			if (!parse_pin(cell, storage->find(rst_attr), cell_rst_pin, cell_rst_pol) || cell_rst_pol != spec.rstpol)
				continue;
			this_cell_ports[cell_rst_pin] = 'R';
		}

		if (spec.has_sr) {
			if (!parse_pin(cell, storage->find("preset"), cell_set_pin, cell_set_pol))
				continue;
			if (!parse_pin(cell, storage->find("clear"), cell_clr_pin, cell_clr_pol))
				continue;
			if (!cell_data_pol) {
				// a negated data path is propagated to the output, which requires swapping set and reset
				std::swap(cell_set_pin, cell_clr_pin);
				std::swap(cell_set_pol, cell_clr_pol);
			}
			if (cell_set_pol != spec.setpol || cell_clr_pol != spec.clrpol)
				continue;
			this_cell_ports[cell_set_pin] = 'S';
			this_cell_ports[cell_clr_pin] = 'R';
		}

		if (spec.dff_has_enable)
			this_cell_ports[cell_enable_pin] = 'E';
		this_cell_ports[cell_data_pin] = 'D';

		find_better_cell(best, cell, storage, cell_data_pol, this_cell_ports);
	}

	if (best.cell != nullptr) {
		log("  cell %s (%s) is a direct match for cell type %s.\n", best.cell->args[0], best.rank.description(), ID::str(cell_type));
		cell_mappings[cell_type].cell_name = RTLIL::escape_id(best.cell->args[0]);
		cell_mappings[cell_type].ports = best.ports;
	}
}

static IdString port_name_ref(TwinePool &twines, char port)
{
	return twines.add(stringf("\\%c", port));
}

static void dfflibmap(cell_mappings_t &cell_mappings, RTLIL::Design *design, RTLIL::Module *module)
{
	log("Mapping DFF/DLATCH cells in module `%s':\n", module->name);

	dict<SigBit, pool<Cell*>> notmap;
	SigMap sigmap(module);

	std::vector<RTLIL::Cell*> cell_list;
	for (auto cell : module->cells()) {
		auto cats = StaticCellTypes::categories;
		if (cats.is_ff(cell->type) && !cats.is_stdcell(cell->type))
			log_error("Wide register cell type %s is not supported. "
					  "Convert netlist to gate-level first.\n", cell->type);

		if (design->selected(module, cell) && cell_mappings.count(cell->type) > 0)
			cell_list.push_back(cell);
		if (cell->type == ID($_NOT_))
			notmap[sigmap(cell->getPort(ID::A))].insert(cell);
	}

	auto &twines = module->twines();

	std::map<std::string, int> stats;
	for (auto cell : cell_list)
	{
		IdString cell_type = cell->type;
		IdString cell_name = cell->name;
		auto cell_connections = cell->connections();
		dict<RTLIL::IdString, RTLIL::Const> attributes = std::move(cell->attributes);

		module->remove(cell);

		cell_mapping &cm = cell_mappings[cell_type];
		RTLIL::Cell *new_cell = module->addCell(cell_name, twines.add(cm.cell_name));

		new_cell->attributes = std::move(attributes);

		bool has_q = false, has_qn = false;
		for (auto &port : cm.ports) {
			if (port.second == 'Q') has_q = true;
			if (port.second == 'q') has_qn = true;
		}

		for (auto &port : cm.ports) {
			RTLIL::SigSpec sig;
			if ('A' <= port.second && port.second <= 'Z') {
				sig = cell_connections[port_name_ref(twines, port.second)];
			} else
			if (port.second == 'q') {
				RTLIL::SigSpec old_sig = cell_connections[port_name_ref(twines, char(port.second - ('a' - 'A')))];
				sig = module->addWire(NEW_ID, GetSize(old_sig));
				if (has_q && has_qn) {
					for (auto &it : notmap[sigmap(old_sig)]) {
						module->connect(it->getPort(ID::Y), sig);
						it->setPort(ID::Y, module->addWire(NEW_ID, GetSize(old_sig)));
					}
				} else {
					module->addNotGate(NEW_ID, sig, old_sig);
				}
			} else
			if ('a' <= port.second && port.second <= 'z') {
				sig = cell_connections[port_name_ref(twines, char(port.second - ('a' - 'A')))];
				sig = module->NotGate(NEW_ID, sig);
			} else
			if (port.second == '0' || port.second == '1') {
				sig = RTLIL::SigSpec(port.second == '0' ? 0 : 1, 1);
			} else
			if (port.second == 0) {
				sig = module->addWire(NEW_ID);
			} else
				log_abort();
			new_cell->setPort("\\" + port.first, sig);
		}

		stats[stringf("%s cells to %s cells", twines.str(cell_type), new_cell->type.str())]++;
	}

	for (auto &stat: stats)
		log("  mapped %d %s.\n", stat.second, stat.first);
}

struct DfflibmapPass : public Pass {
	DfflibmapPass() : Pass("dfflibmap", "technology mapping of flip-flops and latches") { }
	void help() override
	{
		log("\n");
		log("    dfflibmap [-prepare] [-map-only] [-info] [-dont_use <cell_name>] -liberty <file> [selection]\n");
		log("\n");
		log("Map internal flip-flop and latch cells to the flip-flop and latch cells in the\n");
		log("technology library specified in the given liberty files.\n");
		log("\n");
		log("This pass may add inverters as needed. Therefore it is recommended to\n");
		log("first run this pass and then map the logic paths to the target technology.\n");
		log("\n");
		log("When called with -prepare, this command will convert the internal FF/latch cells\n");
		log("to the internal cell types that best match the cells found in the given\n");
		log("liberty file, but won't actually map them to the target cells.\n");
		log("\n");
		log("When called with -map-only, this command will only map internal cell\n");
		log("types that are already of exactly the right type to match the target\n");
		log("cells, leaving remaining internal cells untouched.\n");
		log("\n");
		log("When called with -info, this command will only print the target cell\n");
		log("list, along with their associated internal cell types, and the arguments\n");
		log("that would be passed to the dfflegalize pass.  The design will not be\n");
		log("changed.\n");
		log("\n");
		log("When called with -dont_use, this command will not map to the specified cell\n");
		log("name as an alternative to setting the dont_use property in the Liberty file.\n");
		log("This argument can be called multiple times with different cell names. This\n");
		log("argument also supports simple glob patterns in the cell name.\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) override
	{
		log_header(design, "Executing DFFLIBMAP pass (mapping DFF/DLATCH cells to sequential cells from liberty file).\n");
		log_push();

		bool prepare_mode = false;
		bool map_only_mode = false;
		bool info_mode = false;

		std::vector<std::string> liberty_files;
		std::vector<std::string> dont_use_cells;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			std::string arg = args[argidx];
			if (arg == "-liberty" && argidx+1 < args.size()) {
				append_globbed(liberty_files, args[++argidx]);
				continue;
			}
			if (arg == "-prepare") {
				prepare_mode = true;
				continue;
			}
			if (arg == "-map-only") {
				map_only_mode = true;
				continue;
			}
			if (arg == "-info") {
				info_mode = true;
				continue;
			}
			if (arg == "-dont_use" && argidx+1 < args.size()) {
				dont_use_cells.push_back(args[++argidx]);
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		int modes = 0;
		if (prepare_mode)
			modes++;
		if (map_only_mode)
			modes++;
		if (info_mode)
			modes++;
		if (modes > 1)
			log_cmd_error("Only one of -prepare, -map-only, or -info options should be given!\n");

		if (liberty_files.empty())
			log_cmd_error("Missing `-liberty liberty_file' option!\n");

		LibertyMergedCells merged;
		for (auto path : liberty_files) {
			std::istream* f = uncompressed(path);
			LibertyParser p(*f, path, liberty_synth_filter);
			merged.merge(p);
			delete f;
		}

		cell_mappings_t cell_mappings;
		CellFinder finder(merged.cells, dont_use_cells, cell_mappings);

		const std::vector<FfType> ff_types = {
			{ID($_DFF_N_), {}},
			{ID($_DFF_P_), {.ctrlpol=true}},

			{ID($_DFF_NN0_), {.has_reset=true}},
			{ID($_DFF_NN1_), {.has_reset=true, .rstval=true}},
			{ID($_DFF_NP0_), {.has_reset=true, .rstpol=true}},
			{ID($_DFF_NP1_), {.has_reset=true, .rstpol=true, .rstval=true}},
			{ID($_DFF_PN0_), {.ctrlpol=true, .has_reset=true}},
			{ID($_DFF_PN1_), {.ctrlpol=true, .has_reset=true, .rstval=true}},
			{ID($_DFF_PP0_), {.ctrlpol=true, .has_reset=true, .rstpol=true}},
			{ID($_DFF_PP1_), {.ctrlpol=true, .has_reset=true, .rstpol=true, .rstval=true}},

			{ID($_DFFE_NN_), {.dff_has_enable=true}},
			{ID($_DFFE_NP_), {.dff_has_enable=true, .dff_enapol=true}},
			{ID($_DFFE_PN_), {.ctrlpol=true, .dff_has_enable=true}},
			{ID($_DFFE_PP_), {.ctrlpol=true, .dff_has_enable=true, .dff_enapol=true}},

			{ID($_DFFSR_NNN_), {.has_sr=true}},
			{ID($_DFFSR_NNP_), {.has_sr=true, .clrpol=true}},
			{ID($_DFFSR_NPN_), {.has_sr=true, .setpol=true}},
			{ID($_DFFSR_NPP_), {.has_sr=true, .setpol=true, .clrpol=true}},
			{ID($_DFFSR_PNN_), {.ctrlpol=true, .has_sr=true}},
			{ID($_DFFSR_PNP_), {.ctrlpol=true, .has_sr=true, .clrpol=true}},
			{ID($_DFFSR_PPN_), {.ctrlpol=true, .has_sr=true, .setpol=true}},
			{ID($_DFFSR_PPP_), {.ctrlpol=true, .has_sr=true, .setpol=true, .clrpol=true}},

			{ID($_DLATCH_N_), {.is_latch=true}},
			{ID($_DLATCH_P_), {.is_latch=true, .ctrlpol=true}},

			{ID($_DLATCH_NN0_), {.is_latch=true, .has_reset=true}},
			{ID($_DLATCH_NN1_), {.is_latch=true, .has_reset=true, .rstval=true}},
			{ID($_DLATCH_NP0_), {.is_latch=true, .has_reset=true, .rstpol=true}},
			{ID($_DLATCH_NP1_), {.is_latch=true, .has_reset=true, .rstpol=true, .rstval=true}},
			{ID($_DLATCH_PN0_), {.is_latch=true, .ctrlpol=true, .has_reset=true}},
			{ID($_DLATCH_PN1_), {.is_latch=true, .ctrlpol=true, .has_reset=true, .rstval=true}},
			{ID($_DLATCH_PP0_), {.is_latch=true, .ctrlpol=true, .has_reset=true, .rstpol=true}},
			{ID($_DLATCH_PP1_), {.is_latch=true, .ctrlpol=true, .has_reset=true, .rstpol=true, .rstval=true}},

			{ID($_DLATCHSR_NNN_), {.is_latch=true, .has_sr=true}},
			{ID($_DLATCHSR_NNP_), {.is_latch=true, .has_sr=true, .clrpol=true}},
			{ID($_DLATCHSR_NPN_), {.is_latch=true, .has_sr=true, .setpol=true}},
			{ID($_DLATCHSR_NPP_), {.is_latch=true, .has_sr=true, .setpol=true, .clrpol=true}},
			{ID($_DLATCHSR_PNN_), {.is_latch=true, .ctrlpol=true, .has_sr=true}},
			{ID($_DLATCHSR_PNP_), {.is_latch=true, .ctrlpol=true, .has_sr=true, .clrpol=true}},
			{ID($_DLATCHSR_PPN_), {.is_latch=true, .ctrlpol=true, .has_sr=true, .setpol=true}},
			{ID($_DLATCHSR_PPP_), {.is_latch=true, .ctrlpol=true, .has_sr=true, .setpol=true, .clrpol=true}},
		};

		for (auto &ff : ff_types)
			finder.find(ff.type, ff.spec);

		log("  final dff/dlatch cell mappings:\n");
		for (auto &ff : ff_types)
			logmap(cell_mappings, ff.type);

		if (!map_only_mode) {
			std::string dfflegalize_cmd = "dfflegalize";
			for (auto it : cell_mappings)
				dfflegalize_cmd += stringf(" -cell %s 01", ID::str(it.first));
			dfflegalize_cmd += " t:$_DFF* t:$_SDFF* t:$_DLATCH*";
			if (info_mode) {
				log("dfflegalize command line: %s\n", dfflegalize_cmd);
			} else {
				Pass::call(design, dfflegalize_cmd);
			}
		}

		if (!prepare_mode && !info_mode) {
			for (auto module : design->selected_modules())
				if (!module->get_blackbox_attribute())
					dfflibmap(cell_mappings, design, module);
		}

		log_pop();
	}
} DfflibmapPass;

PRIVATE_NAMESPACE_END