vj-sim 0.3.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! A module body's items as one flat list.
//!
//! A generate block (`if`/`case`/`for` generate, LRM 1800-2023 ยง27) is a
//! nested scope, but everything declared in an instantiated one -- signals,
//! processes, continuous assignments, subroutines, instances -- belongs to
//! the enclosing module instance and runs with it. Every pass that
//! enumerates a module's contents goes through [`module_items`], so they
//! all agree on which items exist and in what order (member indices are
//! used as keys, e.g. `SymbolKey`).

use crate::symid::SymbolUid;
use sv_lang::{DefinitionKind, Expression, Symbol};
use sv_lang_kinds::SymbolKind;

/// `body`'s members, each instantiated generate block (and each
/// instantiated iteration of a generate loop) replaced by its own items,
/// recursively, in declaration order. Uninstantiated branches are dropped.
pub fn module_items<'d>(body: &Symbol<'d>) -> Vec<Symbol<'d>> {
    let mut out = Vec::new();
    push_items(body, &mut out);
    out
}

/// The static checker instances of `body` (LRM 17.3), nested ones included,
/// outermost first, in declaration order: the instances [`module_items`]
/// flattens away.
pub fn checker_instances<'d>(body: &Symbol<'d>) -> Vec<Symbol<'d>> {
    fn walk<'d>(scope: &Symbol<'d>, out: &mut Vec<Symbol<'d>>) {
        for m in scope.members() {
            if let Some(blocks) = generate_children(&m) {
                for b in blocks {
                    walk(&b, out);
                }
            } else if m.kind() == SymbolKind::CheckerInstance {
                out.push(m);
                walk(&m, out);
            } else if let Some(elements) = checker_array_elements(&m) {
                for e in elements {
                    out.push(e);
                    walk(&e, out);
                }
            } else if m.kind() == SymbolKind::StatementBlock {
                // A procedural instance (17.3) is declared in the scope of the
                // statement that instantiates it.
                walk(&m, out);
            }
        }
    }
    let mut out = Vec::new();
    walk(body, &mut out);
    out
}

/// One checker instantiation statement (LRM 17.3: a checker instantiated in an
/// `always` or `initial` procedure).
#[derive(Clone, Copy)]
pub struct ProceduralChecker<'d> {
    /// The procedure the statement is in.
    pub block: Symbol<'d>,
    /// The statement.
    pub stmt: sv_lang::Statement<'d>,
    /// The instance it instantiates.
    pub instance: Symbol<'d>,
}

/// The procedural checker instantiations of `body`'s procedures (generate
/// blocks and static checker instances' included), in source order. A
/// procedural instance is a member of its scope like a static one, so only the
/// statements tell the two apart; designs with no checker instance at all skip
/// the walk.
pub fn procedural_checkers<'d>(body: &Symbol<'d>) -> Vec<ProceduralChecker<'d>> {
    if checker_instances(body).is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    for block in module_items(body) {
        if block.kind() != SymbolKind::ProceduralBlock {
            continue;
        }
        let Some(root) = crate::process::cfg::proc_body(&block) else {
            continue;
        };
        let mut stack = vec![root.as_sem_node()];
        while let Some(n) = stack.pop() {
            if let Some(stmt) = n.as_statement() {
                for instance in stmt.procedural_checker_instances() {
                    out.push(ProceduralChecker {
                        block,
                        stmt,
                        instance,
                    });
                }
            }
            let mut kids = n.children();
            kids.reverse();
            stack.extend(kids);
        }
    }
    out
}

/// The `CheckerInstanceBody` of checker instance `inst`: the scope slang's
/// analysis keys its results by. The body is not a member of anything, so it
/// is reached through a member's parent; `None` for an instance with no
/// members (nothing to analyze).
pub fn checker_instance_body<'d>(inst: &Symbol<'d>) -> Option<Symbol<'d>> {
    inst.members().next()?.parent()
}

/// One output formal argument of a checker instance and its connection
/// (LRM 17.3: "as if there were continuous assignments, executed in the
/// Reactive region, of the checker's output formal arguments to their
/// corresponding actual arguments").
#[derive(Clone, Copy)]
pub struct CheckerOutput<'d> {
    /// The checker's output formal: a variable of the checker.
    pub formal: Symbol<'d>,
    /// slang's `actual = <formal value>` assignment (its right-hand side is
    /// an empty argument standing for the formal), or `None` for an output
    /// left unconnected.
    pub assign: Option<sv_lang::Expression<'d>>,
    /// The formal's initial value (`output int ctr = 0`), evaluated in the
    /// instantiation's context. `None` when it declares none.
    pub initial: Option<sv_lang::Expression<'d>>,
}

/// The output formals of checker instance `inst`, in port order. Input
/// formals (`AssertionPort`s) and outputs (`FormalArgument`s) are listed by
/// the instance's members in the same order as its connections.
pub fn checker_outputs<'d>(inst: &Symbol<'d>) -> Vec<CheckerOutput<'d>> {
    let formals = inst.members().filter(|m| {
        matches!(
            m.kind(),
            SymbolKind::AssertionPort | SymbolKind::FormalArgument
        )
    });
    let mut out = Vec::new();
    for (formal, conn) in formals.zip(inst.checker_instance_connections()) {
        if formal.kind() == SymbolKind::FormalArgument {
            out.push(CheckerOutput {
                formal,
                assign: conn.actual().and_then(|a| a.as_expression()),
                initial: conn.output_initial_expr(),
            });
        }
    }
    out
}

/// The output formal of a checker instance that `formal` is, with its
/// instance's connection data: `None` for any other symbol.
pub fn checker_output_of<'d>(formal: &Symbol<'d>) -> Option<CheckerOutput<'d>> {
    if formal.kind() != SymbolKind::FormalArgument {
        return None;
    }
    let inst = formal.parent()?.checker_instance_body_parent_instance()?;
    checker_outputs(&inst)
        .into_iter()
        .find(|o| o.formal.uid() == formal.uid())
}

/// Whether `sym` is declared in a checker (LRM 17): the first instance or
/// checker instance body up its parent chain is a checker instance's. A
/// checker's procedures and continuous assignments are scheduled in the
/// Reactive region (LRM 17.7.3).
pub fn is_in_checker(sym: &Symbol<'_>) -> bool {
    let mut cur = Some(*sym);
    while let Some(s) = cur {
        let kind = s.kind();
        if kind == SymbolKind::CheckerInstanceBody {
            return true;
        }
        if kind == SymbolKind::InstanceBody {
            return false;
        }
        cur = s.parent();
    }
    false
}

/// Whether `sym` is declared in a `program` (LRM 24.3): the instance body it
/// belongs to ([`enclosing_instance_body`]) was instantiated from a program
/// definition. A program's `initial` blocks and the code they run are
/// scheduled in the Reactive region (LRM 4.4.2.6, 24.3.1), after the design
/// has settled for the time step, like a checker's ([`is_in_checker`]).
pub fn is_in_program(sym: &Symbol<'_>) -> bool {
    enclosing_instance_body(sym)
        .and_then(|b| b.instance_body_definition())
        .is_some_and(|d| d.definition_kind() == Some(DefinitionKind::Program))
}

/// The instance body whose items `sym` is one of: the first `InstanceBody`
/// up its parent chain, except that a checker instance's body (LRM 17.3)
/// hands over to the instance body that instantiates the checker -- its
/// items run there ([`module_items`]), although its `parent()` is the scope
/// the checker was declared in. `None` for a symbol of no instance (a
/// package's).
pub fn enclosing_instance_body<'d>(sym: &Symbol<'d>) -> Option<Symbol<'d>> {
    let mut cur = Some(*sym);
    while let Some(s) = cur {
        let kind = s.kind();
        if kind == SymbolKind::InstanceBody {
            return Some(s);
        }
        cur = if kind == SymbolKind::CheckerInstanceBody {
            s.checker_instance_body_parent_instance()?.parent()
        } else {
            s.parent()
        };
    }
    None
}

/// The package (or compilation unit) whose items `sym` is one of, `None` for
/// a symbol of an instance.
pub fn enclosing_package<'d>(sym: &Symbol<'d>) -> Option<Symbol<'d>> {
    if enclosing_instance_body(sym).is_some() {
        return None;
    }
    let mut cur = sym.parent();
    while let Some(p) = cur {
        if matches!(p.kind(), SymbolKind::Package | SymbolKind::CompilationUnit) {
            return Some(p);
        }
        cur = p.parent();
    }
    None
}

/// The instantiated generate blocks nested anywhere in `body` (the scopes
/// [`module_items`] flattens), outermost first.
pub fn generate_scopes<'d>(body: &Symbol<'d>) -> Vec<Symbol<'d>> {
    let mut out = Vec::new();
    let mut stack = vec![*body];
    while let Some(scope) = stack.pop() {
        for m in scope.members() {
            if let Some(blocks) = generate_children(&m) {
                for b in blocks {
                    out.push(b);
                    stack.push(b);
                }
            } else if m.kind() == SymbolKind::CheckerInstance
                || m.kind() == SymbolKind::StatementBlock
            {
                // Its generate blocks flatten into the enclosing instance
                // like its other items ([`push_items`]); so do those of a
                // procedural checker declared in a statement block.
                stack.push(m);
            } else if let Some(elements) = checker_array_elements(&m) {
                stack.extend(elements);
            }
        }
    }
    out
}

/// The checker instances an array of checker instances `m` (LRM 17.3,
/// `name_of_instance` with unpacked dimensions) stands for, every dimension
/// flattened, in element order; `None` for any other symbol.
pub fn checker_array_elements<'d>(m: &Symbol<'d>) -> Option<Vec<Symbol<'d>>> {
    fn flatten<'d>(a: &Symbol<'d>, out: &mut Vec<Symbol<'d>>) -> bool {
        for e in a.instance_array_elements() {
            if e.kind() == SymbolKind::CheckerInstance {
                out.push(e);
            } else if e.kind() != SymbolKind::InstanceArray || !flatten(&e, out) {
                // A module or primitive array: not a checker array.
                return false;
            }
        }
        true
    }
    if m.kind() != SymbolKind::InstanceArray {
        return None;
    }
    let mut out = Vec::new();
    (flatten(m, &mut out) && !out.is_empty()).then_some(out)
}

/// The instantiated blocks `m` stands for, if it is a generate construct.
fn generate_children<'d>(m: &Symbol<'d>) -> Option<Vec<Symbol<'d>>> {
    let kind = m.kind();
    if kind == SymbolKind::GenerateBlock {
        return Some(if m.generate_block_is_uninstantiated() {
            Vec::new()
        } else {
            vec![*m]
        });
    }
    if kind == SymbolKind::GenerateBlockArray {
        return Some(
            m.members()
                .filter(|e| {
                    e.kind() == SymbolKind::GenerateBlock && !e.generate_block_is_uninstantiated()
                })
                .collect(),
        );
    }
    None
}

fn push_items<'d>(scope: &Symbol<'d>, out: &mut Vec<Symbol<'d>>) {
    for m in scope.members() {
        match generate_children(&m) {
            Some(blocks) => {
                for b in blocks {
                    push_items(&b, out);
                }
            }
            // A checker instance (LRM 17.3) is a pseudo-instance: its
            // body's items belong to the enclosing instance and run with
            // it, as a generate block's do. Its input formals are
            // `AssertionPort` clones whose actuals slang already
            // substituted into every body expression, so they are not
            // items.
            None if m.kind() == SymbolKind::CheckerInstance => push_items(&m, out),
            None if checker_array_elements(&m).is_some() => {
                for e in checker_array_elements(&m).unwrap_or_default() {
                    push_items(&e, out);
                }
            }
            None if m.kind() == SymbolKind::AssertionPort => {}
            None if m.kind() == SymbolKind::StatementBlock => {
                out.push(m);
                push_block_checkers(&m, out);
            }
            None => out.push(m),
        }
    }
}

/// The items of the procedural checker instances declared in the statement
/// block `block` (LRM 17.3), nested blocks' included. A procedural instance's
/// own variables, functions and procedures exist whether or not the
/// instantiating procedure ever reaches the statement ("each of the three
/// instantiations has its own version of sum").
fn push_block_checkers<'d>(block: &Symbol<'d>, out: &mut Vec<Symbol<'d>>) {
    for m in block.members() {
        if m.kind() == SymbolKind::CheckerInstance {
            push_items(&m, out);
        } else if m.kind() == SymbolKind::StatementBlock {
            push_block_checkers(&m, out);
        }
    }
}

/// What a free checker variable (a `rand` checker variable, LRM 17.7) is to
/// assume-based randomization (17.7.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FreeVarKind {
    /// `rand const`: a random value fixed at initialization.
    Const,
    /// Not assigned by the checker: the simulator chooses its values.
    Active,
    /// The left-hand side of a checker variable assignment (17.7.1): it only
    /// takes a random initial value.
    Inactive,
}

/// The kind of `var` as a free checker variable, `None` for any other symbol.
pub fn free_var_kind(var: &Symbol<'_>) -> Option<FreeVarKind> {
    if var.kind() != SymbolKind::Variable
        || !var
            .variable_flags()
            .contains(sv_lang::VariableFlags::CHECKER_FREE_VARIABLE)
    {
        return None;
    }
    if var.variable_flags().contains(sv_lang::VariableFlags::CONST) {
        return Some(FreeVarKind::Const);
    }
    let assigned = var
        .parent()
        .and_then(|b| b.checker_instance_body_parent_instance())
        .is_some_and(|inst| checker_assigned(&inst).contains(&var.uid()));
    Some(if assigned {
        FreeVarKind::Inactive
    } else {
        FreeVarKind::Active
    })
}

/// The variables the procedures and continuous assignments of checker instance
/// `inst` assign (17.7.1): whatever an assignment's left-hand side names.
fn checker_assigned(inst: &Symbol<'_>) -> std::collections::HashSet<crate::symid::SymbolId> {
    let mut out = std::collections::HashSet::new();
    let mut stack = Vec::new();
    for m in module_items(inst) {
        if m.kind() == SymbolKind::ProceduralBlock {
            stack.extend(crate::process::cfg::proc_body(&m).map(|b| b.as_sem_node()));
        } else if m.kind() == SymbolKind::ContinuousAssign {
            stack.extend(m.continuous_assign_assignment().map(|e| e.as_sem_node()));
        }
    }
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression()
            && e.kind() == sv_lang::kinds::ExpressionKind::Assignment
            && let Some(lhs) = e.left()
        {
            let mut lv = vec![lhs.as_sem_node()];
            while let Some(x) = lv.pop() {
                if let Some(xe) = x.as_expression()
                    && crate::symid::is_value_name(xe.kind())
                    && let Some(s) = xe.referenced_symbol()
                {
                    out.insert(s.uid());
                }
                lv.extend(x.children());
            }
        }
        stack.extend(n.children());
    }
    out
}

/// The generator state a free checker variable's random values start from:
/// its hierarchical path, hashed (17.7.2; stable from run to run, distinct per
/// variable and instance).
pub fn free_var_seed(var: &Symbol<'_>) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in var.hierarchical_path().bytes() {
        h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// Per checker instance of `body` that declares active free variables
/// ([`FreeVarKind::Active`]): the instance and those variables.
pub fn free_var_groups<'d>(body: &Symbol<'d>) -> Vec<(Symbol<'d>, Vec<Symbol<'d>>)> {
    checker_instances(body)
        .into_iter()
        .filter_map(|inst| {
            let vars: Vec<Symbol<'d>> = inst
                .members()
                .filter(|m| free_var_kind(m) == Some(FreeVarKind::Active))
                .collect();
            (!vars.is_empty()).then_some((inst, vars))
        })
        .collect()
}

/// [`module_items`], then [`static_procedural_vars`]: everything in `body`
/// that has storage of the instance's own (a STATE slot), in the order
/// slots are numbered.
pub fn state_items<'d>(body: &Symbol<'d>) -> Vec<Symbol<'d>> {
    let mut out = module_items(body);
    out.extend(static_procedural_vars(body));
    out
}

/// The static variables `body`'s procedural code declares: those of its
/// tasks and functions, their formal arguments included (not a function's
/// result variable), and those of the
/// blocks in its processes and subroutines. LRM 1800-2023 ยง6.21: each has
/// one copy per instance, shared by every call and every process -- STATE
/// storage, like a module variable, rather than a process's frame.
pub fn static_procedural_vars<'d>(body: &Symbol<'d>) -> Vec<Symbol<'d>> {
    let is_static = |v: &Symbol<'_>| {
        matches!(v.kind(), SymbolKind::Variable | SymbolKind::FormalArgument)
            && v.variable_lifetime() == sv_lang::VariableLifetime::Static
            && !is_array_formal(v)
    };
    let mut out = Vec::new();
    // The module-side definitions of interface `extern` methods are
    // subroutines of the body that are not among its members.
    let mut items = module_items(body);
    items.extend(super::itf::extern_impls_in(body));
    for m in items {
        let kind = m.kind();
        if kind == SymbolKind::Subroutine {
            let result = m.subroutine_return_val_var().map(|r| r.uid());
            for v in m.members() {
                if is_static(&v) && Some(v.uid()) != result {
                    out.push(v);
                }
            }
        }
        if kind != SymbolKind::Subroutine && kind != SymbolKind::ProceduralBlock {
            continue;
        }
        let Some(code) = crate::process::cfg::proc_body(&m) else {
            continue;
        };
        let mut stack = vec![code.as_sem_node()];
        while let Some(n) = stack.pop() {
            if let Some(s) = n.as_statement() {
                for block in crate::process::cfg::block_scopes(&s) {
                    out.extend(block.members().filter(|v| is_static(v)));
                }
            }
            let mut kids = crate::process::cfg::live_children(&n);
            kids.reverse();
            stack.extend(kids);
        }
    }
    out
}

/// Whether `var` is a formal argument of fixed unpacked-array type: passed
/// as the caller's temporary copy (LRM 13.5.1), never instance storage, even
/// in a static subroutine (LRM 13.3). A queue / dynamic array / associative
/// formal is a 64-bit handle and stays static storage.
fn is_array_formal(var: &Symbol<'_>) -> bool {
    var.kind() == SymbolKind::FormalArgument
        && var
            .value_type()
            .is_some_and(|t| t.is_unpacked_array() && !crate::state::storage::is_collection(&t))
}

/// Whether `var` is one of [`static_procedural_vars`] of an instance or of a
/// package.
pub fn is_static_procedural_var(var: &Symbol<'_>) -> bool {
    if !matches!(
        var.kind(),
        SymbolKind::Variable | SymbolKind::FormalArgument
    ) || var.variable_lifetime() != sv_lang::VariableLifetime::Static
        || is_array_formal(var)
    {
        return false;
    }
    let mut procedural = false;
    let mut in_class = false;
    let mut in_task = false;
    let mut cur = var.parent();
    while let Some(p) = cur {
        let kind = p.kind();
        if kind == SymbolKind::Subroutine {
            if p.subroutine_return_val_var().map(|r| r.uid()) == Some(var.uid()) {
                return false;
            }
            procedural = true;
            in_task |= p.subroutine_kind() == Some(sv_lang::SubroutineKind::Task);
        } else if kind == SymbolKind::StatementBlock || kind == SymbolKind::ProceduralBlock {
            procedural = true;
        } else if kind == SymbolKind::InstanceBody || kind == SymbolKind::CheckerInstanceBody {
            // A class method's static local lives with its class (LRM 8.9,
            // 6.21), whether the class is in a module or the compilation unit.
            return procedural && !in_class;
        } else if kind == SymbolKind::ClassType {
            in_class = true;
        } else if kind == SymbolKind::Package || kind == SymbolKind::CompilationUnit {
            // A package TASK's static local is the package's own state (LRM
            // 6.21: one copy across calls; an inlined task body would
            // re-initialize a frame local per call). Package functions keep
            // their own storage, formals stay call-frame locals, and a class
            // method's statics live with its class.
            return procedural && !in_class && in_task && var.kind() == SymbolKind::Variable;
        }
        cur = p.parent();
    }
    false
}

/// A variable's initializer, including the one an ANSI port declaration
/// carries (LRM 1800-2023 6.8, 23.2.2.4): `module m(output reg [31:0] z = 5)`
/// puts the `= 5` on the `Port` symbol (`port_initializer`), not on the
/// internal `Variable`, so `Symbol::initializer` alone misses it.
pub fn variable_initializer<'d>(var: &Symbol<'d>) -> Option<Expression<'d>> {
    if let Some(init) = var.initializer() {
        return Some(init);
    }
    if var.kind() != SymbolKind::Variable {
        return None;
    }
    let body = var
        .parent()
        .filter(|p| p.kind() == SymbolKind::InstanceBody)?;
    let uid = var.uid();
    body.instance_body_ports()
        .find(|p| p.port_internal_symbol().is_some_and(|i| i.uid() == uid))
        .and_then(|p| p.port_initializer())
}