Coverage Report

Created: 2026-11-07 16:24

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/mapping/generic/generic_mapping.cpp
Line
Count
Source (jump to first uncovered line)
1
#include "labneura/eda/netlist.h"
2
3
#include "behavioral_synthesis.h"
4
5
#include <algorithm>
6
#include <cctype>
7
#include <cstdint>
8
#include <iterator>
9
#include <optional>
10
#include <regex>
11
#include <map>
12
#include <set>
13
#include <stdexcept>
14
#include <string>
15
#include <unordered_map>
16
#include <unordered_set>
17
#include <utility>
18
#include <vector>
19
20
namespace labneura::eda {
21
namespace {
22
23
2.33k
bool is_identifier(const Expression& expression) {
24
2.33k
    return expression.get_kind() == ExpressionKind::Identifier;
25
2.33k
}
26
27
351
std::optional<bool> literal_value(const Expression& expression) {
28
351
    if (expression.get_kind() != ExpressionKind::Literal &&
29
351
        expression.get_kind() != ExpressionKind::Opaque) {
30
331
        return std::nullopt;
31
331
    }
32
20
    const auto source = expression.get_source();
33
20
    static const std::regex based_literal(
34
20
        R"(^\s*[0-9]+\s*'\s*[sS]?[bBoOdDhH]\s*[0-9a-fA-F_xXzZ?]+\s*$)");
35
20
    static const std::regex decimal(R"(^\s*([0-9]+)\s*$)");
36
20
    std::smatch decimal_match;
37
20
    const bool is_based = std::regex_match(source, based_literal);
38
20
    const bool is_decimal = std::regex_match(source, decimal_match, decimal);
39
20
    if (!is_based && !is_decimal) return std::nullopt;
40
20
    if (source.find_first_of("xXzZ?") != std::string::npos) {
41
1
        throw std::runtime_error(
42
1
            "scalar X/Z constants cannot be mapped to generic tie cells");
43
1
    }
44
19
    if (is_decimal) {
45
3
        return (std::stoull(decimal_match[1].str()) & 1U) != 0;
46
3
    }
47
16
    const auto apostrophe = source.find('\'');
48
16
    const auto base_position = source.find_first_of("bBoOdDhH", apostrophe);
49
16
    const auto digit_position = source.find_first_not_of(" \t", base_position + 1);
50
16
    const auto digits = source.substr(digit_position);
51
16
    const char base = static_cast<char>(
52
16
        std::tolower(static_cast<unsigned char>(source[base_position])));
53
16
    if (digits.empty()) return std::nullopt;
54
16
    if (base == 'd') return (std::stoull(digits) & 1U) != 0;
55
16
    const char last_digit = digits.back();
56
16
    return (std::isdigit(static_cast<unsigned char>(last_digit))
57
16
                ? (last_digit - '0') & 1
58
16
                : (std::tolower(static_cast<unsigned char>(last_digit)) - 'a' + 10) &
59
0
                      1) != 0;
60
16
}
61
62
13
bool literal_bit_value(const Expression& expression, std::size_t bit) {
63
13
    std::string source;
64
71
    for (const char character : expression.get_source()) {
65
71
        if (character != '_' && !std::isspace(
66
71
                                    static_cast<unsigned char>(character))) {
67
71
            source.push_back(character);
68
71
        }
69
71
    }
70
13
    if (source.find_first_of("xXzZ?") != std::string::npos) {
71
1
        throw std::runtime_error(
72
1
            "vector X/Z constants cannot be mapped to generic tie cells");
73
1
    }
74
12
    const auto apostrophe = source.find('\'');
75
12
    std::size_t base = 10;
76
12
    std::string digits = source;
77
12
    if (apostrophe != std::string::npos) {
78
12
        const auto base_position =
79
12
            source.find_first_of("bBoOdDhH", apostrophe + 1);
80
12
        if (base_position == std::string::npos) {
81
0
            throw std::runtime_error(
82
0
                "unsupported vector constant in generic mapping");
83
0
        }
84
12
        switch (static_cast<char>(std::tolower(
85
12
            static_cast<unsigned char>(source[base_position])))) {
86
4
            case 'b': base = 2; break;
87
4
            case 'o': base = 8; break;
88
0
            case 'd': base = 10; break;
89
4
            case 'h': base = 16; break;
90
0
            default:
91
0
                throw std::runtime_error(
92
0
                    "unsupported vector constant in generic mapping");
93
12
        }
94
12
        digits = source.substr(base_position + 1);
95
12
    }
96
12
    if (digits.empty()) {
97
0
        throw std::runtime_error("unsupported vector constant in generic mapping");
98
0
    }
99
12
    const auto value = std::stoull(digits, nullptr, static_cast<int>(base));
100
12
    return bit < sizeof(value) * 8 &&
101
12
           (value & (std::uint64_t{1} << bit)) != 0;
102
12
}
103
104
785
std::string pin_name(std::size_t index) {
105
785
    if (index >= 26) {
106
0
        throw std::runtime_error(
107
0
            "generic Boolean operator has more than 26 operands");
108
0
    }
109
785
    return std::string(1, static_cast<char>('A' + index));
110
785
}
111
112
std::string generic_type_for_operator(const std::string& op,
113
302
                                      std::size_t operand_count) {
114
302
    if (op == "&" || op == "&&") return "AND" + std::to_string(operand_count);
115
152
    if (op == "|" || op == "||") return "OR" + std::to_string(operand_count);
116
84
    if (op == "^") return "XOR" + std::to_string(operand_count);
117
0
    throw std::runtime_error("unsupported Boolean operator in generic mapping: " +
118
0
                             op);
119
84
}
120
121
std::optional<std::string> generic_type_for_primitive(
122
54
    const std::string& cell_type, std::size_t input_count) {
123
54
    if (cell_type == "pullup" || cell_type == "pulldown") {
124
2
        if (input_count != 0) {
125
0
            throw std::runtime_error(
126
0
                "primitive gate '" + cell_type + "' must not have inputs");
127
0
        }
128
2
        return cell_type == "pullup" ? "TIEHI" : "TIELO";
129
2
    }
130
52
    if (cell_type == "buf" || cell_type == "not") {
131
2
        if (input_count != 1) {
132
0
            throw std::runtime_error(
133
0
                "primitive gate '" + cell_type +
134
0
                "' must have exactly one input");
135
0
        }
136
2
        return cell_type == "buf" ? "BUF" : "INV";
137
2
    }
138
139
50
    std::string generic_family;
140
50
    if (cell_type == "and") generic_family = "AND";
141
31
    else if (cell_type == "nand") generic_family = "NAND";
142
29
    else if (cell_type == "or") generic_family = "OR";
143
17
    else if (cell_type == "nor") generic_family = "NOR";
144
16
    else if (cell_type == "xor") generic_family = "XOR";
145
12
    else if (cell_type == "xnor") generic_family = "XNOR";
146
11
    else return std::nullopt;
147
148
39
    if (input_count < 2) {
149
0
        throw std::runtime_error(
150
0
            "primitive gate '" + cell_type +
151
0
            "' must have at least two inputs");
152
0
    }
153
39
    return generic_family + std::to_string(input_count);
154
39
}
155
156
70
bool is_switch_level_primitive(const std::string& cell_type) {
157
70
    return cell_type == "cmos" || cell_type == "nmos" ||
158
70
           cell_type == "pmos" || cell_type == "rnmos" ||
159
70
           cell_type == "rpmos" || cell_type == "rcmos" ||
160
70
           cell_type == "tran" ||
161
70
           cell_type == "rtran" || cell_type == "tranif0" ||
162
70
           cell_type == "tranif1" || cell_type == "rtranif0" ||
163
70
           cell_type == "rtranif1";
164
70
}
165
166
struct GenericMapper {
167
    struct NetShape {
168
        std::size_t width;
169
        std::optional<std::int64_t> left;
170
        std::optional<std::int64_t> right;
171
    };
172
173
    std::vector<Net> nets;
174
    std::vector<Instance> instances;
175
    std::unordered_set<std::string> used_names;
176
    std::unordered_map<std::string, NetShape> net_shapes;
177
    std::size_t next_index = 0;
178
179
125
    explicit GenericMapper(const Module& module) {
180
629
        for (const auto& net : module.get_nets()) {
181
629
            used_names.insert(net.get_name());
182
629
            net_shapes.emplace(
183
629
                net.get_name(),
184
629
                NetShape{net.get_width(), net.get_left_index(),
185
629
                         net.get_right_index()});
186
629
        }
187
125
        for (const auto& instance : module.get_instances()) {
188
67
            used_names.insert(instance.get_name());
189
67
        }
190
125
    }
191
192
1.38k
    std::string unique_name(const std::string& prefix) {
193
1.38k
        std::string name;
194
1.38k
        do {
195
1.38k
            name = prefix + std::to_string(next_index++);
196
1.38k
        } while (!used_names.insert(name).second);
197
1.38k
        return name;
198
1.38k
    }
199
200
187
    std::size_t net_width(const std::string& name) const {
201
187
        const auto net = net_shapes.find(name);
202
187
        return net == net_shapes.end() ? 1 : net->second.width;
203
187
    }
204
205
    std::string bit_reference(const std::string& name, std::size_t width,
206
299
                              std::size_t bit) const {
207
299
        if (width == 1) return name;
208
299
        const auto net = net_shapes.find(name);
209
299
        if (net == net_shapes.end() || net->second.width != width ||
210
299
            !net->second.left || !net->second.right) {
211
0
            throw std::runtime_error(
212
0
                "generic mapping cannot resolve vector bit '" + name + "'");
213
0
        }
214
299
        const auto index =
215
299
            *net->second.left > *net->second.right
216
299
                ? *net->second.right + static_cast<std::int64_t>(bit)
217
299
                : *net->second.right - static_cast<std::int64_t>(bit);
218
299
        return name + "[" + std::to_string(index) + "]";
219
299
    }
220
221
    std::string lower_vector_operand(const Expression& expression,
222
58
                                     std::size_t bit, std::size_t width) {
223
58
        if (is_identifier(expression)) {
224
54
            if (expression.get_width() != width) {
225
0
                throw std::runtime_error(
226
0
                    "generic mapping does not support vector operands with "
227
0
                    "different widths");
228
0
            }
229
54
            return bit_reference(expression.get_source(), width, bit);
230
54
        }
231
4
        if (expression.get_kind() == ExpressionKind::BitSelect &&
232
4
            expression.get_width() == 1 && width == 1) {
233
0
            return expression.get_source();
234
0
        }
235
4
        if (expression.get_width() != width) {
236
0
            throw std::runtime_error(
237
0
                "generic mapping does not support vector operands with "
238
0
                "different widths");
239
0
        }
240
241
4
        const auto temporary = unique_name("__generic_net");
242
4
        nets.emplace_back(temporary, NetType::Internal);
243
4
        lower_vector_bit(expression, bit, temporary, width);
244
4
        return temporary;
245
4
    }
246
247
    void lower_vector_bit(const Expression& expression, std::size_t bit,
248
                          const std::string& destination,
249
48
                          std::size_t width) {
250
48
        if (expression.get_width() != width) {
251
0
            throw std::runtime_error(
252
0
                "generic mapping does not support vector expressions with "
253
0
                "different widths");
254
0
        }
255
48
        if (expression.get_kind() == ExpressionKind::Literal) {
256
13
            add_cell(literal_bit_value(expression, bit) ? "TIEHI" : "TIELO",
257
13
                     {}, destination);
258
13
            return;
259
13
        }
260
35
        if (expression.get_kind() == ExpressionKind::Opaque &&
261
35
            expression.get_value() == "implicit_conversion" &&
262
35
            expression.get_operands().size() == 1) {
263
4
            const auto& operand = expression.get_operands().front();
264
4
            if (operand.get_width() < width) {
265
1
                throw std::runtime_error(
266
1
                    "generic mapping does not support vector sign or zero extension");
267
1
            }
268
3
            lower_vector_bit(operand, bit, destination, operand.get_width());
269
3
            return;
270
4
        }
271
31
        const auto& operands = expression.get_operands();
272
31
        if (expression.get_kind() == ExpressionKind::Binary &&
273
31
            (expression.get_value() == "&" || expression.get_value() == "|" ||
274
23
             expression.get_value() == "^") &&
275
31
            operands.size() == 2) {
276
23
            const auto left = lower_vector_operand(operands[0], bit, width);
277
23
            const auto right = lower_vector_operand(operands[1], bit, width);
278
23
            add_cell(generic_type_for_operator(expression.get_value(), 2),
279
23
                     {{"A", left}, {"B", right}}, destination);
280
23
            return;
281
23
        }
282
8
        if (expression.get_kind() == ExpressionKind::Unary &&
283
8
            expression.get_value() == "~" && operands.size() == 1) {
284
4
            const auto operand =
285
4
                lower_vector_operand(operands.front(), bit, width);
286
4
            add_cell("INV", {{"A", operand}}, destination);
287
4
            return;
288
4
        }
289
4
        if (expression.get_kind() == ExpressionKind::Conditional &&
290
4
            operands.size() == 3 && operands[0].get_width() == 1) {
291
4
            const auto select_name = unique_name("__generic_net");
292
4
            const auto select =
293
4
                lower(operands[0], select_name);
294
4
            if (!select) {
295
0
                throw std::runtime_error(
296
0
                    "conditional vector select has no supported generic mapping");
297
0
            }
298
4
            if (*select == select_name) {
299
0
                nets.emplace_back(*select, NetType::Internal);
300
0
            }
301
4
            const auto when_true =
302
4
                lower_vector_operand(operands[1], bit, width);
303
4
            const auto when_false =
304
4
                lower_vector_operand(operands[2], bit, width);
305
4
            add_cell("MUX2",
306
4
                     {{"S", *select}, {"A1", when_true},
307
4
                      {"A0", when_false}},
308
4
                     destination);
309
4
            return;
310
4
        }
311
0
        throw std::runtime_error(
312
0
            "vector expression '" + expression.get_source() +
313
0
            "' has no supported generic mapping");
314
4
    }
315
316
    void lower_vector_assignment(const Expression& expression,
317
                                 const std::string& destination,
318
13
                                 std::size_t output_width) {
319
13
        const auto expression_width = expression.get_width();
320
13
        if (expression_width == 0 || output_width == 0 ||
321
13
            expression_width < output_width) {
322
0
            throw std::runtime_error(
323
0
                "generic mapping does not support mismatched vector assignment widths");
324
0
        }
325
326
13
        const auto bits = output_width;
327
150
        for (std::size_t bit = 0; bit < bits; ++bit) {
328
137
            const auto target = output_width == 1
329
137
                                    ? destination
330
137
                                    : bit_reference(destination, output_width,
331
137
                                                    bit);
332
137
            if (expression_width > 1 &&
333
137
                !is_identifier(expression)) {
334
41
                lower_vector_bit(expression, bit, target, expression_width);
335
41
                continue;
336
41
            }
337
338
96
            const auto source =
339
96
                expression_width == 1
340
96
                    ? lower(expression, target)
341
96
                    : std::optional<std::string>(
342
96
                          bit_reference(expression.get_source(),
343
96
                                        expression_width, bit));
344
96
            if (!source) {
345
0
                throw std::runtime_error(
346
0
                    "continuous assignment '" + expression.get_source() +
347
0
                    "' has no supported generic mapping");
348
0
            }
349
96
            if (*source != target) {
350
96
                add_cell("BUF", {{"A", *source}}, target);
351
96
            }
352
96
        }
353
13
    }
354
355
    void add_cell(std::string type, std::vector<PinConnection> connections,
356
509
                  const std::string& output) {
357
509
        connections.emplace_back("Y", output);
358
509
        instances.emplace_back(unique_name("__generic_inst"), std::move(type),
359
509
                               std::move(connections));
360
509
    }
361
362
    void lower_user_defined_primitive(const Instance& instance,
363
1
                                      std::vector<Net>& output_nets) {
364
1
        if (instance.is_sequential_primitive()) {
365
0
            throw std::runtime_error(
366
0
                "generic mapping does not support sequential user-defined "
367
0
                "primitive '" +
368
0
                instance.get_cell_type() + "'");
369
0
        }
370
371
1
        const auto& connections = instance.get_connections();
372
1
        const auto output_connection = std::find_if(
373
1
            connections.begin(), connections.end(),
374
1
            [](const PinConnection& connection) {
375
1
                return connection.get_pin() == "Y";
376
1
            });
377
1
        std::vector<std::string> input_nets;
378
1
        input_nets.reserve(connections.size());
379
3
        for (const auto& connection : connections) {
380
3
            if (connection.get_pin() == "Y") {
381
1
                if (net_width(connection.get_net()) != 1) {
382
0
                    throw std::runtime_error(
383
0
                        "generic mapping does not support vector user-defined "
384
0
                        "primitive '" +
385
0
                        instance.get_cell_type() + "'");
386
0
                }
387
2
            } else {
388
2
                if (net_width(connection.get_net()) != 1) {
389
0
                    throw std::runtime_error(
390
0
                        "generic mapping does not support vector user-defined "
391
0
                        "primitive '" +
392
0
                        instance.get_cell_type() + "'");
393
0
                }
394
2
                input_nets.push_back(connection.get_net());
395
2
            }
396
3
        }
397
1
        if (output_connection == connections.end() || input_nets.empty() ||
398
1
            input_nets.size() > 16 || instance.get_primitive_table().empty()) {
399
0
            throw std::runtime_error(
400
0
                "user-defined primitive '" + instance.get_cell_type() +
401
0
                "' has an unsupported port count or empty truth table");
402
0
        }
403
404
1
        const std::size_t combinations =
405
1
            std::size_t{1} << input_nets.size();
406
1
        std::vector<bool> covered(combinations, false);
407
1
        std::vector<bool> values(combinations, false);
408
1
        std::set<std::string> product_terms;
409
4
        for (const auto& row : instance.get_primitive_table()) {
410
4
            if (row.inputs.size() != input_nets.size() ||
411
4
                (row.output != '0' && row.output != '1')) {
412
0
                throw std::runtime_error(
413
0
                    "user-defined primitive '" + instance.get_cell_type() +
414
0
                    "' uses an unsupported UDP table symbol");
415
0
            }
416
20
            for (std::size_t combination = 0; combination < combinations;
417
16
                 ++combination) {
418
16
                bool matches = true;
419
28
                for (std::size_t index = 0; index < input_nets.size(); ++index) {
420
24
                    const char symbol = static_cast<char>(std::tolower(
421
24
                        static_cast<unsigned char>(row.inputs[index])));
422
24
                    const bool input =
423
24
                        (combination & (std::size_t{1} << index)) != 0;
424
24
                    if ((symbol == '0' && input) ||
425
24
                        (symbol == '1' && !input)) {
426
12
                        matches = false;
427
12
                        break;
428
12
                    }
429
12
                    if (symbol != '0' && symbol != '1' && symbol != '?' &&
430
12
                        symbol != 'b') {
431
0
                        throw std::runtime_error(
432
0
                            "user-defined primitive '" +
433
0
                            instance.get_cell_type() +
434
0
                            "' uses an unsupported UDP input symbol");
435
0
                    }
436
12
                }
437
16
                if (!matches) continue;
438
4
                const bool output = row.output == '1';
439
4
                if (covered[combination] && values[combination] != output) {
440
0
                    throw std::runtime_error(
441
0
                        "user-defined primitive '" +
442
0
                        instance.get_cell_type() +
443
0
                        "' has conflicting UDP table rows");
444
0
                }
445
4
                covered[combination] = true;
446
4
                values[combination] = output;
447
4
            }
448
4
            if (row.output == '1') product_terms.insert(row.inputs);
449
4
        }
450
1
        if (std::find(covered.begin(), covered.end(), false) != covered.end()) {
451
0
            throw std::runtime_error(
452
0
                "user-defined primitive '" + instance.get_cell_type() +
453
0
                "' has unspecified UDP outputs that cannot be mapped");
454
0
        }
455
1
        const auto output = output_connection->get_net();
456
1
        if (std::find(values.begin(), values.end(), false) == values.end()) {
457
0
            add_cell("TIEHI", {}, output);
458
0
            return;
459
0
        }
460
1
        if (product_terms.empty()) {
461
0
            add_cell("TIELO", {}, output);
462
0
            return;
463
0
        }
464
465
1
        std::vector<std::string> inverted_inputs(input_nets.size());
466
1
        std::vector<std::string> terms;
467
1
        terms.reserve(product_terms.size());
468
2
        for (const auto& pattern : product_terms) {
469
2
            std::vector<std::string> literals;
470
6
            for (std::size_t index = 0; index < input_nets.size(); ++index) {
471
4
                const auto symbol = static_cast<char>(std::tolower(
472
4
                    static_cast<unsigned char>(pattern[index])));
473
4
                if (symbol == '?' || symbol == 'b') continue;
474
4
                if (symbol == '1') {
475
2
                    literals.push_back(input_nets[index]);
476
2
                    continue;
477
2
                }
478
2
                if (inverted_inputs[index].empty()) {
479
2
                    inverted_inputs[index] = unique_name("__generic_net");
480
2
                    output_nets.emplace_back(inverted_inputs[index],
481
2
                                             NetType::Internal);
482
2
                    add_cell("INV", {{"A", input_nets[index]}},
483
2
                             inverted_inputs[index]);
484
2
                }
485
2
                literals.push_back(inverted_inputs[index]);
486
2
            }
487
488
2
            if (literals.empty()) {
489
0
                const auto constant = unique_name("__generic_net");
490
0
                output_nets.emplace_back(constant, NetType::Internal);
491
0
                add_cell("TIEHI", {}, constant);
492
0
                terms.push_back(constant);
493
2
            } else if (literals.size() == 1) {
494
0
                terms.push_back(literals.front());
495
2
            } else {
496
2
                const auto term = unique_name("__generic_net");
497
2
                output_nets.emplace_back(term, NetType::Internal);
498
2
                std::vector<PinConnection> term_inputs;
499
6
                for (std::size_t index = 0; index < literals.size(); ++index) {
500
4
                    term_inputs.emplace_back(pin_name(index), literals[index]);
501
4
                }
502
2
                add_cell("AND" + std::to_string(literals.size()),
503
2
                         std::move(term_inputs), term);
504
2
                terms.push_back(term);
505
2
            }
506
2
        }
507
508
1
        if (terms.size() == 1) {
509
0
            add_cell("BUF", {{"A", terms.front()}}, output);
510
0
            return;
511
0
        }
512
1
        std::vector<PinConnection> sum_inputs;
513
3
        for (std::size_t index = 0; index < terms.size(); ++index) {
514
2
            sum_inputs.emplace_back(pin_name(index), terms[index]);
515
2
        }
516
1
        add_cell("OR" + std::to_string(terms.size()), std::move(sum_inputs),
517
1
                 output);
518
1
    }
519
520
    bool collect_associative(const Expression& expression,
521
                             const std::string& op,
522
1.27k
                             std::vector<const Expression*>& operands) {
523
1.27k
        if (expression.get_kind() == ExpressionKind::Binary &&
524
1.27k
            expression.get_value() == op &&
525
1.27k
            expression.get_operands().size() == 2) {
526
500
            return collect_associative(expression.get_operands()[0], op,
527
500
                                        operands) &&
528
500
                   collect_associative(expression.get_operands()[1], op,
529
500
                                        operands);
530
500
        }
531
779
        operands.push_back(&expression);
532
779
        return true;
533
1.27k
    }
534
535
280
    bool is_supported_operator(const std::string& op) const {
536
280
        return op == "&" || op == "&&" || op == "|" || op == "||" ||
537
280
               op == "^";
538
280
    }
539
540
    std::optional<std::string> lower(const Expression& expression,
541
1.03k
                                     const std::string& destination) {
542
1.03k
        if (expression.get_kind() == ExpressionKind::Opaque &&
543
1.03k
            expression.get_value() == "implicit_conversion" &&
544
1.03k
            expression.get_operands().size() == 1) {
545
0
            const auto& operand = expression.get_operands().front();
546
0
            if (operand.get_width() == 1 ||
547
0
                operand.get_kind() == ExpressionKind::Literal) {
548
0
                return lower(operand, destination);
549
0
            }
550
0
            const auto signal =
551
0
                lower_vector_operand(operand, 0, operand.get_width());
552
0
            if (signal != destination) {
553
0
                add_cell("BUF", {{"A", signal}}, destination);
554
0
            }
555
0
            return destination;
556
0
        }
557
1.03k
        if (is_identifier(expression)) return expression.get_source();
558
352
        if (expression.get_kind() == ExpressionKind::BitSelect &&
559
352
            expression.get_operands().size() == 2) {
560
1
            const auto& base = expression.get_operands()[0];
561
1
            const auto& selector = expression.get_operands()[1];
562
1
            if (selector.get_kind() == ExpressionKind::Literal) {
563
0
                return expression.get_source();
564
0
            }
565
1
            const auto data_width = base.get_width();
566
1
            const auto selector_width = selector.get_width();
567
1
            if (!is_identifier(base) || !is_identifier(selector) ||
568
1
                data_width < 2 || selector_width == 0 ||
569
1
                selector_width >= sizeof(std::size_t) * 8 ||
570
1
                data_width != (std::size_t{1} << selector_width)) {
571
0
                return std::nullopt;
572
0
            }
573
574
1
            std::vector<std::string> values;
575
1
            values.reserve(data_width);
576
5
            for (std::size_t i = 0; i < data_width; ++i) {
577
4
                values.push_back(base.get_source() + "[" +
578
4
                                 std::to_string(i) + "]");
579
4
            }
580
3
            for (std::size_t level = 0; level < selector_width; ++level) {
581
2
                std::vector<std::string> next_values;
582
2
                next_values.reserve(values.size() / 2);
583
5
                for (std::size_t i = 0; i < values.size(); i += 2) {
584
3
                    const bool final_cell = values.size() == 2;
585
3
                    const auto output =
586
3
                        final_cell ? destination : unique_name("__generic_net");
587
3
                    if (!final_cell) nets.emplace_back(output, NetType::Internal);
588
3
                    add_cell(
589
3
                        "MUX2",
590
3
                        {{"A0", values[i]},
591
3
                         {"A1", values[i + 1]},
592
3
                         {"S", selector.get_source() + "[" +
593
3
                                   std::to_string(level) + "]"}},
594
3
                        output);
595
3
                    next_values.push_back(output);
596
3
                }
597
2
                values = std::move(next_values);
598
2
            }
599
1
            return destination;
600
1
        }
601
351
        if (const auto value = literal_value(expression)) {
602
19
            add_cell(*value ? "TIEHI" : "TIELO", {}, destination);
603
19
            return destination;
604
19
        }
605
332
        if (expression.get_kind() == ExpressionKind::Binary &&
606
332
            is_supported_operator(expression.get_value())) {
607
279
            std::vector<const Expression*> operands;
608
279
            if (!collect_associative(expression, expression.get_value(),
609
279
                                     operands)) {
610
0
                return std::nullopt;
611
0
            }
612
279
            if (operands.size() < 2) return std::nullopt;
613
279
            if ((expression.get_value() == "&&" ||
614
279
                 expression.get_value() == "||") &&
615
279
                std::any_of(operands.begin(), operands.end(),
616
0
                            [](const Expression* operand) {
617
0
                                return operand->get_width() != 1;
618
0
                            })) {
619
0
                return std::nullopt;
620
0
            }
621
279
            std::vector<PinConnection> connections;
622
1.05k
            for (std::size_t i = 0; i < operands.size(); ++i) {
623
779
                const auto signal = lower(*operands[i], unique_name("__generic_net"));
624
779
                if (!signal) return std::nullopt;
625
779
                if (*signal != operands[i]->get_source() ||
626
779
                    !is_identifier(*operands[i])) {
627
136
                    nets.emplace_back(*signal, NetType::Internal);
628
136
                }
629
779
                connections.emplace_back(pin_name(i), *signal);
630
779
            }
631
279
            add_cell(generic_type_for_operator(expression.get_value(),
632
279
                                               operands.size()),
633
279
                     std::move(connections), destination);
634
279
            return destination;
635
279
        }
636
53
        if (expression.get_kind() == ExpressionKind::Unary &&
637
53
            (expression.get_value() == "~" || expression.get_value() == "!") &&
638
53
            expression.get_operands().size() == 1) {
639
38
            const auto& operand = expression.get_operands().front();
640
38
            if (expression.get_value() == "!" && operand.get_width() != 1) {
641
0
                return std::nullopt;
642
0
            }
643
38
            const auto signal = lower(operand, unique_name("__generic_net"));
644
38
            if (!signal) return std::nullopt;
645
38
            if (!is_identifier(operand)) nets.emplace_back(*signal, NetType::Internal);
646
38
            add_cell("INV", {{"A", *signal}}, destination);
647
38
            return destination;
648
38
        }
649
15
        if (expression.get_kind() == ExpressionKind::Conditional &&
650
15
            expression.get_operands().size() == 3) {
651
13
            const auto& operands = expression.get_operands();
652
13
            if (std::any_of(operands.begin(), operands.end(),
653
39
                            [](const Expression& operand) {
654
39
                                return operand.get_width() != 1;
655
39
                            })) {
656
0
                return std::nullopt;
657
0
            }
658
13
            std::vector<std::string> signals;
659
39
            for (const auto& operand : operands) {
660
39
                const auto signal = lower(operand, unique_name("__generic_net"));
661
39
                if (!signal) return std::nullopt;
662
39
                if (!is_identifier(operand)) nets.emplace_back(*signal, NetType::Internal);
663
39
                signals.push_back(*signal);
664
39
            }
665
13
            add_cell("MUX2",
666
13
                     {{"S", signals[0]}, {"A1", signals[1]},
667
13
                      {"A0", signals[2]}},
668
13
                     destination);
669
13
            return destination;
670
13
        }
671
2
        return std::nullopt;
672
15
    }
673
};
674
675
}  // namespace
676
677
171
Module generic_map(const Module& rtl_module) {
678
171
    const auto map_module =
679
209
        [&](const auto& self, const Module& source) -> Module {
680
209
        std::vector<Module> child_modules;
681
209
        child_modules.reserve(source.get_child_modules().size());
682
209
        for (const auto& child : source.get_child_modules()) {
683
38
            child_modules.push_back(self(self, child));
684
38
        }
685
686
209
        Module mapped;
687
209
        const bool requires_behavioral_lowering =
688
209
            source.is_behavioral() ||
689
209
            std::any_of(source.get_assignments().begin(),
690
127
                        source.get_assignments().end(),
691
191
                        [](const ContinuousAssignment& assignment) {
692
191
                            return !is_identifier(
693
191
                                assignment.get_lhs_expression());
694
191
                        });
695
209
        if (requires_behavioral_lowering) {
696
84
            mapped = detail::lower_behavioral_rtl(
697
84
                source.parsed_context_, source.get_name(), {}, true);
698
84
            mapped = Module(mapped.get_name(), mapped.get_ports(),
699
84
                            mapped.get_nets(), mapped.get_instances(),
700
84
                            mapped.get_assignments(), mapped.is_behavioral(),
701
84
                            source.get_hierarchy_instance_name(),
702
84
                            mapped.get_child_modules());
703
125
        } else {
704
125
            GenericMapper mapper(source);
705
125
            std::vector<ContinuousAssignment> remaining_assignments;
706
707
189
            for (const auto& assignment : source.get_assignments()) {
708
189
                const auto& lhs = assignment.get_lhs_expression();
709
189
                if (!is_identifier(lhs)) {
710
0
                    throw std::runtime_error(
711
0
                        "generic mapping currently requires scalar identifier assignment targets: " +
712
0
                        assignment.get_lhs());
713
0
                }
714
189
                const auto& rhs = assignment.get_rhs_expression();
715
189
                if (lhs.get_width() > 1 || rhs.get_width() > 1) {
716
13
                    mapper.lower_vector_assignment(rhs, lhs.get_source(),
717
13
                                                   lhs.get_width());
718
13
                    continue;
719
13
                }
720
176
                const auto result =
721
176
                    mapper.lower(rhs, lhs.get_source());
722
176
                if (!result) {
723
1
                    throw std::runtime_error("continuous assignment '" +
724
1
                                             assignment.get_lhs() + " = " +
725
1
                                             assignment.get_rhs() +
726
1
                                             "' has no supported generic mapping");
727
1
                }
728
175
                if (*result != lhs.get_source()) {
729
9
                    mapper.add_cell("BUF", {{"A", *result}}, lhs.get_source());
730
9
                }
731
175
            }
732
733
124
            auto nets = source.get_nets();
734
124
            nets.insert(nets.end(),
735
124
                        std::make_move_iterator(mapper.nets.begin()),
736
124
                        std::make_move_iterator(mapper.nets.end()));
737
124
            auto instances = source.get_instances();
738
182
            for (std::size_t index = 0; index < instances.size();) {
739
71
                auto& instance = instances[index];
740
71
                const auto& cell_type = instance.get_cell_type();
741
71
                if (instance.is_user_defined_primitive()) {
742
1
                    mapper.lower_user_defined_primitive(instance, nets);
743
1
                    instances.erase(instances.begin() +
744
1
                                    static_cast<std::ptrdiff_t>(index));
745
1
                    continue;
746
1
                }
747
70
                if (is_switch_level_primitive(cell_type)) {
748
12
                    throw std::runtime_error(
749
12
                        "generic mapping does not support switch-level "
750
12
                        "primitive '" +
751
12
                        cell_type +
752
12
                        "'; use a synthesis flow with switch-level support");
753
12
                }
754
58
                const auto input_count = static_cast<std::size_t>(
755
58
                    std::count_if(
756
58
                        instance.get_connections().begin(),
757
58
                        instance.get_connections().end(),
758
176
                        [](const PinConnection& connection) {
759
176
                            return connection.get_pin() != "Y";
760
176
                        }));
761
58
                if (cell_type == "bufif0" || cell_type == "bufif1" ||
762
58
                    cell_type == "notif0" || cell_type == "notif1") {
763
4
                    if (input_count != 2) {
764
0
                        throw std::runtime_error(
765
0
                            "primitive gate '" + cell_type +
766
0
                            "' must have exactly two inputs");
767
0
                    }
768
4
                    const auto& connections = instance.get_connections();
769
4
                    const auto output = std::find_if(
770
4
                        connections.begin(), connections.end(),
771
4
                        [](const PinConnection& connection) {
772
4
                            return connection.get_pin() == "Y";
773
4
                        });
774
4
                    const auto data = std::find_if(
775
4
                        connections.begin(), connections.end(),
776
8
                        [](const PinConnection& connection) {
777
8
                            return connection.get_pin() == "A";
778
8
                        });
779
4
                    const auto enable = std::find_if(
780
4
                        connections.begin(), connections.end(),
781
12
                        [](const PinConnection& connection) {
782
12
                            return connection.get_pin() == "B";
783
12
                        });
784
4
                    if (output == connections.end() ||
785
4
                        data == connections.end() ||
786
4
                        enable == connections.end()) {
787
0
                        throw std::runtime_error(
788
0
                            "primitive gate '" + cell_type +
789
0
                            "' has invalid connections");
790
0
                    }
791
4
                    if (mapper.net_width(output->get_net()) != 1 ||
792
4
                        mapper.net_width(data->get_net()) != 1 ||
793
4
                        mapper.net_width(enable->get_net()) != 1) {
794
0
                        throw std::runtime_error(
795
0
                            "generic mapping does not support vector "
796
0
                            "tri-state primitive '" +
797
0
                            cell_type + "'");
798
0
                    }
799
800
4
                    std::string data_net = data->get_net();
801
4
                    std::string enable_net = enable->get_net();
802
4
                    if (cell_type == "notif0" || cell_type == "notif1") {
803
2
                        const auto inverted =
804
2
                            mapper.unique_name("__generic_net");
805
2
                        nets.emplace_back(inverted, NetType::Internal);
806
2
                        mapper.add_cell("INV", {{"A", data_net}}, inverted);
807
2
                        data_net = inverted;
808
2
                    }
809
4
                    if (cell_type == "bufif1" || cell_type == "notif1") {
810
2
                        const auto inverted =
811
2
                            mapper.unique_name("__generic_net");
812
2
                        nets.emplace_back(inverted, NetType::Internal);
813
2
                        mapper.add_cell("INV", {{"A", enable_net}}, inverted);
814
2
                        enable_net = inverted;
815
2
                    }
816
4
                    instance = Instance(
817
4
                        instance.get_name(), "TRIBUF",
818
4
                        {{"A", std::move(data_net)},
819
4
                         {"TE_B", std::move(enable_net)},
820
4
                         {"Y", output->get_net()}});
821
4
                    continue;
822
4
                }
823
54
                const auto generic_type = generic_type_for_primitive(
824
54
                    cell_type, input_count);
825
54
                if (generic_type) {
826
43
                    const auto& connections = instance.get_connections();
827
43
                    const auto output = std::find_if(
828
43
                        connections.begin(), connections.end(),
829
43
                        [](const PinConnection& connection) {
830
43
                            return connection.get_pin() == "Y";
831
43
                        });
832
43
                    if (output == connections.end()) {
833
0
                        throw std::runtime_error(
834
0
                            "primitive gate '" + cell_type +
835
0
                            "' has no output connection");
836
0
                    }
837
43
                    const auto output_width =
838
43
                        mapper.net_width(output->get_net());
839
129
                    for (const auto& connection : connections) {
840
129
                        const auto connection_width =
841
129
                            mapper.net_width(connection.get_net());
842
129
                        if (connection_width != output_width) {
843
1
                            throw std::runtime_error(
844
1
                                "generic mapping does not support mismatched "
845
1
                                "vector connections on primitive gate '" +
846
1
                                cell_type + "'");
847
1
                        }
848
129
                    }
849
42
                    if (output_width > 1) {
850
1
                        std::vector<Instance> bit_instances;
851
1
                        bit_instances.reserve(output_width);
852
5
                        for (std::size_t bit = 0; bit < output_width; ++bit) {
853
4
                            std::vector<PinConnection> bit_connections;
854
4
                            bit_connections.reserve(connections.size());
855
12
                            for (const auto& connection : connections) {
856
12
                                bit_connections.emplace_back(
857
12
                                    connection.get_pin(),
858
12
                                    mapper.bit_reference(connection.get_net(),
859
12
                                                         output_width, bit));
860
12
                            }
861
4
                            bit_instances.emplace_back(
862
4
                                mapper.unique_name(instance.get_name() +
863
4
                                                   "__bit"),
864
4
                                *generic_type, std::move(bit_connections));
865
4
                        }
866
1
                        instances.erase(instances.begin() +
867
1
                                        static_cast<std::ptrdiff_t>(index));
868
1
                        instances.insert(
869
1
                            instances.begin() +
870
1
                                static_cast<std::ptrdiff_t>(index),
871
1
                            std::make_move_iterator(bit_instances.begin()),
872
1
                            std::make_move_iterator(bit_instances.end()));
873
1
                        index += output_width;
874
1
                        continue;
875
1
                    }
876
41
                    instance = Instance(instance.get_name(),
877
41
                                        *generic_type,
878
41
                                        instance.get_connections());
879
41
                }
880
52
                ++index;
881
52
            }
882
111
            instances.insert(
883
111
                instances.end(),
884
111
                std::make_move_iterator(mapper.instances.begin()),
885
111
                std::make_move_iterator(mapper.instances.end()));
886
111
            mapped = Module(source.get_name(), source.get_ports(),
887
111
                            std::move(nets), std::move(instances),
888
111
                            std::move(remaining_assignments),
889
111
                            source.is_behavioral(),
890
111
                            source.get_hierarchy_instance_name(),
891
111
                            std::move(child_modules));
892
111
        }
893
894
195
        return mapped;
895
209
    };
896
897
171
    return map_module(map_module, rtl_module);
898
171
}
899
900
Module generic_map(const Project& project, const std::string& top,
901
11
                   const std::map<std::string, std::string>& parameters) {
902
11
    std::unordered_map<std::string, const Module*> by_name;
903
11
    std::unordered_set<std::string> instantiated;
904
95
    for (const auto& module : project.get_modules()) by_name[module.get_name()] = &module;
905
95
    for (const auto& module : project.get_modules()) {
906
159
        for (const auto& instance : module.get_instances()) {
907
159
            if (by_name.count(instance.get_cell_type())) {
908
159
                instantiated.insert(instance.get_cell_type());
909
159
            }
910
159
        }
911
95
    }
912
913
11
    std::string top_name = top;
914
11
    if (top_name.empty()) {
915
0
        for (const auto& module : project.get_modules()) {
916
0
            if (instantiated.count(module.get_name())) continue;
917
0
            if (!top_name.empty()) {
918
0
                throw std::runtime_error(
919
0
                    "project has several top-level modules; pass top=<module>");
920
0
            }
921
0
            top_name = module.get_name();
922
0
        }
923
0
        if (top_name.empty()) throw std::runtime_error("project has no top-level module");
924
0
    }
925
11
    const auto top_module = by_name.find(top_name);
926
11
    if (top_module == by_name.end()) {
927
1
        throw std::runtime_error("top module '" + top_name + "' not found in project");
928
1
    }
929
930
10
    if (parameters.empty()) {
931
7
        std::unordered_set<std::string> active_modules;
932
7
        const auto build_hierarchy =
933
7
            [&](const auto& self, const Module& source,
934
39
                const std::string& instance_name) -> Module {
935
39
            if (!active_modules.insert(source.get_name()).second) {
936
0
                throw std::runtime_error(
937
0
                    "recursive module hierarchy detected at '" +
938
0
                    source.get_name() + "'");
939
0
            }
940
941
39
            std::vector<Module> children;
942
39
            for (const auto& instance : source.get_instances()) {
943
32
                const auto child = by_name.find(instance.get_cell_type());
944
32
                if (child != by_name.end()) {
945
32
                    children.push_back(
946
32
                        self(self, *child->second, instance.get_name()));
947
32
                }
948
32
            }
949
950
39
            active_modules.erase(source.get_name());
951
39
            Module hierarchy_node(
952
39
                source.get_name(), source.get_ports(), source.get_nets(),
953
39
                source.get_instances(), source.get_assignments(),
954
39
                source.is_behavioral(), instance_name, std::move(children));
955
39
            hierarchy_node.parsed_context_ = source.parsed_context_;
956
39
            return hierarchy_node;
957
39
        };
958
7
        auto hierarchy =
959
7
            build_hierarchy(build_hierarchy, *top_module->second, {});
960
7
        hierarchy.parsed_context_ = project.parsed_context_;
961
7
        return generic_map(hierarchy);
962
7
    }
963
964
    // Parameter overrides use project-wide elaboration so the specialized
965
    // design reflects the selected top-level values.
966
3
    bool needs_lowering = !parameters.empty();
967
3
    std::vector<const Module*> pending{top_module->second};
968
3
    std::unordered_set<std::string> visited;
969
8
    while (!pending.empty()) {
970
5
        const Module* module = pending.back();
971
5
        pending.pop_back();
972
5
        if (!visited.insert(module->get_name()).second) continue;
973
5
        if (module->is_behavioral()) needs_lowering = true;
974
5
        for (const auto& instance : module->get_instances()) {
975
2
            const auto child = by_name.find(instance.get_cell_type());
976
2
            if (child == by_name.end()) continue;
977
2
            needs_lowering = true;
978
2
            pending.push_back(child->second);
979
2
        }
980
5
    }
981
3
    if (!needs_lowering) return generic_map(*top_module->second);
982
3
    return detail::lower_behavioral_rtl(project.parsed_context_, top_name,
983
3
                                        parameters, true);
984
3
}
985
986
}  // namespace labneura::eda