aboutsummaryrefslogtreecommitdiffstats
path: root/passes/fsm/fsm_recode.cc
blob: fa1ff48cc0f90d201e2cd71d0fc6ea0c80997d32 (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
/*
 *  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/log.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/consteval.h"
#include "kernel/celltypes.h"
#include "fsmdata.h"
#include <math.h>
#include <string.h>
#include <errno.h>

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

static void fm_set_fsm_print(RTLIL::Cell *cell, RTLIL::Module *module, FsmData &fsm_data, const char *prefix, FILE *f)
{
	std::string name = cell->parameters["\\NAME"].decode_string();

	fprintf(f, "set_fsm_state_vector {");
	for (int i = fsm_data.state_bits-1; i >= 0; i--)
		fprintf(f, " %s_reg[%d]", name[0] == '\\' ?  name.substr(1).c_str() : name.c_str(), i);
	fprintf(f, " } -name {%s_%s} {%s:/WORK/%s}\n", prefix, RTLIL::unescape_id(name).c_str(),
			prefix, RTLIL::unescape_id(module->name).c_str());

	fprintf(f, "set_fsm_encoding {");
	for (int i = 0; i < GetSize(fsm_data.state_table); i++) {
		fprintf(f, " s%d=2#", i);
		for (int j = GetSize(fsm_data.state_table[i].bits)-1; j >= 0; j--)
			fprintf(f, "%c", fsm_data.state_table[i].bits[j] == RTLIL::State::S1 ? '1' : '0');
	}
	fprintf(f, " } -name {%s_%s} {%s:/WORK/%s}\n",
			prefix, RTLIL::unescape_id(name).c_str(),
			prefix, RTLIL::unescape_id(module->name).c_str());
}

static void fsm_recode(RTLIL::Cell *cell, RTLIL::Module *module, FILE *fm_set_fsm_file, FILE *encfile, std::string default_encoding)
{
	std::string encoding = cell->attributes.count("\\fsm_encoding") ? cell->attributes.at("\\fsm_encoding").decode_string() : "auto";

	log("Recoding FSM `%s' from module `%s' using `%s' encoding:\n", cell->name.c_str(), module->name.c_str(), encoding.c_str());

	if (encoding != "none" && encoding != "user" && encoding != "one-hot" && encoding != "binary" && encoding != "auto") {
		log("  unknown encoding `%s': using auto instead.\n", encoding.c_str());
		encoding = "auto";
	}

	if (encoding == "none" || encoding == "user") {
		log("  nothing to do for encoding `%s'.\n", encoding.c_str());
		return;
	}

	FsmData fsm_data;
	fsm_data.copy_from_cell(cell);

	if (fm_set_fsm_file != NULL)
		fm_set_fsm_print(cell, module, fsm_data, "r", fm_set_fsm_file);

	if (encoding == "auto") {
		if (!default_encoding.empty())
			encoding = default_encoding;
		else
			encoding = GetSize(fsm_data.state_table) < 32 ? "one-hot" : "binary";
		log("  mapping auto encoding to `%s` for this FSM.\n", encoding.c_str());
	}

	if (encoding == "one-hot") {
		fsm_data.state_bits = fsm_data.state_table.size();
	} else
	if (encoding == "binary") {
		int new_num_state_bits = ceil_log2(fsm_data.state_table.size());
		if (fsm_data.state_bits == new_num_state_bits) {
			log("  existing encoding is already a packed binary encoding.\n");
			return;
		}
		fsm_data.state_bits = new_num_state_bits;
	} else
		log_error("FSM encoding `%s' is not supported!\n", encoding.c_str());

	if (encfile)
		fprintf(encfile, ".fsm %s %s\n", log_id(module), RTLIL::unescape_id(cell->parameters["\\NAME"].decode_string()).c_str());

	int state_idx_counter = fsm_data.reset_state >= 0 ? 1 : 0;
	for (int i = 0; i < int(fsm_data.state_table.size()); i++)
	{
		int state_idx = fsm_data.reset_state == i ? 0 : state_idx_counter++;
		RTLIL::Const new_code;

		if (encoding == "one-hot") {
			new_code = RTLIL::Const(RTLIL::State::Sa, fsm_data.state_bits);
			new_code.bits[state_idx] = RTLIL::State::S1;
		} else
		if (encoding == "binary") {
			new_code = RTLIL::Const(state_idx, fsm_data.state_bits);
		} else
			log_abort();

		log("  %s -> %s\n", fsm_data.state_table[i].as_string().c_str(), new_code.as_string().c_str());
		if (encfile)
			fprintf(encfile, ".map %s %s\n", fsm_data.state_table[i].as_string().c_str(), new_code.as_string().c_str());
		fsm_data.state_table[i] = new_code;
	}

	if (fm_set_fsm_file != NULL)
		fm_set_fsm_print(cell, module, fsm_data, "i", fm_set_fsm_file);

	fsm_data.copy_to_cell(cell);
}

struct FsmRecodePass : public Pass {
	FsmRecodePass() : Pass("fsm_recode", "recoding finite state machines") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    fsm_recode [options] [selection]\n");
		log("\n");
		log("This pass reassign the state encodings for FSM cells. At the moment only\n");
		log("one-hot encoding and binary encoding is supported.\n");

		log("    -encoding <type>\n");
		log("        specify the encoding scheme used for FSMs without the\n");
		log("        'fsm_encoding' attribute or with the attribute set to `auto'.\n");
		log("\n");
		log("    -fm_set_fsm_file <file>\n");
		log("        generate a file containing the mapping from old to new FSM encoding\n");
		log("        in form of Synopsys Formality set_fsm_* commands.\n");
		log("\n");
		log("    -encfile <file>\n");
		log("        write the mappings from old to new FSM encoding to a file in the\n");
		log("        following format:\n");
		log("\n");
		log("            .fsm <module_name> <state_signal>\n");
		log("            .map <old_bitpattern> <new_bitpattern>\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		FILE *fm_set_fsm_file = NULL;
		FILE *encfile = NULL;
		std::string default_encoding;

		log_header(design, "Executing FSM_RECODE pass (re-assigning FSM state encoding).\n");
		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++) {
			std::string arg = args[argidx];
			if (arg == "-fm_set_fsm_file" && argidx+1 < args.size() && fm_set_fsm_file == NULL) {
				fm_set_fsm_file = fopen(args[++argidx].c_str(), "w");
				if (fm_set_fsm_file == NULL)
					log_error("Can't open fm_set_fsm_file `%s' for writing: %s\n", args[argidx].c_str(), strerror(errno));
				continue;
			}
			if (arg == "-encfile" && argidx+1 < args.size() && encfile == NULL) {
				encfile = fopen(args[++argidx].c_str(), "w");
				if (encfile == NULL)
					log_error("Can't open encfile `%s' for writing: %s\n", args[argidx].c_str(), strerror(errno));
				continue;
			}
			if (arg == "-encoding" && argidx+1 < args.size() && default_encoding.empty()) {
				default_encoding = args[++argidx];
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto &mod_it : design->modules_)
			if (design->selected(mod_it.second))
				for (auto &cell_it : mod_it.second->cells_)
					if (cell_it.second->type == "$fsm" && design->selected(mod_it.second, cell_it.second))
						fsm_recode(cell_it.second, mod_it.second, fm_set_fsm_file, encfile, default_encoding);

		if (fm_set_fsm_file != NULL)
			fclose(fm_set_fsm_file);
		if (encfile != NULL)
			fclose(encfile);
	}
} FsmRecodePass;

PRIVATE_NAMESPACE_END
an> (arq) *arq = uq; return (0); } u = &uspace[0]; v = &vspace[0]; q = &qspace[0]; /* * Break dividend and divisor into digits in base B, then * count leading zeros to determine m and n. When done, we * will have: * u = (u[1]u[2]...u[m+n]) sub B * v = (v[1]v[2]...v[n]) sub B * v[1] != 0 * 1 < n <= 4 (if n = 1, we use a different division algorithm) * m >= 0 (otherwise u < v, which we already checked) * m + n = 4 * and thus * m = 4 - n <= 2 */ tmp.uq = uq; u[0] = 0; u[1] = HHALF(tmp.ul[H]); u[2] = LHALF(tmp.ul[H]); u[3] = HHALF(tmp.ul[L]); u[4] = LHALF(tmp.ul[L]); tmp.uq = vq; v[1] = HHALF(tmp.ul[H]); v[2] = LHALF(tmp.ul[H]); v[3] = HHALF(tmp.ul[L]); v[4] = LHALF(tmp.ul[L]); for (n = 4; v[1] == 0; v++) { if (--n == 1) { u_long rbj; /* r*B+u[j] (not root boy jim) */ digit q1, q2, q3, q4; /* * Change of plan, per exercise 16. * r = 0; * for j = 1..4: * q[j] = floor((r*B + u[j]) / v), * r = (r*B + u[j]) % v; * We unroll this completely here. */ t = v[2]; /* nonzero, by definition */ q1 = u[1] / t; rbj = COMBINE(u[1] % t, u[2]); q2 = rbj / t; rbj = COMBINE(rbj % t, u[3]); q3 = rbj / t; rbj = COMBINE(rbj % t, u[4]); q4 = rbj / t; if (arq) *arq = rbj % t; tmp.ul[H] = COMBINE(q1, q2); tmp.ul[L] = COMBINE(q3, q4); return (tmp.q); } } /* * By adjusting q once we determine m, we can guarantee that * there is a complete four-digit quotient at &qspace[1] when * we finally stop. */ for (m = 4 - n; u[1] == 0; u++) m--; for (i = 4 - m; --i >= 0;) q[i] = 0; q += 4 - m; /* * Here we run Program D, translated from MIX to C and acquiring * a few minor changes. * * D1: choose multiplier 1 << d to ensure v[1] >= B/2. */ d = 0; for (t = v[1]; t < B / 2; t <<= 1) d++; if (d > 0) { shl(&u[0], m + n, d); /* u <<= d */ shl(&v[1], n - 1, d); /* v <<= d */ } /* * D2: j = 0. */ j = 0; v1 = v[1]; /* for D3 -- note that v[1..n] are constant */ v2 = v[2]; /* for D3 */ do { register digit uj0, uj1, uj2; /* * D3: Calculate qhat (\^q, in TeX notation). * Let qhat = min((u[j]*B + u[j+1])/v[1], B-1), and * let rhat = (u[j]*B + u[j+1]) mod v[1]. * While rhat < B and v[2]*qhat > rhat*B+u[j+2], * decrement qhat and increase rhat correspondingly. * Note that if rhat >= B, v[2]*qhat < rhat*B. */ uj0 = u[j + 0]; /* for D3 only -- note that u[j+...] change */ uj1 = u[j + 1]; /* for D3 only */ uj2 = u[j + 2]; /* for D3 only */ if (uj0 == v1) { qhat = B; rhat = uj1; goto qhat_too_big; } else { u_long nn = COMBINE(uj0, uj1); qhat = nn / v1; rhat = nn % v1; } while (v2 * qhat > COMBINE(rhat, uj2)) { qhat_too_big: qhat--; if ((rhat += v1) >= B) break; } /* * D4: Multiply and subtract. * The variable `t' holds any borrows across the loop. * We split this up so that we do not require v[0] = 0, * and to eliminate a final special case. */ for (t = 0, i = n; i > 0; i--) { t = u[i + j] - v[i] * qhat - t; u[i + j] = LHALF(t); t = (B - HHALF(t)) & (B - 1); } t = u[j] - t; u[j] = LHALF(t); /* * D5: test remainder. * There is a borrow if and only if HHALF(t) is nonzero; * in that (rare) case, qhat was too large (by exactly 1). * Fix it by adding v[1..n] to u[j..j+n]. */ if (HHALF(t)) { qhat--; for (t = 0, i = n; i > 0; i--) { /* D6: add back. */ t += u[i + j] + v[i]; u[i + j] = LHALF(t); t = HHALF(t); } u[j] = LHALF(u[j] + t); } q[j] = qhat; } while (++j <= m); /* D7: loop on j. */ /* * If caller wants the remainder, we have to calculate it as * u[m..m+n] >> d (this is at most n digits and thus fits in * u[m+1..m+n], but we may need more source digits). */ if (arq) { if (d) { for (i = m + n; i > m; --i) u[i] = (u[i] >> d) | LHALF(u[i - 1] << (HALF_BITS - d)); u[i] = 0; } tmp.ul[H] = COMBINE(uspace[1], uspace[2]); tmp.ul[L] = COMBINE(uspace[3], uspace[4]); *arq = tmp.q; } tmp.ul[H] = COMBINE(qspace[1], qspace[2]); tmp.ul[L] = COMBINE(qspace[3], qspace[4]); return (tmp.q); } /* * Divide two signed quads. * ??? if -1/2 should produce -1 on this machine, this code is wrong * (Grzegorz Milos) Note for the above: -1/2 is 0. And so it should. */ s64 __divdi3(s64 a, s64 b) { u64 ua, ub, uq; int neg; if (a < 0) ua = -(u64)a, neg = 1; else ua = a, neg = 0; if (b < 0) ub = -(u64)b, neg ^= 1; else ub = b; uq = __qdivrem(ua, ub, (u64 *)0); return (neg ? -uq : uq); } /* * Divide two unsigned quads. */ u64 __udivdi3(a, b) u64 a, b; { return (__qdivrem(a, b, (u64 *)0)); } /* * Remainder of unsigned quad division */ u64 __umoddi3(u64 a, u64 b) { u64 rem; __qdivrem(a, b, &rem); return rem; } /* * Remainder of signed quad division. * The result of mod is not always equal to division * remainder. The following example shows the result for all * four possible cases: * 11 % 5 = 1 * -11 % 5 = 4 * 11 % -5 = -4 * -11 % -5 = -1 */ s64 __moddi3(s64 a, s64 b) { u64 ua, ub, urem; int neg1, neg2; if (a < 0) ua = -(u64)a, neg1 = 1; else ua = a, neg1 = 0; if (b < 0) ub = -(u64)b, neg2 = 1; else ub = b, neg2 = 0; __qdivrem(ua, ub, &urem); /* There 4 different cases: */ if (neg1) { if (neg2) return -urem; else return ub - urem; } else { if (neg2) return -ub + urem; else return urem; } } #endif /* BITS_PER_LONG == 32 */ unsigned long long parse_size_and_unit(char *s) { unsigned long long ret = simple_strtoull(s, &s, 0); switch (*s) { case 'G': case 'g': ret <<= 10; case 'M': case 'm': ret <<= 10; case 'K': case 'k': default: ret <<= 10; case 'B': case 'b': break; } return ret; } /* * Local variables: * mode: C * c-set-style: "BSD" * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: */