Coverage Report

Created: 2026-11-03 04:34

/home/runner/work/LabNeura/LabNeura/src/labneura/eda/mapping/generic/behavioral_synthesis.cpp
Line
Count
Source (jump to first uncovered line)
1
// Behavioral RTL synthesis: lowers an elaborated slang AST (always blocks,
2
// continuous assigns, generate blocks, memories, hierarchy) into a bit-level
3
// generic netlist (AND2/OR2/XOR2/INV/MUX2/DFF/TIE) that technology mapping
4
// can consume.
5
#include "labneura/eda/netlist.h"
6
7
#include "behavioral_synthesis.h"
8
#include "labneura/eda/parsed_verilog_context.h"
9
#include "bit_graph.h"
10
11
#include "slang/ast/Compilation.h"
12
#include "slang/ast/Symbol.h"
13
#include "slang/ast/symbols/AttributeSymbol.h"
14
#include "slang/ast/EvalContext.h"
15
#include "slang/ast/Statement.h"
16
#include "slang/ast/TimingControl.h"
17
#include "slang/ast/expressions/AssignmentExpressions.h"
18
#include "slang/ast/expressions/CallExpression.h"
19
#include "slang/ast/expressions/ConversionExpression.h"
20
#include "slang/ast/expressions/LiteralExpressions.h"
21
#include "slang/ast/expressions/MiscExpressions.h"
22
#include "slang/ast/expressions/OperatorExpressions.h"
23
#include "slang/ast/expressions/SelectExpressions.h"
24
#include "slang/ast/statements/ConditionalStatements.h"
25
#include "slang/ast/statements/LoopStatements.h"
26
#include "slang/ast/statements/MiscStatements.h"
27
#include "slang/ast/symbols/BlockSymbols.h"
28
#include "slang/ast/symbols/CompilationUnitSymbols.h"
29
#include "slang/ast/symbols/InstanceSymbols.h"
30
#include "slang/ast/symbols/MemberSymbols.h"
31
#include "slang/ast/symbols/PortSymbols.h"
32
#include "slang/ast/symbols/SubroutineSymbols.h"
33
#include "slang/ast/symbols/VariableSymbols.h"
34
#include "slang/ast/types/AllTypes.h"
35
#include "slang/ast/types/Type.h"
36
#include "slang/diagnostics/TextDiagnosticClient.h"
37
#include "slang/driver/Driver.h"
38
39
#include <algorithm>
40
#include <span>
41
#include <functional>
42
#include <map>
43
#include <mutex>
44
#include <memory>
45
#include <mutex>
46
#include <set>
47
#include <unordered_map>
48
#include <unordered_set>
49
50
namespace labneura::eda {
51
namespace {
52
53
namespace sa = slang::ast;
54
using synth::Bit;
55
using synth::Node;
56
using synth::BitGraph;
57
using synth::kLatch;
58
using synth::kOne;
59
using synth::kZero;
60
using synth::Op;
61
using synth::Word;
62
using synth::WordOps;
63
64
0
[[noreturn]] void unsupported(const std::string& what) {
65
0
    throw std::runtime_error("behavioral synthesis: unsupported " + what);
66
0
}
67
68
struct Var {
69
    const sa::ValueSymbol* symbol = nullptr;
70
    std::string name;
71
    std::size_t width = 0;
72
    std::size_t element_width = 0;  // arrays only
73
    std::size_t element_count = 0;  // arrays only
74
    bool is_array = false;
75
    bool is_scalar = false;
76
    bool registered = false;
77
    slang::ConstantRange range;  // packed range, or array index range
78
    Word wires;
79
    std::vector<char> driven;
80
};
81
82
struct Target {
83
    Var* var;
84
    std::size_t bit;
85
    Bit condition;
86
};
87
88
struct State {
89
    std::unordered_map<const sa::Symbol*, Word> cur;
90
    std::unordered_map<const sa::Symbol*, Word> nb;
91
    Bit returned = 0;  // condition under which a function `return` already executed
92
};
93
94
struct Candidate {
95
    Bit condition;
96
    long offset;
97
};
98
99
4.59k
long signed_value(const Word& word, bool is_signed) {
100
4.59k
    const auto value = synth::as_constant(word);
101
4.59k
    if (!value) unsupported("non-constant value where a constant is required");
102
4.59k
    std::int64_t result = static_cast<std::int64_t>(*value);
103
4.59k
    if (is_signed && !word.empty() && word.size() < 64 && word.back() == kOne) {
104
0
        result -= std::int64_t{1} << word.size();
105
0
    }
106
4.59k
    return static_cast<long>(result);
107
4.59k
}
108
109
60.2k
std::size_t type_width(const sa::Type& type) {
110
    // Unpacked arrays report no bit width; they are stored flat, element by element.
111
60.2k
    const auto& canonical = type.getCanonicalType();
112
60.2k
    if (canonical.isUnpackedArray() && canonical.hasFixedRange()) {
113
24
        const auto* element = canonical.getArrayElementType();
114
24
        return element ? canonical.getFixedRange().width() * type_width(*element) : 0;
115
24
    }
116
60.2k
    return type.getBitWidth();
117
60.2k
}
118
119
std::string expression_source(const sa::Expression& expression,
120
                              const slang::SourceManager& source_manager,
121
1.08k
                              const std::string& scope_prefix) {
122
1.08k
    return detail::verilog_expression_source(expression, source_manager,
123
1.08k
                                            scope_prefix);
124
1.08k
}
125
126
class Synthesizer {
127
public:
128
145
    Synthesizer() : ops_(graph_) {}
129
130
    Module run(const sa::InstanceSymbol& top, const std::string& top_name,
131
               bool preserve_hierarchy,
132
               const slang::SourceManager& source_manager);
133
134
private:
135
    BitGraph graph_;
136
    WordOps ops_;
137
    std::unordered_map<const sa::Symbol*, Var> vars_;
138
    std::string top_prefix_;
139
    const sa::Symbol* anchor_ = nullptr;
140
    State st_;
141
    bool seq_ = false;
142
    int call_depth_ = 0;
143
    Var* return_var_ = nullptr;
144
    const sa::Expression* lvalue_reference_ = nullptr;
145
146
    struct Output {
147
        std::string name;
148
        Var* var;
149
        std::size_t bit;
150
    };
151
    std::vector<const sa::ProceduralBlockSymbol*> procedures_;
152
    std::vector<const sa::ContinuousAssignSymbol*> assigns_;
153
    std::vector<const sa::NetSymbol*> net_initializers_;
154
    std::vector<const sa::InstanceSymbol*> instances_;
155
    bool preserve_hierarchy_ = false;
156
157
    // ---- variables ----
158
4.14k
    std::string path_name(const sa::Symbol& symbol) const {
159
4.14k
        std::string path = symbol.getHierarchicalPath();
160
4.14k
        if (path.rfind(top_prefix_, 0) == 0) path.erase(0, top_prefix_.size());
161
4.14k
        return path;
162
4.14k
    }
163
164
4.31k
    Var& register_var(const sa::ValueSymbol& symbol, bool module_level) {
165
4.31k
        auto [it, inserted] = vars_.try_emplace(&symbol);
166
4.31k
        Var& var = it->second;
167
4.31k
        if (!inserted) return var;
168
4.31k
        const auto& type = symbol.getType();
169
4.31k
        var.symbol = &symbol;
170
4.31k
        var.name = module_level ? path_name(symbol) : std::string(symbol.name);
171
4.31k
        var.registered = module_level;
172
4.31k
        if (type.isUnpackedArray()) {
173
51
            const auto* element = type.getArrayElementType();
174
51
            if (!element || !element->isIntegral() || !type.hasFixedRange()) {
175
0
                unsupported("array type of '" + var.name + "'");
176
0
            }
177
51
            var.is_array = true;
178
51
            var.range = type.getFixedRange();
179
51
            var.element_width = type_width(*element);
180
51
            var.element_count = var.range.width();
181
51
            var.width = var.element_width * var.element_count;
182
4.26k
        } else if (type.isIntegral()) {
183
4.26k
            var.width = type_width(type);
184
4.26k
            var.is_scalar = type.isScalar();
185
4.26k
            if (type.isPackedArray() && type.hasFixedRange() &&
186
4.26k
                type.getFixedRange().width() != var.width) {
187
8
                var.range = slang::ConstantRange{
188
8
                    static_cast<int32_t>(var.width) - 1, 0};
189
4.25k
            } else {
190
4.25k
                var.range = type.hasFixedRange()
191
4.25k
                                ? type.getFixedRange()
192
4.25k
                                : slang::ConstantRange{
193
0
                                      static_cast<int32_t>(var.width) - 1, 0};
194
4.25k
            }
195
4.26k
        } else {
196
0
            unsupported("type of '" + var.name + "'");
197
0
        }
198
4.31k
        var.driven.assign(var.width, 0);
199
4.31k
        if (module_level) {
200
53.9k
            for (std::size_t i = 0; i < var.width; ++i) {
201
49.7k
                const Bit wire = graph_.wire();
202
49.7k
                graph_.node(wire).name = bit_name(var, i);
203
49.7k
                var.wires.push_back(wire);
204
49.7k
            }
205
4.14k
        } else {
206
164
            var.wires.assign(var.width, kLatch);
207
164
        }
208
4.31k
        return var;
209
4.31k
    }
210
211
17.4k
    Var& var_for(const sa::ValueSymbol& symbol) {
212
17.4k
        const auto it = vars_.find(&symbol);
213
17.4k
        if (it != vars_.end()) return it->second;
214
164
        return register_var(symbol, false);
215
17.4k
    }
216
217
98.7k
    std::string bit_name(const Var& var, std::size_t bit) const {
218
98.7k
        if (var.is_scalar && var.width == 1) return var.name;
219
93.9k
        if (var.is_array) {
220
20.4k
            return var.name + "[" + std::to_string(bit / var.element_width +
221
20.4k
                                                   var.range.lower()) +
222
20.4k
                   "][" + std::to_string(bit % var.element_width) + "]";
223
20.4k
        }
224
73.5k
        const long logical = var.range.left >= var.range.right
225
73.5k
                                 ? static_cast<long>(var.range.right) + static_cast<long>(bit)
226
73.5k
                                 : static_cast<long>(var.range.right) - static_cast<long>(bit);
227
73.5k
        return var.name + "[" + std::to_string(logical) + "]";
228
93.9k
    }
229
230
44.6k
    void drive(Var& var, std::size_t bit, Bit value) {
231
44.6k
        if (var.driven[bit]) {
232
0
            throw std::runtime_error("behavioral synthesis: multiple drivers on " +
233
0
                                     bit_name(var, bit));
234
0
        }
235
44.6k
        var.driven[bit] = 1;
236
44.6k
        graph_.node(var.wires[bit]).a = value;
237
44.6k
    }
238
239
    // ---- scope walking ----
240
696
    void collect(const sa::Scope& scope) {
241
10.7k
        for (const auto& member : scope.members()) {
242
10.7k
            switch (member.kind) {
243
141
                case sa::SymbolKind::Net: {
244
141
                    const auto& net = member.as<sa::NetSymbol>();
245
141
                    register_var(net, true);
246
141
                    if (net.getInitializer()) net_initializers_.push_back(&net);
247
141
                    break;
248
0
                }
249
4.00k
                case sa::SymbolKind::Variable:
250
4.00k
                    register_var(member.as<sa::VariableSymbol>(), true);
251
4.00k
                    break;
252
560
                case sa::SymbolKind::ProceduralBlock:
253
560
                    procedures_.push_back(&member.as<sa::ProceduralBlockSymbol>());
254
560
                    break;
255
1.97k
                case sa::SymbolKind::ContinuousAssign:
256
1.97k
                    assigns_.push_back(&member.as<sa::ContinuousAssignSymbol>());
257
1.97k
                    break;
258
628
                case sa::SymbolKind::GenerateBlock: {
259
628
                    const auto& block = member.as<sa::GenerateBlockSymbol>();
260
628
                    if (!block.isUninstantiated) collect(block);
261
628
                    break;
262
0
                }
263
26
                case sa::SymbolKind::GenerateBlockArray: {
264
26
                    const auto& array = member.as<sa::GenerateBlockArraySymbol>();
265
262
                    for (const auto* entry : array.entries) {
266
262
                        if (!entry->isUninstantiated) collect(*entry);
267
262
                    }
268
26
                    break;
269
0
                }
270
60
                case sa::SymbolKind::Instance: {
271
60
                    const auto& child = member.as<sa::InstanceSymbol>();
272
60
                    instances_.push_back(&child);
273
60
                    if (!preserve_hierarchy_ || !child.isModule()) {
274
0
                        collect(child.body);
275
0
                    }
276
60
                    break;
277
0
                }
278
0
                case sa::SymbolKind::PrimitiveInstance:
279
0
                    unsupported("gate primitive instances in behavioral synthesis");
280
3.33k
                default:
281
3.33k
                    break;
282
10.7k
            }
283
10.7k
        }
284
696
    }
285
286
    // ---- constants ----
287
    Word from_constant(const slang::ConstantValue& value, std::size_t width,
288
11.9k
                       bool is_signed) {
289
11.9k
        if (!value.isInteger()) unsupported("non-integer constant");
290
11.9k
        const auto& integer = value.integer();
291
11.9k
        Word word(integer.getBitWidth());
292
211k
        for (std::size_t i = 0; i < word.size(); ++i) {
293
199k
            const auto bit = integer[static_cast<int32_t>(i)];
294
199k
            word[i] = !bit.isUnknown() && bit.value == 1 ? kOne : kZero;
295
199k
        }
296
11.9k
        return synth::resize(word, width, is_signed && integer.isSigned());
297
11.9k
    }
298
299
27.2k
    std::optional<Word> constant_of(const sa::Expression& expr) {
300
27.2k
        if (expr.type->isIntegral() == false) return std::nullopt;
301
27.2k
        if (const auto* constant = expr.getConstant()) {
302
11.9k
            if (constant->isInteger()) {
303
11.9k
                return from_constant(*constant, type_width(*expr.type),
304
11.9k
                                     expr.type->isSigned());
305
11.9k
            }
306
11.9k
        }
307
15.3k
        const bool try_eval =
308
15.3k
            (expr.kind == sa::ExpressionKind::Call &&
309
15.3k
             expr.as<sa::CallExpression>().isSystemCall()) ||
310
15.3k
            expr.kind == sa::ExpressionKind::IntegerLiteral ||
311
15.3k
            expr.kind == sa::ExpressionKind::UnbasedUnsizedIntegerLiteral ||
312
15.3k
            (expr.kind == sa::ExpressionKind::NamedValue &&
313
15.3k
             (expr.as<sa::NamedValueExpression>().symbol.kind ==
314
8.19k
                  sa::SymbolKind::Parameter ||
315
8.19k
              expr.as<sa::NamedValueExpression>().symbol.kind ==
316
8.19k
                  sa::SymbolKind::EnumValue));
317
15.3k
        if (!try_eval) return std::nullopt;
318
21
        sa::EvalContext context(*anchor_);
319
21
        const auto value = expr.eval(context);
320
21
        if (!value.isInteger()) return std::nullopt;
321
1
        return from_constant(value, type_width(*expr.type), expr.type->isSigned());
322
21
    }
323
324
2.58k
    long constant_int(const sa::Expression& expr) {
325
2.58k
        const auto word = eval(expr);
326
2.58k
        return signed_value(word, expr.type->isSigned());
327
2.58k
    }
328
329
    // ---- reads ----
330
8.35k
    const Word& read_var(Var& var) {
331
8.35k
        const auto found = st_.cur.find(var.symbol);
332
8.35k
        return found != st_.cur.end() ? found->second : var.wires;
333
8.35k
    }
334
335
4.38k
    static long translate(const slang::ConstantRange& range, long index) {
336
4.38k
        return range.left >= range.right ? index - range.right
337
4.38k
                                         : static_cast<long>(range.right) - index;
338
4.38k
    }
339
340
    std::vector<Candidate> element_candidates(const sa::Expression& selector,
341
                                              const slang::ConstantRange& range,
342
2.04k
                                              std::size_t unit_width, bool is_array) {
343
2.04k
        const Word index = eval(selector);
344
2.69k
        const auto position = [&](long logical) {
345
2.69k
            return is_array ? logical - range.lower() : translate(range, logical);
346
2.69k
        };
347
2.04k
        std::vector<Candidate> result;
348
2.04k
        if (synth::as_constant(index)) {
349
2.01k
            const long logical = signed_value(index, selector.type->isSigned());
350
2.01k
            result.push_back({kOne, position(logical) * static_cast<long>(unit_width)});
351
2.01k
            return result;
352
2.01k
        }
353
705
        for (long k = range.lower(); k <= range.upper(); ++k) {
354
680
            const Bit condition = ops_.equal(
355
680
                index, synth::constant_word(static_cast<std::uint64_t>(k), index.size()));
356
680
            if (condition == kZero) continue;
357
680
            result.push_back({condition, position(k) * static_cast<long>(unit_width)});
358
680
        }
359
25
        return result;
360
2.04k
    }
361
362
    std::vector<Candidate> range_candidates(const sa::RangeSelectExpression& select,
363
1.25k
                                            const slang::ConstantRange& range) {
364
1.25k
        std::vector<Candidate> result;
365
1.25k
        if (select.getSelectionKind() == sa::RangeSelectionKind::Simple) {
366
1.25k
            const long a = translate(range, constant_int(select.left()));
367
1.25k
            const long b = translate(range, constant_int(select.right()));
368
1.25k
            result.push_back({kOne, std::min(a, b)});
369
1.25k
            return result;
370
1.25k
        }
371
0
        const long width = constant_int(select.right());
372
0
        const bool up = select.getSelectionKind() == sa::RangeSelectionKind::IndexedUp;
373
0
        const auto offset_for = [&](long base) {
374
0
            const long first = up ? base : base - width + 1;
375
0
            const long last = up ? base + width - 1 : base;
376
0
            return std::min(translate(range, first), translate(range, last));
377
0
        };
378
0
        const Word base = eval(select.left());
379
0
        if (synth::as_constant(base)) {
380
0
            result.push_back(
381
0
                {kOne, offset_for(signed_value(base, select.left().type->isSigned()))});
382
0
            return result;
383
0
        }
384
0
        for (long k = range.lower(); k <= range.upper(); ++k) {
385
0
            const Bit condition = ops_.equal(
386
0
                base, synth::constant_word(static_cast<std::uint64_t>(k), base.size()));
387
0
            if (condition == kZero) continue;
388
0
            result.push_back({condition, offset_for(k)});
389
0
        }
390
0
        return result;
391
0
    }
392
393
    Word gather(const Word& vector, const std::vector<Candidate>& candidates,
394
2.15k
                std::size_t width) {
395
2.15k
        Word result(width, kZero);
396
2.68k
        for (const auto& candidate : candidates) {
397
39.1k
            for (std::size_t j = 0; j < width; ++j) {
398
36.4k
                const long position = candidate.offset + static_cast<long>(j);
399
36.4k
                const Bit bit = position >= 0 && position < static_cast<long>(vector.size())
400
36.4k
                                    ? vector[static_cast<std::size_t>(position)]
401
36.4k
                                    : kZero;
402
36.4k
                result[j] = candidate.condition == kOne
403
36.4k
                                ? bit
404
36.4k
                                : graph_.make_or(result[j],
405
18.6k
                                                 graph_.make_and(candidate.condition, bit));
406
36.4k
            }
407
2.68k
        }
408
2.15k
        return result;
409
2.15k
    }
410
411
2.34k
    Bit truthy(const Word& word) { return ops_.reduce_or(word); }
412
413
    Word apply_binary(sa::BinaryOperator op, const Word& left, const Word& right,
414
2.70k
                      bool is_signed, std::size_t out_width) {
415
2.70k
        using B = sa::BinaryOperator;
416
2.70k
        const std::size_t common = std::max(left.size(), right.size());
417
2.70k
        const auto one_bit = [&](Bit value) { return synth::resize({value}, out_width, false); };
418
2.70k
        switch (op) {
419
109
            case B::Add:
420
109
                return ops_.add(synth::resize(left, out_width, is_signed),
421
109
                                synth::resize(right, out_width, is_signed));
422
212
            case B::Subtract:
423
212
                return ops_.sub(synth::resize(left, out_width, is_signed),
424
212
                                synth::resize(right, out_width, is_signed));
425
12
            case B::Multiply:
426
12
                return ops_.multiply(synth::resize(left, out_width, is_signed),
427
12
                                     synth::resize(right, out_width, is_signed));
428
737
            case B::BinaryAnd:
429
1.14k
            case B::BinaryOr:
430
1.18k
            case B::BinaryXor:
431
1.18k
            case B::BinaryXnor: {
432
1.18k
                const auto a = synth::resize(left, out_width, is_signed);
433
1.18k
                const auto b = synth::resize(right, out_width, is_signed);
434
1.18k
                if (op == B::BinaryAnd) return ops_.bitwise('&', a, b);
435
445
                if (op == B::BinaryOr) return ops_.bitwise('|', a, b);
436
33
                const auto x = ops_.bitwise('^', a, b);
437
33
                return op == B::BinaryXor ? x : ops_.bit_not(x);
438
445
            }
439
420
            case B::Equality:
440
420
            case B::CaseEquality:
441
420
                return one_bit(ops_.equal(synth::resize(left, common, is_signed),
442
420
                                          synth::resize(right, common, is_signed)));
443
83
            case B::Inequality:
444
83
            case B::CaseInequality:
445
83
                return one_bit(graph_.make_not(
446
83
                    ops_.equal(synth::resize(left, common, is_signed),
447
83
                               synth::resize(right, common, is_signed))));
448
326
            case B::LessThan:
449
332
            case B::LessThanEqual:
450
346
            case B::GreaterThan:
451
458
            case B::GreaterThanEqual: {
452
458
                const auto a = synth::resize(left, common, is_signed);
453
458
                const auto b = synth::resize(right, common, is_signed);
454
458
                if (op == B::LessThan) return one_bit(ops_.less_than(a, b, is_signed));
455
132
                if (op == B::GreaterThan) return one_bit(ops_.less_than(b, a, is_signed));
456
118
                if (op == B::LessThanEqual) {
457
6
                    return one_bit(graph_.make_not(ops_.less_than(b, a, is_signed)));
458
6
                }
459
112
                return one_bit(graph_.make_not(ops_.less_than(a, b, is_signed)));
460
118
            }
461
137
            case B::LogicalAnd:
462
137
                return one_bit(graph_.make_and(truthy(left), truthy(right)));
463
80
            case B::LogicalOr:
464
80
                return one_bit(graph_.make_or(truthy(left), truthy(right)));
465
0
            case B::LogicalImplication:
466
0
                return one_bit(graph_.make_or(graph_.make_not(truthy(left)), truthy(right)));
467
0
            case B::LogicalEquivalence:
468
0
                return one_bit(graph_.make_not(
469
0
                    graph_.make_xor(truthy(left), truthy(right))));
470
3
            case B::LogicalShiftLeft:
471
3
            case B::ArithmeticShiftLeft:
472
3
                return ops_.shift(synth::resize(left, out_width, is_signed), right,
473
3
                                  WordOps::Shift::Left);
474
4
            case B::LogicalShiftRight:
475
4
                return ops_.shift(synth::resize(left, out_width, false), right,
476
4
                                  WordOps::Shift::LogicalRight);
477
0
            case B::ArithmeticShiftRight:
478
0
                return ops_.shift(synth::resize(left, out_width, is_signed), right,
479
0
                                  is_signed ? WordOps::Shift::ArithmeticRight
480
0
                                            : WordOps::Shift::LogicalRight);
481
1
            case B::Divide:
482
2
            case B::Mod: {
483
2
                const auto a = synth::resize(left, out_width, is_signed);
484
2
                const auto b = synth::resize(right, out_width, is_signed);
485
2
                const auto result = ops_.divmod(a, b, is_signed);
486
2
                return op == B::Divide ? result.first : result.second;
487
1
            }
488
1
            case B::Power: {
489
1
                const auto base = synth::resize(left, out_width, is_signed);
490
1
                if (const auto exponent = synth::as_constant(right)) {
491
1
                    if (*exponent > 64) unsupported("constant exponent above 64");
492
1
                    Word result = synth::constant_word(1, out_width);
493
3
                    for (std::uint64_t i = 0; i < *exponent; ++i) {
494
2
                        result = ops_.multiply(result, base);
495
2
                    }
496
1
                    return result;
497
1
                }
498
0
                if (synth::as_constant(base) == std::optional<std::uint64_t>(2)) {
499
0
                    return ops_.shift(synth::constant_word(1, out_width), right,
500
0
                                      WordOps::Shift::Left);
501
0
                }
502
0
                unsupported("power with a non-constant exponent and a base other than 2");
503
0
            }
504
0
            default:
505
0
                unsupported("binary operator");
506
2.70k
        }
507
2.70k
    }
508
509
27.2k
    Word eval(const sa::Expression& expr) {
510
27.2k
        using K = sa::ExpressionKind;
511
27.2k
        const std::size_t width = type_width(*expr.type);
512
27.2k
        if (const auto constant = constant_of(expr)) return *constant;
513
15.3k
        switch (expr.kind) {
514
9
            case K::HierarchicalValue:
515
8.20k
            case K::NamedValue: {
516
8.20k
                const auto& symbol = expr.as<sa::ValueExpressionBase>().symbol;
517
8.20k
                Var& var = var_for(symbol);
518
                // Arrays are stored flat, so a whole-array read is the flat word.
519
8.20k
                return synth::resize(read_var(var), width, false);
520
9
            }
521
278
            case K::Conversion: {
522
278
                const auto& conversion = expr.as<sa::ConversionExpression>();
523
278
                if (!expr.type->isIntegral()) unsupported("non-integral conversion");
524
278
                const auto& operand = conversion.operand();
525
278
                return synth::resize(eval(operand), width, operand.type->isSigned());
526
9
            }
527
670
            case K::UnaryOp: {
528
670
                const auto& unary = expr.as<sa::UnaryExpression>();
529
670
                const Word operand = eval(unary.operand());
530
670
                const bool is_signed = unary.operand().type->isSigned();
531
670
                using U = sa::UnaryOperator;
532
670
                const auto one_bit = [&](Bit value) {
533
293
                    return synth::resize({value}, width, false);
534
293
                };
535
670
                switch (unary.op) {
536
0
                    case U::Plus: return synth::resize(operand, width, is_signed);
537
12
                    case U::Minus:
538
12
                        return ops_.negate(synth::resize(operand, width, is_signed));
539
365
                    case U::BitwiseNot:
540
365
                        return ops_.bit_not(synth::resize(operand, width, is_signed));
541
0
                    case U::BitwiseAnd: return one_bit(ops_.reduce_and(operand));
542
19
                    case U::BitwiseOr: return one_bit(ops_.reduce_or(operand));
543
75
                    case U::BitwiseXor: return one_bit(ops_.reduce_xor(operand));
544
3
                    case U::BitwiseNand:
545
3
                        return one_bit(graph_.make_not(ops_.reduce_and(operand)));
546
0
                    case U::BitwiseNor:
547
0
                        return one_bit(graph_.make_not(ops_.reduce_or(operand)));
548
0
                    case U::BitwiseXnor:
549
0
                        return one_bit(graph_.make_not(ops_.reduce_xor(operand)));
550
196
                    case U::LogicalNot: return one_bit(graph_.make_not(truthy(operand)));
551
0
                    default: unsupported("increment/decrement inside an expression");
552
670
                }
553
670
            }
554
2.70k
            case K::BinaryOp: {
555
2.70k
                const auto& binary = expr.as<sa::BinaryExpression>();
556
2.70k
                const bool is_signed = binary.left().type->isSigned() &&
557
2.70k
                                       binary.right().type->isSigned();
558
2.70k
                const bool shift = binary.op == sa::BinaryOperator::LogicalShiftLeft ||
559
2.70k
                                   binary.op == sa::BinaryOperator::LogicalShiftRight ||
560
2.70k
                                   binary.op == sa::BinaryOperator::ArithmeticShiftLeft ||
561
2.70k
                                   binary.op == sa::BinaryOperator::ArithmeticShiftRight;
562
2.70k
                const Word left = eval(binary.left());
563
2.70k
                const Word right = eval(binary.right());
564
2.70k
                return apply_binary(binary.op, left, right,
565
2.70k
                                    shift ? binary.left().type->isSigned() : is_signed,
566
2.70k
                                    width);
567
670
            }
568
303
            case K::ConditionalOp: {
569
303
                const auto& cond = expr.as<sa::ConditionalExpression>();
570
303
                if (cond.conditions.size() != 1 || cond.conditions[0].pattern) {
571
0
                    unsupported("pattern conditions in ?:");
572
0
                }
573
303
                const Bit select = truthy(eval(*cond.conditions[0].expr));
574
303
                const bool z_right = is_all_z(cond.right());
575
303
                if (z_right || is_all_z(cond.left())) {
576
1
                    const auto& data_expr = z_right ? cond.left() : cond.right();
577
1
                    Word data = synth::resize(eval(data_expr), width, data_expr.type->isSigned());
578
1
                    const Bit enable = z_right ? select : graph_.make_not(select);
579
1
                    for (auto& bit : data) bit = graph_.tri(bit, enable);
580
1
                    return data;
581
1
                }
582
302
                return ops_.mux(
583
302
                    select,
584
302
                    synth::resize(eval(cond.left()), width, cond.left().type->isSigned()),
585
302
                    synth::resize(eval(cond.right()), width, cond.right().type->isSigned()));
586
303
            }
587
565
            case K::Concatenation: {
588
565
                const auto& concat = expr.as<sa::ConcatenationExpression>();
589
565
                Word result;
590
2.40k
                for (auto it = concat.operands().rbegin(); it != concat.operands().rend();
591
1.83k
                     ++it) {
592
1.83k
                    const Word part = eval(**it);
593
1.83k
                    result.insert(result.end(), part.begin(), part.end());
594
1.83k
                }
595
565
                return synth::resize(result, width, false);
596
303
            }
597
80
            case K::Replication: {
598
80
                const auto& rep = expr.as<sa::ReplicationExpression>();
599
80
                const long count = constant_int(rep.count());
600
80
                const Word part = eval(rep.concat());
601
80
                Word result;
602
1.70k
                for (long i = 0; i < count; ++i) {
603
1.62k
                    result.insert(result.end(), part.begin(), part.end());
604
1.62k
                }
605
80
                return synth::resize(result, width, false);
606
303
            }
607
1.12k
            case K::ElementSelect: {
608
1.12k
                const auto& select = expr.as<sa::ElementSelectExpression>();
609
1.12k
                const auto& value = select.value();
610
1.12k
                if (value.type->isUnpackedArray()) {
611
149
                    if (value.kind != K::NamedValue) unsupported("nested array read");
612
149
                    Var& var = var_for(value.as<sa::NamedValueExpression>().symbol);
613
149
                    const auto candidates = element_candidates(
614
149
                        select.selector(), var.range, var.element_width, true);
615
149
                    return gather(read_var(var), candidates, width);
616
149
                }
617
972
                const Word vector = eval(value);
618
972
                const auto candidates = element_candidates(
619
972
                    select.selector(), value.type->getFixedRange(), width, false);
620
972
                return gather(vector, candidates, width);
621
1.12k
            }
622
1.03k
            case K::RangeSelect: {
623
1.03k
                const auto& select = expr.as<sa::RangeSelectExpression>();
624
1.03k
                const Word vector = eval(select.value());
625
1.03k
                return gather(vector,
626
1.03k
                              range_candidates(select, select.value().type->getFixedRange()),
627
1.03k
                              width);
628
1.12k
            }
629
0
            case K::SimpleAssignmentPattern:
630
0
                return pattern_word(
631
0
                    expr.as<sa::SimpleAssignmentPatternExpression>().elements(), *expr.type);
632
10
            case K::StructuredAssignmentPattern:
633
10
                return pattern_word(
634
10
                    expr.as<sa::StructuredAssignmentPatternExpression>().elements(),
635
10
                    *expr.type);
636
9
            case K::LValueReference:
637
9
                if (!lvalue_reference_) unsupported("lvalue reference outside an assignment");
638
9
                return synth::resize(eval(*lvalue_reference_), width, false);
639
32
            case K::Inside: {
640
32
                const auto& inside = expr.as<sa::InsideExpression>();
641
32
                const Word subject = eval(inside.left());
642
32
                bool is_signed = inside.left().type->isSigned();
643
32
                Bit match = kZero;
644
102
                for (const auto* item : inside.rangeList()) {
645
102
                    const auto compare_width = [&](const sa::Expression& e) {
646
102
                        return std::max(subject.size(), type_width(*e.type));
647
102
                    };
648
102
                    if (item->kind == K::ValueRange) {
649
0
                        const auto& range = item->as<sa::ValueRangeExpression>();
650
0
                        const bool item_signed =
651
0
                            is_signed && range.left().type->isSigned() &&
652
0
                            range.right().type->isSigned();
653
0
                        const std::size_t w = std::max(compare_width(range.left()),
654
0
                                                       compare_width(range.right()));
655
0
                        const Word v = synth::resize(subject, w, item_signed);
656
0
                        const Word lo = synth::resize(eval(range.left()), w, item_signed);
657
0
                        const Word hi = synth::resize(eval(range.right()), w, item_signed);
658
0
                        match = graph_.make_or(
659
0
                            match, graph_.make_and(
660
0
                                       graph_.make_not(ops_.less_than(v, lo, item_signed)),
661
0
                                       graph_.make_not(ops_.less_than(hi, v, item_signed))));
662
102
                    } else {
663
102
                        const bool item_signed = is_signed && item->type->isSigned();
664
102
                        const std::size_t w = compare_width(*item);
665
102
                        match = graph_.make_or(
666
102
                            match, ops_.equal(synth::resize(subject, w, item_signed),
667
102
                                              synth::resize(eval(*item), w, item_signed)));
668
102
                    }
669
102
                }
670
32
                return synth::resize(Word{match}, width, false);
671
1.12k
            }
672
225
            case K::MemberAccess: {
673
225
                const auto& access = expr.as<sa::MemberAccessExpression>();
674
225
                if (!access.value().type->isIntegral() ||
675
225
                    access.member.kind != sa::SymbolKind::Field) {
676
0
                    unsupported("member access on a non-packed type");
677
0
                }
678
225
                const Word packed = eval(access.value());
679
225
                const auto offset = access.member.as<sa::FieldSymbol>().bitOffset;
680
225
                Word field(width, kZero);
681
1.53k
                for (std::size_t i = 0; i < width && offset + i < packed.size(); ++i) {
682
1.30k
                    field[i] = packed[offset + i];
683
1.30k
                }
684
225
                return field;
685
1.12k
            }
686
105
            case K::Call: {
687
105
                const auto& call = expr.as<sa::CallExpression>();
688
105
                if (call.isSystemCall()) {
689
20
                    const auto name = call.getSubroutineName();
690
20
                    if ((name == "$signed" || name == "$unsigned") &&
691
20
                        call.arguments().size() == 1) {
692
20
                        const auto& argument = *call.arguments()[0];
693
20
                        return synth::resize(eval(argument), width,
694
20
                                             argument.type->isSigned());
695
20
                    }
696
20
                }
697
85
                return synth::resize(call_subroutine(call), width,
698
85
                                     call.type->isSigned());
699
105
            }
700
0
            case K::Assignment:
701
0
                unsupported("assignment used as a value");
702
0
            default:
703
0
                unsupported("expression kind " + std::string(toString(expr.kind)));
704
15.3k
        }
705
15.3k
    }
706
707
    // Elements of an assignment pattern arrive in declaration order (struct fields,
708
    // or array elements from the left bound), already resolved against defaults.
709
10
    Word pattern_word(std::span<const sa::Expression* const> elements, const sa::Type& type) {
710
10
        const std::size_t total = type_width(type);
711
10
        Word result(total, kZero);
712
10
        const auto place = [&](const sa::Expression& element, std::size_t offset,
713
34
                               std::size_t width) {
714
34
            const Word value = synth::resize(eval(element), width, element.type->isSigned());
715
102
            for (std::size_t i = 0; i < width && offset + i < total; ++i) {
716
68
                result[offset + i] = value[i];
717
68
            }
718
34
        };
719
10
        const auto& canonical = type.getCanonicalType();
720
10
        if (canonical.isStruct() && canonical.isIntegral()) {
721
10
            std::size_t index = 0;
722
10
            for (const auto& field :
723
34
                 canonical.as<sa::PackedStructType>().membersOfType<sa::FieldSymbol>()) {
724
34
                if (index >= elements.size()) break;
725
34
                place(*elements[index++], field.bitOffset, type_width(field.getType()));
726
34
            }
727
10
            return result;
728
10
        }
729
0
        if (canonical.isUnpackedArray() || canonical.isIntegral()) {
730
0
            const auto* element_type = canonical.getArrayElementType();
731
0
            if (!element_type || !canonical.hasFixedRange() || elements.empty()) {
732
0
                unsupported("assignment pattern for this type");
733
0
            }
734
0
            const auto range = canonical.getFixedRange();
735
0
            const std::size_t element_width = type_width(*element_type);
736
0
            for (std::size_t i = 0; i < elements.size(); ++i) {
737
0
                const std::size_t position =
738
0
                    canonical.isUnpackedArray()
739
0
                        ? (range.left <= range.right ? i : elements.size() - 1 - i)
740
0
                        : elements.size() - 1 - i;
741
0
                place(*elements[i], position * element_width, element_width);
742
0
            }
743
0
            return result;
744
0
        }
745
0
        unsupported("assignment pattern for this type");
746
0
    }
747
748
    // ---- lvalues ----
749
    using TargetList = std::vector<std::vector<Target>>;
750
751
7.54k
    TargetList lvalue_bits(const sa::Expression& expr) {
752
7.54k
        using K = sa::ExpressionKind;
753
7.54k
        const std::size_t width = type_width(*expr.type);
754
7.54k
        switch (expr.kind) {
755
0
            case K::HierarchicalValue:
756
6.31k
            case K::NamedValue: {
757
6.31k
                Var& var = var_for(expr.as<sa::ValueExpressionBase>().symbol);
758
6.31k
                TargetList result(var.width);
759
96.1k
                for (std::size_t i = 0; i < var.width; ++i) result[i].push_back({&var, i, kOne});
760
6.31k
                return result;
761
0
            }
762
919
            case K::ElementSelect: {
763
919
                const auto& select = expr.as<sa::ElementSelectExpression>();
764
919
                const auto& value = select.value();
765
919
                TargetList result(width);
766
919
                if (value.type->isUnpackedArray()) {
767
351
                    if (value.kind != K::NamedValue) unsupported("nested array write");
768
351
                    Var& var = var_for(value.as<sa::NamedValueExpression>().symbol);
769
351
                    for (const auto& candidate : element_candidates(
770
353
                             select.selector(), var.range, var.element_width, true)) {
771
353
                        if (candidate.offset < 0 ||
772
353
                            candidate.offset >= static_cast<long>(var.width)) {
773
0
                            continue;
774
0
                        }
775
12.5k
                        for (std::size_t j = 0; j < width; ++j) {
776
12.1k
                            result[j].push_back({&var,
777
12.1k
                                                 static_cast<std::size_t>(candidate.offset) + j,
778
12.1k
                                                 candidate.condition});
779
12.1k
                        }
780
353
                    }
781
351
                    return result;
782
351
                }
783
568
                const auto base = lvalue_bits(value);
784
568
                for (const auto& candidate : element_candidates(
785
692
                         select.selector(), value.type->getFixedRange(), width, false)) {
786
692
                    add_slice(result, base, candidate);
787
692
                }
788
568
                return result;
789
919
            }
790
216
            case K::RangeSelect: {
791
216
                const auto& select = expr.as<sa::RangeSelectExpression>();
792
216
                TargetList result(width);
793
216
                const auto base = lvalue_bits(select.value());
794
216
                for (const auto& candidate : range_candidates(
795
216
                         select, select.value().type->getFixedRange())) {
796
216
                    add_slice(result, base, candidate);
797
216
                }
798
216
                return result;
799
919
            }
800
91
            case K::MemberAccess: {
801
91
                const auto& access = expr.as<sa::MemberAccessExpression>();
802
91
                if (!access.value().type->isIntegral() ||
803
91
                    access.member.kind != sa::SymbolKind::Field) {
804
0
                    unsupported("member access on a non-packed type");
805
0
                }
806
91
                const auto base = lvalue_bits(access.value());
807
91
                const auto offset = access.member.as<sa::FieldSymbol>().bitOffset;
808
91
                TargetList result(width);
809
447
                for (std::size_t j = 0; j < width && offset + j < base.size(); ++j) {
810
356
                    result[j] = base[offset + j];
811
356
                }
812
91
                return result;
813
919
            }
814
2
            case K::Concatenation: {
815
2
                TargetList result;
816
2
                const auto& concat = expr.as<sa::ConcatenationExpression>();
817
6
                for (auto it = concat.operands().rbegin(); it != concat.operands().rend();
818
4
                     ++it) {
819
4
                    auto part = lvalue_bits(**it);
820
4
                    result.insert(result.end(), part.begin(), part.end());
821
4
                }
822
2
                return result;
823
919
            }
824
0
            default:
825
0
                unsupported("assignment target (expression kind " +
826
0
                            std::string(toString(expr.kind)) + ")");
827
7.54k
        }
828
7.54k
    }
829
830
908
    void add_slice(TargetList& result, const TargetList& base, const Candidate& candidate) {
831
4.69k
        for (std::size_t j = 0; j < result.size(); ++j) {
832
3.78k
            const long position = candidate.offset + static_cast<long>(j);
833
3.78k
            if (position < 0 || position >= static_cast<long>(base.size())) continue;
834
3.78k
            for (const auto& target : base[static_cast<std::size_t>(position)]) {
835
3.78k
                result[j].push_back(
836
3.78k
                    {target.var, target.bit,
837
3.78k
                     graph_.make_and(candidate.condition, target.condition)});
838
3.78k
            }
839
3.78k
        }
840
908
    }
841
842
74.4k
    Word& touch_cur(Var& var) {
843
74.4k
        auto [it, inserted] = st_.cur.try_emplace(var.symbol);
844
74.4k
        if (inserted) {
845
2.95k
            it->second = seq_ && var.registered ? var.wires : Word(var.width, kLatch);
846
2.95k
        }
847
74.4k
        return it->second;
848
74.4k
    }
849
5.45k
    Word& touch_nb(Var& var) {
850
5.45k
        auto [it, inserted] = st_.nb.try_emplace(var.symbol);
851
5.45k
        if (inserted) it->second = var.wires;
852
5.45k
        return it->second;
853
5.45k
    }
854
855
6.66k
    void write(const sa::Expression& lhs, Word value, bool nonblocking) {
856
6.66k
        const auto targets = lvalue_bits(lhs);
857
6.66k
        value = synth::resize(value, targets.size(), false);
858
86.2k
        for (std::size_t p = 0; p < targets.size(); ++p) {
859
79.7k
            for (const auto& target : targets[p]) {
860
79.7k
                Word& destination =
861
79.7k
                    nonblocking && seq_ ? touch_nb(*target.var) : touch_cur(*target.var);
862
79.7k
                destination[target.bit] =
863
79.7k
                    target.condition == kOne
864
79.7k
                        ? value[p]
865
79.7k
                        : graph_.make_mux(target.condition, value[p], destination[target.bit]);
866
79.7k
            }
867
79.6k
        }
868
6.66k
    }
869
870
    // ---- statements ----
871
1.88k
    Word initial_value(const Var& var, bool nonblocking) const {
872
1.88k
        if (nonblocking) return var.wires;
873
1.74k
        return seq_ && var.registered ? var.wires : Word(var.width, kLatch);
874
1.88k
    }
875
876
    void merge_maps(Bit condition,
877
                    std::unordered_map<const sa::Symbol*, Word>& when_true,
878
                    std::unordered_map<const sa::Symbol*, Word>& when_false,
879
3.72k
                    std::unordered_map<const sa::Symbol*, Word>& out, bool nonblocking) {
880
3.72k
        std::set<const sa::Symbol*> keys;
881
23.3k
        for (const auto& entry : when_true) keys.insert(entry.first);
882
23.6k
        for (const auto& entry : when_false) keys.insert(entry.first);
883
24.4k
        for (const auto* key : keys) {
884
24.4k
            const Var& var = vars_.at(key);
885
24.4k
            const auto t = when_true.find(key);
886
24.4k
            const auto f = when_false.find(key);
887
24.4k
            const Word tw = t != when_true.end() ? t->second : initial_value(var, nonblocking);
888
24.4k
            const Word fw = f != when_false.end() ? f->second : initial_value(var, nonblocking);
889
24.4k
            Word merged(tw.size());
890
163k
            for (std::size_t i = 0; i < tw.size(); ++i) {
891
139k
                merged[i] = graph_.make_mux(condition, tw[i], fw[i]);
892
139k
            }
893
24.4k
            out[key] = std::move(merged);
894
24.4k
        }
895
3.72k
    }
896
897
1.86k
    State merge(Bit condition, State& when_true, State& when_false) {
898
1.86k
        State result;
899
1.86k
        merge_maps(condition, when_true.cur, when_false.cur, result.cur, false);
900
1.86k
        merge_maps(condition, when_true.nb, when_false.nb, result.nb, true);
901
1.86k
        result.returned = graph_.make_mux(condition, when_true.returned, when_false.returned);
902
1.86k
        return result;
903
1.86k
    }
904
905
    void exec_branch(Bit condition, const std::function<void()>& then_branch,
906
923
                     const std::function<void()>& else_branch) {
907
923
        if (condition == kOne) {
908
79
            then_branch();
909
79
            return;
910
79
        }
911
844
        if (condition == kZero) {
912
198
            else_branch();
913
198
            return;
914
198
        }
915
646
        State saved = st_;
916
646
        then_branch();
917
646
        State taken = std::move(st_);
918
646
        st_ = std::move(saved);
919
646
        else_branch();
920
646
        st_ = merge(condition, taken, st_);
921
646
    }
922
923
    Bit case_match(const sa::CaseStatement& statement, const Word& subject,
924
2.23k
                   const sa::Expression& item) {
925
2.23k
        const bool is_signed = statement.expr.type->isSigned() && item.type->isSigned();
926
2.23k
        const std::size_t width = std::max(subject.size(), type_width(*item.type));
927
2.23k
        const Word a = synth::resize(subject, width, is_signed);
928
2.23k
        const Word b = synth::resize(eval(item), width, is_signed);
929
2.23k
        if (statement.condition == sa::CaseStatementCondition::Normal) {
930
2.22k
            return ops_.equal(a, b);
931
2.22k
        }
932
15
        std::vector<char> ignore(width, 0);
933
15
        sa::EvalContext context(*anchor_);
934
15
        const auto constant = item.eval(context);
935
15
        if (constant.isInteger()) {
936
15
            const auto& integer = constant.integer();
937
90
            for (std::size_t i = 0; i < width && i < integer.getBitWidth(); ++i) {
938
75
                const auto bit = integer[static_cast<int32_t>(i)];
939
75
                if (!bit.isUnknown()) continue;
940
6
                const bool is_x = bit.value == slang::logic_t::x.value;
941
6
                if (is_x && statement.condition == sa::CaseStatementCondition::WildcardJustZ) {
942
0
                    continue;
943
0
                }
944
6
                ignore[i] = 1;
945
6
            }
946
15
        }
947
15
        Bit result = kOne;
948
90
        for (std::size_t i = 0; i < width; ++i) {
949
75
            if (ignore[i]) continue;
950
69
            result = graph_.make_and(result,
951
69
                                     graph_.make_not(graph_.make_xor(a[i], b[i])));
952
69
        }
953
15
        return result;
954
2.23k
    }
955
956
0
    bool covers_all(const std::vector<std::pair<Bit, State>>& branches) {
957
0
        Bit covered = kZero;
958
0
        for (const auto& branch : branches) covered = graph_.make_or(covered, branch.first);
959
0
        return is_tautology(covered);
960
0
    }
961
962
    // Exhaustive check over the (small) support of a condition.
963
2
    bool is_tautology(Bit root) {
964
2
        if (root == kOne) return true;
965
2
        std::vector<Bit> leaves;
966
2
        std::unordered_set<Bit> seen;
967
2
        std::vector<Bit> stack{root};
968
5
        while (!stack.empty()) {
969
3
            const Bit id = stack.back();
970
3
            stack.pop_back();
971
3
            if (!seen.insert(id).second) continue;
972
3
            const Node& n = graph_.node(id);
973
3
            switch (n.op) {
974
1
                case Op::Const: break;
975
1
                case Op::Wire:
976
1
                    if (n.a >= 0) stack.push_back(n.a);
977
0
                    else leaves.push_back(id);
978
1
                    break;
979
0
                case Op::Not: stack.push_back(n.a); break;
980
0
                case Op::And:
981
0
                case Op::Or:
982
0
                case Op::Xor: stack.push_back(n.a); stack.push_back(n.b); break;
983
0
                case Op::Mux: stack.push_back(n.a); stack.push_back(n.b); stack.push_back(n.c); break;
984
1
                default: leaves.push_back(id); break;
985
3
            }
986
3
            if (leaves.size() > 14) return false;
987
3
        }
988
2
        std::unordered_map<Bit, bool> value;
989
3
        std::function<bool(Bit)> evaluate = [&](Bit id) -> bool {
990
3
            const Node& n = graph_.node(id);
991
3
            switch (n.op) {
992
1
                case Op::Const: return id == kOne;
993
1
                case Op::Wire: return n.a >= 0 ? evaluate(n.a) : value.at(id);
994
0
                case Op::Not: return !evaluate(n.a);
995
0
                case Op::And: return evaluate(n.a) && evaluate(n.b);
996
0
                case Op::Or: return evaluate(n.a) || evaluate(n.b);
997
0
                case Op::Xor: return evaluate(n.a) != evaluate(n.b);
998
0
                case Op::Mux: return evaluate(n.c) ? evaluate(n.b) : evaluate(n.a);
999
1
                default: return value.at(id);
1000
3
            }
1001
3
        };
1002
2
        for (std::uint32_t mask = 0; mask < (1u << leaves.size()); ++mask) {
1003
3
            for (std::size_t i = 0; i < leaves.size(); ++i) value[leaves[i]] = (mask >> i) & 1u;
1004
2
            if (!evaluate(root)) return false;
1005
2
        }
1006
0
        return true;
1007
2
    }
1008
1009
0
    bool has_full_case(const sa::CaseStatement& node) const {
1010
0
        for (const auto* attribute : anchor_->getParentScope()->getCompilation().getAttributes(node)) {
1011
0
            if (attribute->name == "full_case") return true;
1012
0
        }
1013
0
        return false;
1014
0
    }
1015
1016
605
    static bool is_all_z(const sa::Expression& expr) {
1017
605
        const sa::Expression* current = &expr;
1018
702
        while (current->kind == sa::ExpressionKind::Conversion) {
1019
97
            current = &current->as<sa::ConversionExpression>().operand();
1020
97
        }
1021
605
        if (current->kind != sa::ExpressionKind::IntegerLiteral) return false;
1022
90
        const auto& value = current->as<sa::IntegerLiteral>().getValue();
1023
91
        for (slang::bitwidth_t i = 0; i < value.getBitWidth(); ++i) {
1024
90
            if (value[i].value != slang::logic_t::Z_VALUE) return false;
1025
90
        }
1026
1
        return value.getBitWidth() > 0;
1027
90
    }
1028
1029
    // Inlines a user function/task call; returns the function result (empty for tasks).
1030
86
    Word call_subroutine(const sa::CallExpression& call) {
1031
86
        const auto* subroutine = std::get<0>(call.subroutine);
1032
86
        const auto formals = subroutine->getArguments();
1033
86
        const auto actuals = call.arguments();
1034
86
        if (++call_depth_ > 32) unsupported("recursive function '" + std::string(subroutine->name) + "'");
1035
86
        std::vector<Word> inputs(formals.size());
1036
233
        for (std::size_t i = 0; i < formals.size(); ++i) {
1037
147
            const auto direction = formals[i]->direction;
1038
147
            if (direction == sa::ArgumentDirection::Out) continue;
1039
146
            if (direction == sa::ArgumentDirection::Ref) unsupported("ref arguments");
1040
146
            inputs[i] = synth::resize(eval(*actuals[i]), type_width(formals[i]->getType()),
1041
146
                                      actuals[i]->type->isSigned());
1042
146
        }
1043
233
        for (std::size_t i = 0; i < formals.size(); ++i) {
1044
147
            Var& formal = var_for(*formals[i]);
1045
147
            st_.cur[formals[i]] = formals[i]->direction == sa::ArgumentDirection::Out
1046
147
                                      ? Word(formal.width, kLatch)
1047
147
                                      : inputs[i];
1048
147
        }
1049
86
        Var* result_var = nullptr;
1050
86
        if (subroutine->returnValVar) {
1051
85
            result_var = &var_for(*subroutine->returnValVar);
1052
85
            st_.cur[subroutine->returnValVar] = Word(result_var->width, kLatch);
1053
85
        }
1054
86
        Var* const outer_return_var = return_var_;
1055
86
        const Bit outer_returned = st_.returned;
1056
86
        return_var_ = result_var;
1057
86
        st_.returned = kZero;
1058
86
        exec(subroutine->getBody());
1059
86
        return_var_ = outer_return_var;
1060
86
        st_.returned = outer_returned;
1061
233
        for (std::size_t i = 0; i < formals.size(); ++i) {
1062
147
            const auto direction = formals[i]->direction;
1063
147
            if (direction != sa::ArgumentDirection::Out &&
1064
147
                direction != sa::ArgumentDirection::InOut) {
1065
146
                continue;
1066
146
            }
1067
1
            const sa::Expression* target = actuals[i];
1068
1
            if (target->kind == sa::ExpressionKind::Assignment) {
1069
1
                target = &target->as<sa::AssignmentExpression>().left();
1070
1
            }
1071
1
            write(*target, st_.cur.at(formals[i]), false);
1072
1
        }
1073
86
        --call_depth_;
1074
86
        return result_var ? st_.cur.at(subroutine->returnValVar) : Word{};
1075
86
    }
1076
1077
4.69k
    void exec_expression(const sa::Expression& expr) {
1078
4.69k
        using K = sa::ExpressionKind;
1079
4.69k
        if (expr.kind == K::Assignment) {
1080
4.32k
            const auto& assignment = expr.as<sa::AssignmentExpression>();
1081
4.32k
            const auto& left = assignment.left();
1082
            // For compound assignments slang folds the operator into right(), with an
1083
            // LValueReference standing for the current value of the target.
1084
4.32k
            const sa::Expression* const outer_reference = lvalue_reference_;
1085
4.32k
            lvalue_reference_ = &left;
1086
4.32k
            Word value = eval(assignment.right());
1087
4.32k
            lvalue_reference_ = outer_reference;
1088
4.32k
            const std::size_t width = type_width(*left.type);
1089
4.32k
            value = synth::resize(value, width, assignment.right().type->isSigned());
1090
4.32k
            write(left, value, assignment.isNonBlocking());
1091
4.32k
            return;
1092
4.32k
        }
1093
363
        if (expr.kind == K::UnaryOp) {
1094
359
            const auto& unary = expr.as<sa::UnaryExpression>();
1095
359
            using U = sa::UnaryOperator;
1096
359
            if (unary.op == U::Preincrement || unary.op == U::Postincrement ||
1097
359
                unary.op == U::Predecrement || unary.op == U::Postdecrement) {
1098
359
                const std::size_t width = type_width(*unary.operand().type);
1099
359
                const Word one = synth::constant_word(1, width);
1100
359
                const Word current = eval(unary.operand());
1101
359
                const bool increment =
1102
359
                    unary.op == U::Preincrement || unary.op == U::Postincrement;
1103
359
                write(unary.operand(), increment ? ops_.add(current, one)
1104
359
                                                 : ops_.sub(current, one),
1105
359
                      false);
1106
359
                return;
1107
359
            }
1108
359
        }
1109
4
        if (expr.kind == K::Call && expr.as<sa::CallExpression>().isSystemCall()) {
1110
3
            return;  // $display and friends have no hardware meaning
1111
3
        }
1112
1
        if (expr.kind == K::Call) {
1113
1
            call_subroutine(expr.as<sa::CallExpression>());
1114
1
            return;
1115
1
        }
1116
0
        unsupported("expression statement");
1117
0
    }
1118
1119
    // Statements after a possible `return` only run when it has not fired.
1120
806
    void exec_sequence(std::span<const sa::Statement* const> list, std::size_t first) {
1121
3.98k
        for (std::size_t i = first; i < list.size(); ++i) {
1122
3.17k
            exec(*list[i]);
1123
3.17k
            if (st_.returned == kZero || i + 1 == list.size()) continue;
1124
0
            if (st_.returned == kOne) return;
1125
0
            exec_branch(graph_.make_not(st_.returned), [&] { exec_sequence(list, i + 1); },
1126
0
                        [] {});
1127
0
            return;
1128
0
        }
1129
806
    }
1130
1131
9.35k
    void exec(const sa::Statement& statement) {
1132
9.35k
        using S = sa::StatementKind;
1133
9.35k
        switch (statement.kind) {
1134
35
            case S::Empty:
1135
35
            case S::ImmediateAssertion:
1136
270
            case S::ConcurrentAssertion:
1137
270
                return;
1138
806
            case S::List:
1139
806
                exec_sequence(statement.as<sa::StatementList>().list, 0);
1140
806
                return;
1141
156
            case S::Return: {
1142
156
                const auto& node = statement.as<sa::ReturnStatement>();
1143
156
                if (node.expr && return_var_ != nullptr) {
1144
156
                    touch_cur(*return_var_) =
1145
156
                        synth::resize(eval(*node.expr), return_var_->width,
1146
156
                                      node.expr->type->isSigned());
1147
156
                }
1148
156
                st_.returned = kOne;
1149
156
                return;
1150
35
            }
1151
2.53k
            case S::Block:
1152
2.53k
                exec(statement.as<sa::BlockStatement>().body);
1153
2.53k
                return;
1154
0
            case S::Timed:
1155
0
                exec(statement.as<sa::TimedStatement>().stmt);
1156
0
                return;
1157
103
            case S::VariableDeclaration: {
1158
103
                const auto& symbol = statement.as<sa::VariableDeclStatement>().symbol;
1159
103
                if (const auto* initializer = symbol.getInitializer()) {
1160
13
                    Var& var = var_for(symbol);
1161
13
                    touch_cur(var) = synth::resize(eval(*initializer), var.width,
1162
13
                                                   initializer->type->isSigned());
1163
13
                }
1164
103
                return;
1165
35
            }
1166
4.33k
            case S::ExpressionStatement:
1167
4.33k
                exec_expression(statement.as<sa::ExpressionStatement>().expr);
1168
4.33k
                return;
1169
923
            case S::Conditional: {
1170
923
                const auto& node = statement.as<sa::ConditionalStatement>();
1171
923
                Bit condition = kOne;
1172
923
                for (const auto& entry : node.conditions) {
1173
923
                    if (entry.pattern) unsupported("pattern-matching if");
1174
923
                    condition = graph_.make_and(condition, truthy(eval(*entry.expr)));
1175
923
                }
1176
923
                exec_branch(
1177
923
                    condition, [&] { exec(node.ifTrue); },
1178
923
                    [&] {
1179
844
                        if (node.ifFalse) exec(*node.ifFalse);
1180
844
                    });
1181
923
                return;
1182
35
            }
1183
221
            case S::Case: {
1184
221
                const auto& node = statement.as<sa::CaseStatement>();
1185
221
                const Word subject = eval(node.expr);
1186
221
                State base = st_;
1187
221
                std::vector<std::pair<Bit, State>> branches;
1188
1.21k
                for (const auto& group : node.items) {
1189
1.21k
                    Bit match = kZero;
1190
2.23k
                    for (const auto* item : group.expressions) {
1191
2.23k
                        match = graph_.make_or(match, case_match(node, subject, *item));
1192
2.23k
                    }
1193
1.21k
                    st_ = base;
1194
1.21k
                    exec(*group.stmt);
1195
1.21k
                    branches.emplace_back(match, std::move(st_));
1196
1.21k
                }
1197
221
                st_ = std::move(base);
1198
221
                if (node.defaultCase) {
1199
221
                    exec(*node.defaultCase);
1200
221
                } else if (!branches.empty() && (has_full_case(node) || covers_all(branches))) {
1201
                    // full_case: uncovered values are don't-care, so reuse the last item
1202
0
                    st_ = std::move(branches.back().second);
1203
0
                    branches.back().first = kZero;
1204
0
                }
1205
1.43k
                for (auto it = branches.rbegin(); it != branches.rend(); ++it) {
1206
1.21k
                    if (it->first == kOne) {
1207
0
                        st_ = std::move(it->second);
1208
1.21k
                    } else if (it->first != kZero) {
1209
1.21k
                        st_ = merge(it->first, it->second, st_);
1210
1.21k
                    }
1211
1.21k
                }
1212
221
                return;
1213
35
            }
1214
13
            case S::ForLoop: {
1215
13
                const auto& loop = statement.as<sa::ForLoopStatement>();
1216
13
                for (const auto* variable : loop.loopVars) {
1217
13
                    if (const auto* initializer = variable->getInitializer()) {
1218
13
                        Var& var = var_for(*variable);
1219
13
                        touch_cur(var) = synth::resize(eval(*initializer), var.width,
1220
13
                                                       initializer->type->isSigned());
1221
13
                    }
1222
13
                }
1223
13
                for (const auto* initializer : loop.initializers) exec_expression(*initializer);
1224
372
                for (int iteration = 0;; ++iteration) {
1225
372
                    if (iteration > 65536) unsupported("loop with more than 65536 iterations");
1226
372
                    if (loop.stopExpr) {
1227
372
                        const Bit condition = truthy(eval(*loop.stopExpr));
1228
372
                        if (condition == kZero) break;
1229
359
                        if (condition != kOne) unsupported("loop with a non-constant bound");
1230
359
                    }
1231
359
                    exec(loop.body);
1232
359
                    for (const auto* step : loop.steps) exec_expression(*step);
1233
359
                }
1234
13
                return;
1235
35
            }
1236
0
            default:
1237
0
                unsupported("statement kind " + std::string(toString(statement.kind)));
1238
9.35k
        }
1239
9.35k
    }
1240
1241
    // ---- process completion ----
1242
2.53k
    void begin_process(bool seq) {
1243
2.53k
        st_ = State{};
1244
2.53k
        seq_ = seq;
1245
2.53k
    }
1246
1247
    // ---- latch inference helpers ----
1248
217k
    bool has_latch(Bit id, std::unordered_map<Bit, bool>& memo) {
1249
217k
        if (id == kLatch) return true;
1250
217k
        const auto found = memo.find(id);
1251
217k
        if (found != memo.end()) return found->second;
1252
122k
        const Node n = graph_.node(id);
1253
122k
        bool result = false;
1254
122k
        switch (n.op) {
1255
3.54k
            case Op::Not: result = has_latch(n.a, memo); break;
1256
35.4k
            case Op::And:
1257
47.9k
            case Op::Or:
1258
55.4k
            case Op::Xor: result = has_latch(n.a, memo) || has_latch(n.b, memo); break;
1259
23.7k
            case Op::Mux:
1260
23.7k
                result = has_latch(n.a, memo) || has_latch(n.b, memo) || has_latch(n.c, memo);
1261
23.7k
                break;
1262
39.8k
            default: break;
1263
122k
        }
1264
122k
        memo[id] = result;
1265
122k
        return result;
1266
122k
    }
1267
1268
    // Data value with unassigned paths replaced by 0, and the condition under which
1269
    // the signal is assigned (the latch enable).
1270
11
    std::pair<Bit, Bit> latch_parts(Bit id, std::unordered_map<Bit, std::pair<Bit, Bit>>& memo) {
1271
11
        if (id == kLatch) return {kZero, kZero};
1272
9
        const auto found = memo.find(id);
1273
9
        if (found != memo.end()) return found->second;
1274
9
        const Node n = graph_.node(id);
1275
9
        std::pair<Bit, Bit> result{id, kOne};
1276
9
        switch (n.op) {
1277
0
            case Op::Not: {
1278
0
                const auto x = latch_parts(n.a, memo);
1279
0
                result = {graph_.make_not(x.first), x.second};
1280
0
                break;
1281
0
            }
1282
2
            case Op::And:
1283
3
            case Op::Or:
1284
3
            case Op::Xor: {
1285
3
                const auto x = latch_parts(n.a, memo);
1286
3
                const auto y = latch_parts(n.b, memo);
1287
3
                const Bit data = n.op == Op::And   ? graph_.make_and(x.first, y.first)
1288
3
                                 : n.op == Op::Or ? graph_.make_or(x.first, y.first)
1289
1
                                                  : graph_.make_xor(x.first, y.first);
1290
3
                result = {data, graph_.make_and(x.second, y.second)};
1291
3
                break;
1292
3
            }
1293
1
            case Op::Mux: {
1294
1
                const auto sel = latch_parts(n.c, memo);
1295
1
                const auto hi = latch_parts(n.b, memo);
1296
1
                const auto lo = latch_parts(n.a, memo);
1297
1
                result = {graph_.make_mux(sel.first, hi.first, lo.first),
1298
1
                          graph_.make_and(sel.second,
1299
1
                                          graph_.make_mux(sel.first, hi.second, lo.second))};
1300
1
                break;
1301
3
            }
1302
5
            default: break;
1303
9
        }
1304
9
        memo[id] = result;
1305
9
        return result;
1306
9
    }
1307
1308
2.34k
    void finish_combinational() {
1309
2.34k
        std::unordered_map<Bit, bool> latch_memo;
1310
2.34k
        std::unordered_map<Bit, std::pair<Bit, Bit>> parts_memo;
1311
2.74k
        for (auto& [symbol, word] : st_.cur) {
1312
2.74k
            Var& var = vars_.at(symbol);
1313
2.74k
            if (!var.registered) continue;
1314
184k
            for (std::size_t i = 0; i < var.width; ++i) {
1315
181k
                Bit value = word[i];
1316
181k
                if (value == kLatch) continue;
1317
32.1k
                if (has_latch(value, latch_memo)) {
1318
2
                    const auto [data, enable] = latch_parts(value, parts_memo);
1319
2
                    if (is_tautology(enable)) {
1320
0
                        value = data;
1321
2
                    } else {
1322
2
                        value = graph_.latch_cell(bit_name(var, i));
1323
2
                        graph_.node(value).a = data;
1324
2
                        graph_.node(value).b = enable;
1325
2
                    }
1326
2
                }
1327
32.1k
                drive(var, i, value);
1328
32.1k
            }
1329
2.58k
        }
1330
2.34k
    }
1331
1332
    struct AsyncLevel {
1333
        Bit active;  // asserted while this asynchronous control is active
1334
        State state;
1335
    };
1336
1337
    std::optional<Bit> level_value(const AsyncLevel& level, const sa::Symbol* key,
1338
2.25k
                                   std::size_t bit, const Var& var) {
1339
2.25k
        const auto nb = level.state.nb.find(key);
1340
2.25k
        if (nb != level.state.nb.end() && nb->second[bit] != var.wires[bit]) {
1341
2.11k
            return nb->second[bit];
1342
2.11k
        }
1343
136
        const auto cur = level.state.cur.find(key);
1344
136
        if (cur != level.state.cur.end() && cur->second[bit] != var.wires[bit]) {
1345
0
            return cur->second[bit];
1346
0
        }
1347
136
        return std::nullopt;
1348
136
    }
1349
1350
    void finish_sequential(Bit clock, bool negedge, const std::vector<AsyncLevel>& levels,
1351
184
                           bool both_edges = false) {
1352
184
        std::set<const sa::Symbol*> keys;
1353
184
        for (const auto& entry : st_.cur) keys.insert(entry.first);
1354
286
        for (const auto& entry : st_.nb) keys.insert(entry.first);
1355
184
        for (const auto& level : levels) {
1356
119
            for (const auto& entry : level.state.cur) keys.insert(entry.first);
1357
195
            for (const auto& entry : level.state.nb) keys.insert(entry.first);
1358
119
        }
1359
292
        for (const auto* key : keys) {
1360
292
            Var& var = vars_.at(key);
1361
292
            if (!var.registered) continue;
1362
292
            const auto cur = st_.cur.find(key);
1363
292
            const auto nb = st_.nb.find(key);
1364
4.50k
            for (std::size_t i = 0; i < var.width; ++i) {
1365
4.21k
                Bit d = cur != st_.cur.end() ? cur->second[i] : var.wires[i];
1366
4.21k
                if (nb != st_.nb.end() && nb->second[i] != var.wires[i]) d = nb->second[i];
1367
4.21k
                Bit act[2] = {kZero, kZero};  // asynchronous clear / set conditions
1368
4.21k
                bool used[2] = {false, false};
1369
4.21k
                Bit earlier = kZero;  // controls listed first take priority
1370
4.21k
                for (const auto& level : levels) {
1371
2.25k
                    const auto value = level_value(level, key, i, var);
1372
2.25k
                    if (!value) {
1373
                        // The control freezes this bit while it is asserted.
1374
136
                        d = graph_.make_mux(level.active, var.wires[i], d);
1375
136
                        continue;
1376
136
                    }
1377
2.11k
                    if (*value != kZero && *value != kOne) {
1378
0
                        unsupported("non-constant asynchronous reset value for " +
1379
0
                                    bit_name(var, i));
1380
0
                    }
1381
2.11k
                    const int kind = *value == kOne ? 1 : 0;
1382
2.11k
                    used[kind] = true;
1383
2.11k
                    act[kind] = graph_.make_or(
1384
2.11k
                        act[kind], graph_.make_and(level.active, graph_.make_not(earlier)));
1385
2.11k
                    earlier = graph_.make_or(earlier, level.active);
1386
2.11k
                }
1387
4.21k
                if (!used[0] && !used[1] && (d == var.wires[i] || d == kLatch)) continue;
1388
3.28k
                if (d == kLatch) d = var.wires[i];
1389
3.28k
                if (both_edges) {
1390
1
                    if (used[0] || used[1]) unsupported("asynchronous reset on a dual-edge flop");
1391
                    // q = p ^ n: p captures (d ^ n) on rising edges, n captures (d ^ p) on
1392
                    // falling edges, so q equals d after either edge.
1393
1
                    const Bit p = graph_.flop(bit_name(var, i) + "_pos", false);
1394
1
                    const Bit n = graph_.flop(bit_name(var, i) + "_neg", true);
1395
1
                    graph_.node(p).a = graph_.make_xor(d, n);
1396
1
                    graph_.node(p).b = clock;
1397
1
                    graph_.node(n).a = graph_.make_xor(d, p);
1398
1
                    graph_.node(n).b = clock;
1399
1
                    drive(var, i, graph_.make_xor(p, n));
1400
1
                    continue;
1401
1
                }
1402
3.28k
                const Bit q = graph_.flop(bit_name(var, i), negedge);
1403
3.28k
                graph_.node(q).a = d;
1404
3.28k
                graph_.node(q).b = clock;
1405
3.28k
                if (used[0] && used[1]) {
1406
1
                    graph_.node(q).c = act[0];
1407
1
                    graph_.node(q).d = act[1];
1408
3.28k
                } else if (used[0] || used[1]) {
1409
2.11k
                    graph_.node(q).c = used[1] ? act[1] : act[0];
1410
2.11k
                    graph_.node(q).reset_value = used[1];
1411
2.11k
                }
1412
3.28k
                drive(var, i, q);
1413
3.28k
            }
1414
292
        }
1415
184
    }
1416
1417
119
    static const sa::Statement& unwrap_single(const sa::Statement& statement) {
1418
119
        const sa::Statement* current = &statement;
1419
225
        for (;;) {
1420
225
            if (current->kind == sa::StatementKind::Block) {
1421
106
                current = &current->as<sa::BlockStatement>().body;
1422
119
            } else if (current->kind == sa::StatementKind::List &&
1423
119
                       current->as<sa::StatementList>().list.size() == 1) {
1424
0
                current = current->as<sa::StatementList>().list[0];
1425
119
            } else {
1426
119
                return *current;
1427
119
            }
1428
225
        }
1429
119
    }
1430
1431
600
    static const sa::Symbol* control_symbol(const sa::Expression* expr) {
1432
717
        while (expr) {
1433
717
            if (expr->kind == sa::ExpressionKind::UnaryOp) {
1434
117
                expr = &expr->as<sa::UnaryExpression>().operand();
1435
600
            } else if (expr->kind == sa::ExpressionKind::Conversion) {
1436
0
                expr = &expr->as<sa::ConversionExpression>().operand();
1437
600
            } else if (expr->kind == sa::ExpressionKind::NamedValue) {
1438
600
                return &expr->as<sa::NamedValueExpression>().symbol;
1439
600
            } else {
1440
0
                return nullptr;
1441
0
            }
1442
717
        }
1443
0
        return nullptr;
1444
600
    }
1445
1446
560
    void run_procedure(const sa::ProceduralBlockSymbol& block) {
1447
560
        using P = sa::ProceduralBlockKind;
1448
560
        if (block.procedureKind == P::Initial || block.procedureKind == P::Final) return;
1449
556
        const sa::Statement* body = &block.getBody();
1450
556
        const sa::TimingControl* timing = nullptr;
1451
556
        if (body->kind == sa::StatementKind::Timed) {
1452
188
            timing = &body->as<sa::TimedStatement>().timing;
1453
188
            body = &body->as<sa::TimedStatement>().stmt;
1454
188
        }
1455
556
        struct Event {
1456
556
            const sa::Expression* expr;
1457
556
            bool negedge;
1458
556
            bool both;
1459
556
        };
1460
556
        std::vector<Event> events;
1461
556
        const auto consider = [&](const sa::TimingControl& control) {
1462
308
            if (control.kind != sa::TimingControlKind::SignalEvent) return;
1463
304
            const auto& event = control.as<sa::SignalEventControl>();
1464
304
            if (event.edge == sa::EdgeKind::None) return;
1465
304
            if (event.edge == sa::EdgeKind::BothEdges) {
1466
0
                events.push_back({&event.expr, false, true});
1467
0
                return;
1468
0
            }
1469
304
            events.push_back({&event.expr, event.edge == sa::EdgeKind::NegEdge, false});
1470
304
        };
1471
556
        if (timing) {
1472
188
            if (timing->kind == sa::TimingControlKind::EventList) {
1473
239
                for (const auto* event : timing->as<sa::EventListControl>().events) {
1474
239
                    consider(*event);
1475
239
                }
1476
119
            } else {
1477
69
                consider(*timing);
1478
69
            }
1479
188
        }
1480
        // "posedge x or negedge x" is a dual-edge clock.
1481
859
        for (std::size_t x = 0; x < events.size(); ++x) {
1482
423
            for (std::size_t y = x + 1; y < events.size(); ++y) {
1483
121
                const auto* sx = control_symbol(events[x].expr);
1484
121
                if (sx && sx == control_symbol(events[y].expr) &&
1485
121
                    events[x].negedge != events[y].negedge && !events[x].both &&
1486
121
                    !events[y].both) {
1487
1
                    events[x].both = true;
1488
1
                    events.erase(events.begin() + static_cast<std::ptrdiff_t>(y));
1489
1
                    break;
1490
1
                }
1491
121
            }
1492
303
        }
1493
556
        const bool sequential = !events.empty();
1494
556
        if (block.procedureKind == P::AlwaysFF && !sequential) {
1495
0
            unsupported("always_ff without a clock edge");
1496
0
        }
1497
556
        begin_process(sequential);
1498
556
        std::vector<AsyncLevel> levels;
1499
556
        Event clock_event{nullptr, false, false};
1500
556
        if (sequential) {
1501
            // Edge events whose signal is tested by the leading if/else-if chain are
1502
            // asynchronous set/reset controls; the remaining one is the clock.
1503
184
            std::vector<char> is_control(events.size(), 0);
1504
184
            std::size_t controls = 0;
1505
303
            while (events.size() - controls > 1) {
1506
119
                const auto& statement = unwrap_single(*body);
1507
119
                if (statement.kind != sa::StatementKind::Conditional) {
1508
0
                    unsupported("asynchronous control without a leading if");
1509
0
                }
1510
119
                const auto& node = statement.as<sa::ConditionalStatement>();
1511
119
                if (node.conditions.size() != 1 || node.conditions[0].pattern || !node.ifFalse) {
1512
0
                    unsupported("asynchronous reset structure");
1513
0
                }
1514
119
                const auto* symbol = control_symbol(node.conditions[0].expr);
1515
119
                std::size_t match = events.size();
1516
359
                for (std::size_t e = 0; e < events.size(); ++e) {
1517
240
                    if (!is_control[e] && control_symbol(events[e].expr) == symbol) match = e;
1518
240
                }
1519
119
                if (!symbol || match == events.size()) {
1520
0
                    unsupported("asynchronous control not matching the sensitivity list");
1521
0
                }
1522
119
                is_control[match] = 1;
1523
119
                ++controls;
1524
119
                const Bit active = truthy(eval(*node.conditions[0].expr));
1525
119
                State saved = std::move(st_);
1526
119
                st_ = State{};
1527
119
                exec(node.ifTrue);
1528
119
                levels.push_back({active, std::move(st_)});
1529
119
                st_ = std::move(saved);
1530
119
                body = node.ifFalse;
1531
119
            }
1532
487
            for (std::size_t e = 0; e < events.size(); ++e) {
1533
303
                if (!is_control[e]) clock_event = events[e];
1534
303
            }
1535
184
        }
1536
556
        Bit clock = kZero;
1537
556
        if (sequential) {
1538
184
            const Word word = eval(*clock_event.expr);
1539
184
            clock = word.empty() ? kZero : word.front();
1540
184
        }
1541
556
        exec(*body);
1542
556
        if (sequential) {
1543
184
            finish_sequential(clock, clock_event.negedge, levels, clock_event.both);
1544
372
        } else {
1545
372
            finish_combinational();
1546
372
        }
1547
556
    }
1548
1549
1.97k
    void run_assign(const sa::Expression& lhs, const sa::Expression& rhs) {
1550
1.97k
        begin_process(false);
1551
1.97k
        write(lhs, synth::resize(eval(rhs), type_width(*lhs.type), rhs.type->isSigned()),
1552
1.97k
              false);
1553
1.97k
        finish_combinational();
1554
1.97k
    }
1555
1556
0
    void link_instance(const sa::InstanceSymbol& child) {
1557
0
        for (const auto* connection : child.getPortConnections()) {
1558
0
            if (connection->port.kind != sa::SymbolKind::Port) continue;
1559
0
            const auto& port = connection->port.as<sa::PortSymbol>();
1560
0
            const auto* expression = connection->getExpression();
1561
0
            if (!expression || !port.internalSymbol) continue;
1562
0
            if (port.internalSymbol->kind != sa::SymbolKind::Net &&
1563
0
                port.internalSymbol->kind != sa::SymbolKind::Variable) {
1564
0
                unsupported("port '" + std::string(port.name) + "' of non-net type");
1565
0
            }
1566
0
            Var& inner = var_for(port.internalSymbol->as<sa::ValueSymbol>());
1567
0
            if (port.direction == sa::ArgumentDirection::In) {
1568
0
                begin_process(false);
1569
0
                const Word value = synth::resize(eval(*expression), inner.width,
1570
0
                                                 expression->type->isSigned());
1571
0
                for (std::size_t i = 0; i < inner.width; ++i) drive(inner, i, value[i]);
1572
0
            } else if (port.direction == sa::ArgumentDirection::Out) {
1573
0
                const sa::Expression* target = expression;
1574
0
                if (target->kind == sa::ExpressionKind::Assignment) {
1575
0
                    target = &target->as<sa::AssignmentExpression>().left();
1576
0
                }
1577
0
                begin_process(false);
1578
0
                write(*target, inner.wires, false);
1579
0
                finish_combinational();
1580
0
            } else {
1581
0
                unsupported("inout port '" + std::string(port.name) + "'");
1582
0
            }
1583
0
        }
1584
0
    }
1585
1586
    // ---- netlist emission ----
1587
    struct Emitter;
1588
};
1589
1590
struct Rebuilder {
1591
    BitGraph& source;
1592
    BitGraph target;
1593
    std::vector<Bit> memo;
1594
    std::vector<char> state;
1595
    std::vector<Bit> pending;
1596
    std::string context;
1597
    std::vector<std::string> trail;
1598
1599
    explicit Rebuilder(BitGraph& graph)
1600
145
        : source(graph), memo(graph.size(), -1), state(graph.size(), 0) {}
1601
1602
274k
    Bit visit(Bit id) {
1603
274k
        if (memo[static_cast<std::size_t>(id)] != -1) return memo[static_cast<std::size_t>(id)];
1604
140k
        const Node& n = source.node(id);
1605
140k
        Bit result = kZero;
1606
140k
        switch (n.op) {
1607
103
            case Op::Const: result = id; break;
1608
0
            case Op::Latch:
1609
0
                throw std::runtime_error(
1610
0
                    "behavioral synthesis: latch inferred (signal not assigned on every "
1611
0
                    "path) affecting " + context +
1612
0
                    " (unassigned path through " +
1613
0
                    (trail.empty() ? std::string("?") : trail.back()) + ")");
1614
7.89k
            case Op::Input: result = target.input(n.name); break;
1615
47.1k
            case Op::Wire: {
1616
47.1k
                auto& mark = state[static_cast<std::size_t>(id)];
1617
47.1k
                if (mark == 1) {
1618
0
                    throw std::runtime_error(
1619
0
                        "behavioral synthesis: combinational loop detected near " + context);
1620
0
                }
1621
47.1k
                mark = 1;
1622
47.1k
                trail.push_back(n.name);
1623
47.1k
                result = n.a < 0 ? kZero : visit(n.a);
1624
47.1k
                trail.pop_back();
1625
47.1k
                mark = 2;
1626
47.1k
                break;
1627
47.1k
            }
1628
2.92k
            case Op::Not: result = target.make_not(visit(n.a)); break;
1629
33.2k
            case Op::And: result = target.make_and(visit(n.a), visit(n.b)); break;
1630
12.2k
            case Op::Or: result = target.make_or(visit(n.a), visit(n.b)); break;
1631
7.47k
            case Op::Xor: result = target.make_xor(visit(n.a), visit(n.b)); break;
1632
25.8k
            case Op::Mux: {
1633
25.8k
                const Bit select = visit(n.c);
1634
25.8k
                const Bit when_true = visit(n.b);
1635
25.8k
                const Bit when_false = visit(n.a);
1636
25.8k
                result = target.make_mux(select, when_true, when_false);
1637
25.8k
                break;
1638
47.1k
            }
1639
3.28k
            case Op::Flop:
1640
3.28k
                result = target.flop(n.name, n.negedge);
1641
3.28k
                target.node(result).reset_value = n.reset_value;
1642
3.28k
                memo[static_cast<std::size_t>(id)] = result;
1643
3.28k
                pending.push_back(id);
1644
3.28k
                return result;
1645
1
            case Op::Tri: result = target.tri(visit(n.a), target.make_not(visit(n.b))); break;  // b becomes active-low
1646
2
            case Op::LatchCell:
1647
2
                result = target.latch_cell(n.name);
1648
2
                memo[static_cast<std::size_t>(id)] = result;
1649
2
                pending.push_back(id);
1650
2
                return result;
1651
140k
        }
1652
136k
        memo[static_cast<std::size_t>(id)] = result;
1653
136k
        return result;
1654
140k
    }
1655
1656
36.3k
    void drain() {
1657
39.6k
        while (!pending.empty()) {
1658
3.28k
            const Bit id = pending.back();
1659
3.28k
            pending.pop_back();
1660
3.28k
            const Node& flop = source.node(id);
1661
3.28k
            context = flop.name;
1662
3.28k
            const Bit data = visit(flop.a);
1663
3.28k
            const Bit clock = visit(flop.b);
1664
3.28k
            const Bit reset = flop.c >= 0 ? target.make_not(visit(flop.c)) : -1;
1665
3.28k
            const Bit set = flop.d >= 0 ? target.make_not(visit(flop.d)) : -1;
1666
3.28k
            auto& created = target.node(memo[static_cast<std::size_t>(id)]);
1667
3.28k
            created.a = data;
1668
3.28k
            created.b = clock;
1669
3.28k
            created.c = reset;
1670
3.28k
            created.d = set;
1671
3.28k
        }
1672
36.3k
    }
1673
};
1674
1675
Module Synthesizer::run(const sa::InstanceSymbol& top, const std::string& top_name,
1676
                        bool preserve_hierarchy,
1677
145
                        const slang::SourceManager& source_manager) {
1678
145
    preserve_hierarchy_ = preserve_hierarchy;
1679
145
    top_prefix_ = top_name + ".";
1680
145
    anchor_ = &top.body;
1681
145
    collect(top.body);
1682
1683
145
    std::vector<Port> ports;
1684
145
    std::vector<Net> nets;
1685
145
    std::vector<Output> outputs;
1686
145
    std::map<Bit, std::string> input_names;
1687
145
    std::unordered_set<std::string> port_names;
1688
2.14k
    for (const auto* port_symbol : top.body.getPortList()) {
1689
2.14k
        if (port_symbol->kind != sa::SymbolKind::Port) continue;
1690
2.14k
        const auto& port = port_symbol->as<sa::PortSymbol>();
1691
2.14k
        if (!port.internalSymbol) continue;
1692
2.14k
        Var& var = var_for(port.internalSymbol->as<sa::ValueSymbol>());
1693
2.14k
        if (port.direction == sa::ArgumentDirection::InOut) {
1694
0
            unsupported("inout port '" + std::string(port.name) + "'");
1695
0
        }
1696
2.14k
        const bool is_input = port.direction == sa::ArgumentDirection::In;
1697
2.14k
        std::optional<std::int64_t> packed_left;
1698
2.14k
        std::optional<std::int64_t> packed_right;
1699
2.14k
        std::optional<std::int64_t> unpacked_left;
1700
2.14k
        std::optional<std::int64_t> unpacked_right;
1701
2.14k
        std::size_t packed_width = var.width;
1702
2.14k
        if (var.is_array) {
1703
24
            packed_width = var.element_width;
1704
24
            unpacked_left = var.range.left;
1705
24
            unpacked_right = var.range.right;
1706
24
            const auto* element_type = var.symbol->getType().getArrayElementType();
1707
24
            if (element_type && element_type->isPackedArray()) {
1708
22
                const auto element_range = element_type->getFixedRange();
1709
22
                if (element_range.width() == var.element_width) {
1710
22
                    packed_left = element_range.left;
1711
22
                    packed_right = element_range.right;
1712
22
                } else {
1713
0
                    packed_left =
1714
0
                        static_cast<std::int64_t>(var.element_width - 1);
1715
0
                    packed_right = 0;
1716
0
                }
1717
22
            } else if (var.element_width > 1) {
1718
2
                packed_left = static_cast<std::int64_t>(var.element_width - 1);
1719
2
                packed_right = 0;
1720
2
            } else {
1721
0
                packed_left = 0;
1722
0
                packed_right = 0;
1723
0
            }
1724
2.11k
        } else if (!var.is_scalar) {
1725
806
            packed_left = var.range.left;
1726
806
            packed_right = var.range.right;
1727
806
        }
1728
2.14k
        ports.emplace_back(
1729
2.14k
            var.name,
1730
2.14k
            is_input ? PortDirection::Input : PortDirection::Output,
1731
2.14k
            var.width, packed_left, packed_right, unpacked_left,
1732
2.14k
            unpacked_right, packed_width);
1733
2.14k
        port_names.insert(var.name);
1734
21.1k
        for (std::size_t i = 0; i < var.width; ++i) {
1735
19.0k
            const std::string name = bit_name(var, i);
1736
19.0k
            nets.emplace_back(name, is_input ? NetType::Input : NetType::Output);
1737
19.0k
            if (is_input) {
1738
9.27k
                drive(var, i, graph_.input(name));
1739
9.78k
            } else {
1740
9.78k
                outputs.push_back({name, &var, i});
1741
9.78k
            }
1742
19.0k
        }
1743
2.14k
    }
1744
1745
145
    for (const auto* child : instances_) {
1746
60
        if (!preserve_hierarchy_ || !child->isModule()) link_instance(*child);
1747
60
    }
1748
145
    for (const auto* net : net_initializers_) {
1749
0
        Var& var = var_for(*net);
1750
0
        begin_process(false);
1751
0
        Word& slot = touch_cur(var);
1752
0
        slot = synth::resize(eval(*net->getInitializer()), var.width,
1753
0
                             net->getInitializer()->type->isSigned());
1754
0
        finish_combinational();
1755
0
    }
1756
1.97k
    for (const auto* assign : assigns_) {
1757
1.97k
        const auto& expression = assign->getAssignment().as<sa::AssignmentExpression>();
1758
1.97k
        run_assign(expression.left(), expression.right());
1759
1.97k
    }
1760
560
    for (const auto* block : procedures_) run_procedure(*block);
1761
1762
145
    if (preserve_hierarchy_) {
1763
145
        std::map<std::string, Var*> internal_vars;
1764
4.31k
        for (auto& [symbol, var] : vars_) {
1765
4.31k
            (void)symbol;
1766
4.31k
            if (var.registered && !port_names.count(var.name)) {
1767
2.00k
                internal_vars.emplace(var.name, &var);
1768
2.00k
            }
1769
4.31k
        }
1770
2.00k
        for (const auto& [name, var] : internal_vars) {
1771
32.7k
            for (std::size_t bit = 0; bit < var->width; ++bit) {
1772
30.7k
                if (var->driven[bit]) {
1773
26.5k
                    outputs.push_back({bit_name(*var, bit), var, bit});
1774
26.5k
                }
1775
30.7k
            }
1776
2.00k
        }
1777
145
    }
1778
1779
145
    Rebuilder rebuild(graph_);
1780
145
    std::vector<Bit> roots;
1781
36.3k
    for (const auto& output : outputs) {
1782
36.3k
        rebuild.context = output.name;
1783
36.3k
        roots.push_back(rebuild.visit(output.var->wires[output.bit]));
1784
36.3k
        rebuild.drain();
1785
36.3k
    }
1786
145
    BitGraph& g = rebuild.target;
1787
1788
145
    std::vector<std::string> net_name(g.size());
1789
69.2k
    for (std::size_t i = 0; i < g.size(); ++i) {
1790
69.1k
        if (g.node(static_cast<Bit>(i)).op == Op::Input) {
1791
7.89k
            net_name[i] = g.node(static_cast<Bit>(i)).name;
1792
7.89k
        }
1793
69.1k
    }
1794
145
    std::vector<char> claimed(g.size(), 0);
1795
36.5k
    for (std::size_t i = 0; i < outputs.size(); ++i) {
1796
36.3k
        const auto root = static_cast<std::size_t>(roots[i]);
1797
36.3k
        const Op op = g.node(roots[i]).op;
1798
36.3k
        if (op != Op::Input && op != Op::Const && net_name[root].empty()) {
1799
12.1k
            net_name[root] = outputs[i].name;
1800
12.1k
            claimed[root] = 1;
1801
12.1k
        }
1802
36.3k
    }
1803
145
    std::unordered_set<std::string> used_names;
1804
19.0k
    for (const auto& net : nets) used_names.insert(net.get_name());
1805
68.8k
    for (std::size_t i = 3; i < g.size(); ++i) {
1806
68.7k
        if (!net_name[i].empty()) continue;
1807
48.6k
        const Node& n = g.node(static_cast<Bit>(i));
1808
48.6k
        const bool is_state = n.op == Op::Flop || n.op == Op::LatchCell;
1809
48.6k
        std::string name = is_state && !n.name.empty() ? n.name : "";
1810
48.6k
        if (name.empty() || !used_names.insert(name).second) {
1811
48.6k
            name = (is_state ? "_q" : "_n") + std::to_string(i);
1812
48.6k
        }
1813
48.6k
        net_name[i] = std::move(name);
1814
48.6k
    }
1815
1816
145
    std::vector<Instance> instances;
1817
145
    bool tie[2] = {false, false};
1818
159k
    const auto net_of = [&](Bit id) -> std::string {
1819
159k
        if (id == kZero || id == kOne) {
1820
16.0k
            tie[id] = true;
1821
16.0k
            return id == kOne ? "__tie1" : "__tie0";
1822
16.0k
        }
1823
143k
        return net_name[static_cast<std::size_t>(id)];
1824
159k
    };
1825
145
    std::map<Bit, std::string> inverted_clocks;
1826
145
    int counter = 0;
1827
145
    const auto make_instance = [&](const std::string& type,
1828
80.6k
                                   std::vector<PinConnection> pins) {
1829
80.6k
        instances.emplace_back("__g" + std::to_string(counter++), type, std::move(pins));
1830
80.6k
    };
1831
68.8k
    for (std::size_t i = 3; i < g.size(); ++i) {
1832
68.7k
        const Node& n = g.node(static_cast<Bit>(i));
1833
68.7k
        const std::string& out = net_name[i];
1834
68.7k
        switch (n.op) {
1835
2.67k
            case Op::Not: make_instance("INV", {{"A", net_of(n.a)}, {"Y", out}}); break;
1836
24.6k
            case Op::And:
1837
24.6k
                make_instance("AND2", {{"A", net_of(n.a)}, {"B", net_of(n.b)}, {"Y", out}});
1838
24.6k
                break;
1839
5.54k
            case Op::Or:
1840
5.54k
                make_instance("OR2", {{"A", net_of(n.a)}, {"B", net_of(n.b)}, {"Y", out}});
1841
5.54k
                break;
1842
6.15k
            case Op::Xor:
1843
6.15k
                make_instance("XOR2", {{"A", net_of(n.a)}, {"B", net_of(n.b)}, {"Y", out}});
1844
6.15k
                break;
1845
18.5k
            case Op::Mux:
1846
18.5k
                make_instance("MUX2", {{"A0", net_of(n.a)}, {"A1", net_of(n.b)},
1847
18.5k
                                       {"S", net_of(n.c)}, {"Y", out}});
1848
18.5k
                break;
1849
3.28k
            case Op::Flop: {
1850
3.28k
                std::string clock = net_of(n.b);
1851
3.28k
                if (n.negedge) {
1852
1
                    auto found = inverted_clocks.find(n.b);
1853
1
                    if (found == inverted_clocks.end()) {
1854
1
                        std::string inverted = "_clkn" + std::to_string(n.b);
1855
1
                        make_instance("INV", {{"A", clock}, {"Y", inverted}});
1856
1
                        nets.emplace_back(inverted, NetType::Internal);
1857
1
                        found = inverted_clocks.emplace(n.b, std::move(inverted)).first;
1858
1
                    }
1859
1
                    clock = found->second;
1860
1
                }
1861
3.28k
                if (n.c >= 0 && n.d >= 0) {
1862
1
                    make_instance("DFFSR", {{"D", net_of(n.a)}, {"CLK", clock},
1863
1
                                            {"RESET_B", net_of(n.c)}, {"SET_B", net_of(n.d)},
1864
1
                                            {"Y", out}});
1865
3.28k
                } else if (n.c >= 0) {
1866
2.11k
                    make_instance(n.reset_value ? "DFFS" : "DFFR",
1867
2.11k
                                  {{"D", net_of(n.a)}, {"CLK", clock},
1868
2.11k
                                   {n.reset_value ? "SET_B" : "RESET_B", net_of(n.c)},
1869
2.11k
                                   {"Y", out}});
1870
2.11k
                } else {
1871
1.16k
                    make_instance("DFF", {{"D", net_of(n.a)}, {"CLK", clock}, {"Y", out}});
1872
1.16k
                }
1873
3.28k
                break;
1874
0
            }
1875
1
            case Op::Tri:
1876
1
                make_instance("TRIBUF", {{"A", net_of(n.a)}, {"TE_B", net_of(n.b)},
1877
1
                                         {"Y", out}});
1878
1
                break;
1879
2
            case Op::LatchCell:
1880
2
                make_instance("LATCH", {{"D", net_of(n.a)}, {"GATE", net_of(n.b)}, {"Y", out}});
1881
2
                break;
1882
7.89k
            default: break;
1883
68.7k
        }
1884
68.7k
    }
1885
36.5k
    for (std::size_t i = 0; i < outputs.size(); ++i) {
1886
36.3k
        if (!claimed[static_cast<std::size_t>(roots[i])]) {
1887
19.6k
            make_instance("BUF", {{"A", net_of(roots[i])}, {"Y", outputs[i].name}});
1888
19.6k
        }
1889
36.3k
    }
1890
435
    for (int value = 0; value < 2; ++value) {
1891
290
        if (!tie[value]) continue;
1892
109
        const std::string name = value ? "__tie1" : "__tie0";
1893
109
        make_instance(value ? "TIEHI" : "TIELO", {{"Y", name}});
1894
109
        nets.emplace_back(name, NetType::Internal);
1895
109
    }
1896
68.8k
    for (std::size_t i = 3; i < g.size(); ++i) {
1897
68.7k
        const Op op = g.node(static_cast<Bit>(i)).op;
1898
68.7k
        if (op == Op::Input || claimed[i]) continue;
1899
48.6k
        nets.emplace_back(net_name[i], NetType::Internal);
1900
48.6k
    }
1901
145
    if (preserve_hierarchy_) {
1902
145
        std::unordered_set<std::string> net_names;
1903
67.8k
        for (const auto& net : nets) net_names.insert(net.get_name());
1904
4.31k
        for (const auto& [symbol, var] : vars_) {
1905
4.31k
            (void)symbol;
1906
4.31k
            if (!var.registered || port_names.count(var.name) ||
1907
4.31k
                !net_names.insert(var.name).second) {
1908
2.30k
                continue;
1909
2.30k
            }
1910
2.00k
            std::optional<std::int64_t> packed_left;
1911
2.00k
            std::optional<std::int64_t> packed_right;
1912
2.00k
            std::optional<std::int64_t> unpacked_left;
1913
2.00k
            std::optional<std::int64_t> unpacked_right;
1914
2.00k
            std::size_t packed_width = var.width;
1915
2.00k
            if (var.is_array) {
1916
27
                packed_width = var.element_width;
1917
27
                unpacked_left = var.range.left;
1918
27
                unpacked_right = var.range.right;
1919
27
                const auto* element_type =
1920
27
                    var.symbol->getType().getArrayElementType();
1921
27
                if (element_type && element_type->isPackedArray()) {
1922
24
                    const auto element_range = element_type->getFixedRange();
1923
24
                    if (element_range.width() == var.element_width) {
1924
24
                        packed_left = element_range.left;
1925
24
                        packed_right = element_range.right;
1926
24
                    } else {
1927
0
                        packed_left =
1928
0
                            static_cast<std::int64_t>(var.element_width - 1);
1929
0
                        packed_right = 0;
1930
0
                    }
1931
24
                } else if (var.element_width > 1) {
1932
2
                    packed_left =
1933
2
                        static_cast<std::int64_t>(var.element_width - 1);
1934
2
                    packed_right = 0;
1935
2
                } else {
1936
1
                    packed_left = 0;
1937
1
                    packed_right = 0;
1938
1
                }
1939
1.97k
            } else if (!var.is_scalar) {
1940
881
                packed_left = var.range.left;
1941
881
                packed_right = var.range.right;
1942
881
            }
1943
2.00k
            nets.emplace_back(var.name, NetType::Internal, var.width,
1944
2.00k
                              packed_left, packed_right, unpacked_left,
1945
2.00k
                              unpacked_right, packed_width);
1946
2.00k
        }
1947
145
    }
1948
145
    std::vector<Module> child_modules;
1949
145
    if (preserve_hierarchy_) {
1950
145
        for (const auto* child : instances_) {
1951
60
            if (!child->isModule()) continue;
1952
1953
60
            std::vector<PinConnection> connections;
1954
1.11k
            for (const auto* connection : child->getPortConnections()) {
1955
1.11k
                if (!connection->getExpression()) continue;
1956
1.08k
                connections.emplace_back(
1957
1.08k
                    std::string(connection->port.name),
1958
1.08k
                    expression_source(*connection->getExpression(),
1959
1.08k
                                      source_manager, top_prefix_));
1960
1.08k
            }
1961
60
            instances.emplace_back(
1962
60
                std::string(child->name),
1963
60
                std::string(child->getDefinition().name),
1964
60
                std::move(connections));
1965
1966
60
            Synthesizer child_synthesizer;
1967
60
            auto mapped_child = child_synthesizer.run(
1968
60
                *child, std::string(child->getHierarchicalPath()), true,
1969
60
                source_manager);
1970
60
            child_modules.emplace_back(
1971
60
                mapped_child.get_name(), mapped_child.get_ports(),
1972
60
                mapped_child.get_nets(), mapped_child.get_instances(),
1973
60
                mapped_child.get_assignments(), mapped_child.is_behavioral(),
1974
60
                std::string(child->name), mapped_child.get_child_modules());
1975
60
        }
1976
145
    }
1977
1978
145
    return Module(std::string(top.getDefinition().name), std::move(ports),
1979
145
                  std::move(nets), std::move(instances), {},
1980
145
                  false, {}, std::move(child_modules));
1981
145
}
1982
1983
}  // namespace
1984
1985
Module detail::lower_behavioral_rtl(
1986
    const std::shared_ptr<ParsedVerilogContext>& context, const std::string& top,
1987
    const std::map<std::string, std::string>& parameters,
1988
85
    bool preserve_hierarchy) {
1989
85
    if (!context || !context->compilation) {
1990
0
        throw std::runtime_error(
1991
0
            "behavioral RTL has no retained Slang parse context; create it with parse_verilog");
1992
0
    }
1993
85
    std::lock_guard lock(context->mutex);
1994
85
    auto& driver = context->driver;
1995
85
    struct DriverOptionsRestore {
1996
85
        slang::driver::Driver& driver;
1997
85
        std::vector<std::string> top_modules;
1998
85
        std::vector<std::string> parameter_overrides;
1999
85
        bool active = false;
2000
2001
85
        ~DriverOptionsRestore() {
2002
85
            if (!active) return;
2003
3
            driver.options.topModules = std::move(top_modules);
2004
3
            driver.options.paramOverrides = std::move(parameter_overrides);
2005
3
        }
2006
85
    } restore_options{driver, driver.options.topModules,
2007
85
                      driver.options.paramOverrides};
2008
85
    slang::ast::Compilation* compilation = context->compilation.get();
2009
85
    const auto find_instance = [&](slang::ast::Compilation& candidate) {
2010
85
        const slang::ast::InstanceSymbol* found = nullptr;
2011
85
        const auto search_scope = [&](const auto& self,
2012
3.36k
                                      const slang::ast::Scope& scope) -> void {
2013
101k
            for (const auto& member : scope.members()) {
2014
101k
                switch (member.kind) {
2015
465
                    case slang::ast::SymbolKind::Instance: {
2016
465
                        const auto& instance =
2017
465
                            member.as<slang::ast::InstanceSymbol>();
2018
465
                        if (instance.getDefinition().name == top) {
2019
36
                            found = &instance;
2020
36
                            return;
2021
36
                        }
2022
429
                        if (instance.isModule()) self(self, instance.body);
2023
429
                        break;
2024
465
                    }
2025
3.24k
                    case slang::ast::SymbolKind::GenerateBlock: {
2026
3.24k
                        const auto& block =
2027
3.24k
                            member.as<slang::ast::GenerateBlockSymbol>();
2028
3.24k
                        if (!block.isUninstantiated) self(self, block);
2029
3.24k
                        break;
2030
465
                    }
2031
194
                    case slang::ast::SymbolKind::GenerateBlockArray: {
2032
194
                        const auto& array =
2033
194
                            member.as<slang::ast::GenerateBlockArraySymbol>();
2034
1.25k
                        for (const auto* entry : array.entries) {
2035
1.25k
                            if (!entry->isUninstantiated) self(self, *entry);
2036
1.25k
                            if (found) return;
2037
1.25k
                        }
2038
194
                        break;
2039
194
                    }
2040
97.3k
                    default:
2041
97.3k
                        break;
2042
101k
                }
2043
101k
                if (found) return;
2044
101k
            }
2045
3.36k
        };
2046
85
        for (const auto* instance : candidate.getRoot().topInstances) {
2047
85
            if (instance->getDefinition().name == top) {
2048
49
                found = instance;
2049
49
                break;
2050
49
            }
2051
36
            if (instance->isModule()) search_scope(search_scope, instance->body);
2052
36
            if (found) break;
2053
36
        }
2054
85
        return found;
2055
85
    };
2056
2057
85
    std::unique_ptr<slang::ast::Compilation> specialized_compilation;
2058
85
    if (!parameters.empty()) {
2059
3
        restore_options.active = true;
2060
3
        driver.options.topModules = {top};
2061
3
        driver.options.paramOverrides.clear();
2062
3
        for (const auto& [name, value] : parameters) {
2063
3
            driver.options.paramOverrides.push_back(name + "=" + value);
2064
3
        }
2065
3
        specialized_compilation = driver.createCompilation();
2066
3
        driver.reportCompilation(*specialized_compilation, true);
2067
3
        if (!driver.reportDiagnostics(true)) {
2068
0
            throw std::runtime_error(
2069
0
                "slang failed to elaborate the Verilog design:\n" +
2070
0
                driver.textDiagClient->getString());
2071
0
        }
2072
3
        compilation = specialized_compilation.get();
2073
3
    }
2074
2075
85
    const auto* selected_top = find_instance(*compilation);
2076
85
    if (!selected_top) {
2077
0
        throw std::runtime_error("top module '" + top + "' not found in parsed design");
2078
0
    }
2079
2080
85
    Synthesizer synthesizer;
2081
85
    return synthesizer.run(
2082
85
        *selected_top, std::string(selected_top->getHierarchicalPath()),
2083
85
        preserve_hierarchy, driver.sourceManager);
2084
85
}
2085
2086
}  // namespace labneura::eda