vj 0.3.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
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
//! Covergroups (IEEE 1800-2023 Clause 19) in `vj run` and `vj
//! build-aot`: which covergroups each instance compiles
//! (`vj_codegen::covergroup`), and their description as plain data
//! ([`CovGroupImage`]) that `vj_exec::covergroups` registers with the
//! runtime once the kernels exist (`vj_runtime::covergroup_rt`) and gives
//! the sampler process of a covergroup with a clocking event (19.3:
//! `covergroup cg @(posedge clk)` samples every instance of itself on each
//! event).

use std::collections::HashMap;

use sv_lang::{SemNode, Symbol, SyntaxTree};
use vj_codegen::covergroup::{self as cov, CovExtract};
use vj_codegen::error::LoweringError;
use vj_codegen::pipeline::CovergroupLoweringSpec;
use vj_codegen::process_lower::{SignalSlot, to_state_edge_kind};
use vj_sim::image::verif::{CovClassClockImage, CovExprTermImage, CovGroupImage, CovSamplerImage};
use vj_sim::netlist::InstanceId;
use vj_sim::state::EdgeKind as StateEdgeKind;
use vj_sim::symid::{SymbolId, SymbolUid};

/// Every covergroup of the design, per instance.
pub(crate) struct CovPlan<'d> {
    pub specs: Vec<CovergroupLoweringSpec<'d>>,
    /// Index-aligned with `specs`.
    pub extracts: Vec<CovExtract<'d>>,
    pub instances: Vec<InstanceId>,
}

/// Finds and extracts the covergroups of each instance in `bodies`, and
/// those declared in `packages`; `roots` are each instance's process bodies
/// (where `new` is called).
pub(crate) fn plan<'d>(
    bodies: &[(InstanceId, Symbol<'d>)],
    packages: &[Symbol<'d>],
    units: &[Symbol<'d>],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    roots: &HashMap<InstanceId, Vec<SemNode<'d>>>,
    trees: &[SyntaxTree],
) -> Result<CovPlan<'d>, vj_codegen::error::LoweringError> {
    let mut type_index: HashMap<String, u32> = HashMap::new();
    let mut out = CovPlan {
        specs: Vec::new(),
        extracts: Vec::new(),
        instances: Vec::new(),
    };
    for (id, body) in bodies {
        for cg in cov::declared_covergroups(*body) {
            let x = cov::extract(cg, trees)?;
            let next = type_index.len() as u32;
            let idx = *type_index.entry(cov::type_key(&cg)).or_insert(next);
            // `new` in a process, or in a variable's initializer.
            let mut nodes = roots.get(id).cloned().unwrap_or_default();
            nodes.extend(
                vj_sim::netlist::module_items(body)
                    .into_iter()
                    .filter_map(|m| m.initializer().map(|e| e.as_sem_node())),
            );
            // Each distinct `ref` binding is its own table of the type.
            let sets = cov::ref_binding_sets(&cg, &x.formals, &nodes)?;
            let mut first = Some(x);
            for refs in sets {
                let x = match first.take() {
                    Some(x) => x,
                    None => cov::extract(cg, trees)?,
                };
                let sampler_terms = match x.event.filter(|ev| !is_block_event(*ev)) {
                    Some(ev) => Some(event_terms(ev, &instance_signals[id], &cg, &refs)?),
                    None => None,
                };
                out.specs.push(CovergroupLoweringSpec {
                    prefix: format!("vj_cov_{}", out.specs.len()),
                    cg,
                    type_index: idx,
                    kernels: x.kernels.clone(),
                    refs: refs.clone(),
                    signals: instance_signals[id].clone(),
                    gates: sampler_terms
                        .as_ref()
                        .map_or_else(Vec::new, EventTerms::spec_gates),
                    event_values: sampler_terms
                        .as_ref()
                        .map_or_else(Vec::new, EventTerms::value_terms),
                });
                out.extracts.push(x);
                out.instances.push(*id);
            }
        }
    }
    // A covergroup declared in a package (19.3) is one type for the whole
    // design: one table, compiled against the first instance (`new` finds
    // a type's table from any caller), with `new` sought in every
    // instance's processes. Its expressions see its own arguments; a
    // package variable it read would fail loudly when its kernel compiles.
    if let Some((home, _)) = bodies.first() {
        let all_roots: Vec<SemNode<'d>> = roots.values().flatten().copied().collect();
        // Package covergroups, and (19.4) those embedded in the classes of
        // the compilation units, packages and instance bodies: one type each
        // (an embedded covergroup reads its object's properties through the
        // hidden `this` cell `new` passes).
        let mut shared: Vec<Symbol<'d>> = Vec::new();
        for pkg in packages {
            shared.extend(
                pkg.members()
                    .filter(|m| m.kind() == sv_lang::kinds::SymbolKind::CovergroupType),
            );
        }
        for scope in units
            .iter()
            .chain(packages)
            .copied()
            .chain(bodies.iter().map(|(_, b)| *b))
        {
            for cg in cov::class_covergroups(scope) {
                if !shared.iter().any(|s| s.uid() == cg.uid()) {
                    shared.push(cg);
                }
            }
        }
        for cg in shared {
            {
                let x = cov::extract(cg, trees)?;
                let next = type_index.len() as u32;
                let key = cov::type_key(&cg);
                if type_index.contains_key(&key) {
                    continue;
                }
                let idx = *type_index.entry(key).or_insert(next);
                let refs = cov::ref_bindings(&cg, &x.formals, &all_roots)?;
                // 19.3/19.4: with a sampling event, the table lives in the
                // instance that owns the event's signal (`top.clk`), whose
                // sampler samples every object `new` made of the type
                // (none, if none was constructed). The object itself is
                // reached through `new`'s table lookup, not the instance.
                let (at, sampler_terms) = match x.event {
                    None => (*home, None),
                    // 19.4: an event on class properties is polled per object
                    // by a watcher of the type, not a module signal's sampler.
                    Some(_) if x.class_event.is_some() => (*home, None),
                    Some(ev) => {
                        let mut found = None;
                        let mut first_err = None;
                        for (id, _) in bodies {
                            match event_terms(ev, &instance_signals[id], &cg, &refs) {
                                Ok(t) => {
                                    found = Some((*id, Some(t)));
                                    break;
                                }
                                Err(e) => {
                                    first_err.get_or_insert(e);
                                }
                            }
                        }
                        match found {
                            Some(f) => f,
                            None => return Err(first_err.expect("a design has an instance")),
                        }
                    }
                };
                out.specs.push(CovergroupLoweringSpec {
                    prefix: format!("vj_cov_{}", out.specs.len()),
                    cg,
                    type_index: idx,
                    kernels: x.kernels.clone(),
                    refs,
                    signals: instance_signals[&at].clone(),
                    gates: sampler_terms
                        .as_ref()
                        .map_or_else(Vec::new, EventTerms::spec_gates),
                    event_values: sampler_terms
                        .as_ref()
                        .map_or_else(Vec::new, EventTerms::value_terms),
                });
                out.extracts.push(x);
                out.instances.push(at);
            }
        }
    }
    Ok(out)
}

/// The [`CovGroupImage`]s of `plan`, in table order. `intern` assigns a symbol
/// index to a kernel's name (`covergroup::kernel_name`).
pub(crate) fn image<'d>(
    plan: &CovPlan<'d>,
    mut intern: impl FnMut(&str) -> u32,
) -> Result<Vec<CovGroupImage>, LoweringError> {
    let mut out = Vec::with_capacity(plan.specs.len());
    for ((spec, x), id) in plan.specs.iter().zip(&plan.extracts).zip(&plan.instances) {
        let kernels = (0..spec.kernels.len())
            .map(|k| intern(&cov::kernel_name(&spec.prefix, k)))
            .collect();
        let sampler = match x
            .event
            .filter(|ev| !is_block_event(*ev) && x.class_event.is_none())
        {
            None => None,
            Some(ev) => {
                let et = event_terms(ev, &spec.signals, &spec.cg, &spec.refs)?;
                // The gate functions `plan` had compiled (`CovergroupLoweringSpec::gates`):
                // the whole-signal terms' first, then those of the expression terms.
                let gates = et
                    .gates
                    .iter()
                    .enumerate()
                    .map(|(i, (term, _))| (*term, intern(&cov::gate_name(&spec.prefix, i))))
                    .collect();
                let mut next_gate = et.gates.len();
                let exprs = et
                    .exprs
                    .iter()
                    .enumerate()
                    .map(|(i, x)| CovExprTermImage {
                        func: intern(&cov::event_value_name(&spec.prefix, i)),
                        edge: x.edge,
                        wake: x.wake.clone(),
                        gates: x
                            .gates
                            .iter()
                            .map(|_| {
                                next_gate += 1;
                                intern(&cov::gate_name(&spec.prefix, next_gate - 1))
                            })
                            .collect(),
                    })
                    .collect();
                Some(CovSamplerImage {
                    terms: et.terms,
                    gates,
                    exprs,
                    strobe: x.strobe,
                })
            }
        };
        let class_clock = x.class_event.as_ref().map(|c| CovClassClockImage {
            terms: c.terms.clone(),
            gates: c.gates.clone(),
            strobe: x.strobe,
        });
        let blocks = cov::block_event_targets(&spec.cg)?
            .iter()
            .map(|(sub, is_end)| cov::block_event_key(sub, *is_end))
            .collect::<Result<_, _>>()?;
        out.push(CovGroupImage {
            type_index: spec.type_index,
            site: cov::table_site_with_refs(&spec.cg, spec.refs.iter().map(|(_, a)| *a)),
            instance: *id,
            decl: x.decl.clone(),
            kernels,
            sampler,
            class_clock,
            blocks,
        });
    }
    Ok(out)
}

/// Whether the sampling event `ev` is a block event list (19.3 `@@(...)`),
/// which the subroutines it names signal instead of a sampler process.
fn is_block_event(ev: SemNode<'_>) -> bool {
    ev.as_timing_control()
        .is_some_and(|t| t.kind() == sv_lang::kinds::TimingControlKind::BlockEventList)
}

/// `e` is `base[0]` -- a constant select of the bit that carries a vector's
/// edge (LRM 9.4.2: an edge event on a vector watches its least significant
/// bit) -- under an edge keyword, so the event equals the base signal's.
fn lsb_edge_select(e: sv_lang::Expression<'_>, edge: sv_lang::EdgeKind) -> bool {
    use sv_lang::kinds::ExpressionKind as K;
    if e.kind() != K::ElementSelect || edge == sv_lang::EdgeKind::None {
        return false;
    }
    let Some(base) = e
        .select_value()
        .filter(|b| vj_sim::symid::is_value_name(b.kind()))
    else {
        return false;
    };
    let Some(t) = base
        .expr_type()
        .filter(|t| t.is_integral() && !t.is_struct() && !t.is_union())
    else {
        return false;
    };
    let r = t.bit_vector_range();
    let (left, right) = (i64::from(r.left), i64::from(r.right));
    let Some(idx) = e
        .selector()
        .and_then(|x| x.constant_value())
        .and_then(|v| v.as_i64())
    else {
        return false;
    };
    (if left >= right {
        idx - right
    } else {
        right - idx
    }) == 0
}

/// A sampling event as the sampler watches it.
struct EventTerms<'d> {
    /// What wakes the sampler: `(signal slot, edge)`, the whole-signal terms
    /// of the event first, then one `(slot, any change)` per signal an
    /// expression term reads.
    terms: Vec<(u32, Option<StateEdgeKind>)>,
    /// The `iff` conditions (19.3, 9.4.2.3) of the whole-signal terms, each
    /// with its term index.
    gates: Vec<(u32, sv_lang::Expression<'d>)>,
    /// The terms on an expression or select, in source order.
    exprs: Vec<ExprTerm<'d>>,
}

/// A sampling-event term on an expression (`@(posedge v[1])`,
/// `@(posedge (a & b))`, LRM 9.4.2): its edge, the `terms` it is woken by and
/// its `iff` conditions.
struct ExprTerm<'d> {
    expr: sv_lang::Expression<'d>,
    edge: Option<StateEdgeKind>,
    wake: Vec<u32>,
    gates: Vec<sv_lang::Expression<'d>>,
}

impl<'d> EventTerms<'d> {
    /// Every `iff` condition to compile, in [`cov::gate_name`] order: those of
    /// the whole-signal terms, then those of each expression term.
    fn spec_gates(&self) -> Vec<sv_lang::Expression<'d>> {
        self.gates
            .iter()
            .map(|(_, g)| *g)
            .chain(self.exprs.iter().flat_map(|x| x.gates.iter().copied()))
            .collect()
    }

    /// The expression terms as [`cov::compile_event_values`] takes them.
    fn value_terms(&self) -> Vec<(sv_lang::Expression<'d>, bool)> {
        self.exprs
            .iter()
            .map(|x| (x.expr, x.edge.is_some()))
            .collect()
    }
}

/// `@(e)` / `@(a or b)`: each term's signal slot and edge, plus the `iff`
/// conditions (19.3, 9.4.2.3) of its members, each with its term index. A
/// term on an expression or a select is an [`ExprTerm`].
fn event_terms<'d>(
    ev: SemNode<'d>,
    signals: &HashMap<SymbolId, SignalSlot>,
    cg: &Symbol<'d>,
    refs: &[(Symbol<'d>, Symbol<'d>)],
) -> Result<EventTerms<'d>, LoweringError> {
    let unsupported = |m: String| LoweringError::unsupported_at(&m, cg);
    let tc = ev.as_timing_control().ok_or_else(|| {
        unsupported(format!(
            "covergroup {}'s sampling event is not an event control",
            cg.name()
        ))
    })?;
    let members: Vec<sv_lang::TimingControl<'d>> =
        if tc.kind() == sv_lang::kinds::TimingControlKind::EventList {
            tc.children()
                .into_iter()
                .filter_map(|n| n.as_timing_control())
                .collect()
        } else {
            vec![tc]
        };
    let mut terms = Vec::new();
    let mut gates = Vec::new();
    let mut pending = Vec::new();
    let mut exprs = Vec::new();
    for t in members {
        if t.kind() == sv_lang::kinds::TimingControlKind::BlockEventList {
            // A covergroup declared outside a module instance: refused by
            // name (`block_event_targets`).
            cov::block_event_targets(cg)?;
            return Err(unsupported(format!(
                "covergroup {}: a block event `@@(...)` mixed with other event terms \
                 is not supported (LRM 19.3)",
                cg.name()
            )));
        }
        let mut exprs = t.children().into_iter().filter_map(|n| n.as_expression());
        let first = exprs.next();
        // The watcher below is one (signal, edge) pair on the whole signal.
        // An edge of a select or an expression (`@(posedge v[1])`,
        // `@(posedge (a & b))`) is another event: `referenced_symbol` of it
        // is the base variable, and watching that instead sampled on the
        // wrong events (a silent wrong answer). Only the selected bit that
        // IS the signal's edge bit -- bit 0 of a vector, `posedge v[0]` --
        // is the same event; the others are compared by value, on each
        // change of a signal they read ([`expr_terms`]).
        if let Some(e) = first
            && !vj_sim::symid::is_value_name(e.kind())
            && !lsb_edge_select(e, t.edge())
        {
            let edge = match t.edge() {
                sv_lang::EdgeKind::None => None,
                sv_lang::EdgeKind::BothEdges => Some(StateEdgeKind::BothEdges),
                sv_lang::EdgeKind::PosEdge => Some(StateEdgeKind::Posedge),
                sv_lang::EdgeKind::NegEdge => Some(StateEdgeKind::Negedge),
            };
            if !cov::event_value_supported(e, edge.is_some()) {
                return Err(unsupported(format!(
                    "covergroup {}'s sampling event is a change of an expression wider than \
                     32 bits (LRM 19.3, 9.4.2: use an edge, a narrower expression or \
                     sample() from a process)",
                    cg.name()
                )));
            }
            pending.push((e, edge, exprs_gates(t)));
            continue;
        }
        let sig = first.and_then(|e| e.referenced_symbol()).ok_or_else(|| {
            unsupported(format!(
                "covergroup {}'s sampling event is not on a plain signal",
                cg.name()
            ))
        })?;
        for g in exprs {
            gates.push((terms.len() as u32, g));
        }
        // 19.3: an event on a `ref` formal watches the variable it tracks.
        let sig = refs
            .iter()
            .find(|(f, _)| f.uid() == sig.uid())
            .map_or(sig, |(_, a)| *a);
        let slot = signals.get(&sig.uid()).ok_or_else(|| {
            if sig.kind() == sv_lang::kinds::SymbolKind::ClassProperty {
                // 19.4: the event is a property of each object, so every
                // object would need its own watcher; refused by name.
                return unsupported(format!(
                    "covergroup {}'s sampling event is on class property {} \
                     (a clocking event on a class property is not supported; call sample() \
                     or clock the covergroup on a module signal) (LRM 19.4)",
                    cg.name(),
                    sig.name()
                ));
            }
            unsupported(format!(
                "covergroup {}'s sampling event signal {} is not a signal of the instance \
                 (an event on a constructor argument is not supported)",
                cg.name(),
                sig.name()
            ))
        })?;
        let edge = match t.edge() {
            sv_lang::EdgeKind::None => None,
            sv_lang::EdgeKind::BothEdges => Some(StateEdgeKind::BothEdges),
            e => Some(to_state_edge_kind(e, &sig)?),
        };
        terms.push((slot.slot, edge));
    }
    expr_terms(cg, signals, refs, pending, &mut terms, &mut exprs)?;
    Ok(EventTerms {
        terms,
        gates,
        exprs,
    })
}

/// The `iff` conditions of a sampling-event term: the expressions after its
/// event expression (9.4.2.3).
fn exprs_gates<'d>(t: sv_lang::TimingControl<'d>) -> Vec<sv_lang::Expression<'d>> {
    t.children()
        .into_iter()
        .filter_map(|n| n.as_expression())
        .skip(1)
        .collect()
}

/// Turns the `pending` expression terms of an event into [`ExprTerm`]s: each
/// is woken by every signal its expression reads, appended to `terms` as
/// `(slot, any change)`. A variable it reads that is no signal of the instance
/// is a named error.
fn expr_terms<'d>(
    cg: &Symbol<'d>,
    signals: &HashMap<SymbolId, SignalSlot>,
    refs: &[(Symbol<'d>, Symbol<'d>)],
    pending: Vec<(
        sv_lang::Expression<'d>,
        Option<StateEdgeKind>,
        Vec<sv_lang::Expression<'d>>,
    )>,
    terms: &mut Vec<(u32, Option<StateEdgeKind>)>,
    exprs: &mut Vec<ExprTerm<'d>>,
) -> Result<(), LoweringError> {
    for (expr, edge, gates) in pending {
        let mut slots: Vec<u32> = Vec::new();
        let mut stack = vec![expr.as_sem_node()];
        while let Some(n) = stack.pop() {
            if let Some(x) = n.as_expression()
                && vj_sim::symid::is_value_name(x.kind())
                && let Some(sym) = x.referenced_symbol()
            {
                let sym = refs
                    .iter()
                    .find(|(f, _)| f.uid() == sym.uid())
                    .map_or(sym, |(_, a)| *a);
                match signals.get(&sym.uid()) {
                    Some(info) => {
                        if !slots.contains(&info.slot) {
                            slots.push(info.slot);
                        }
                    }
                    None if matches!(
                        sym.kind(),
                        sv_lang::kinds::SymbolKind::Variable
                            | sv_lang::kinds::SymbolKind::Net
                            | sv_lang::kinds::SymbolKind::ClassProperty
                    ) =>
                    {
                        return Err(LoweringError::unsupported_at(
                            &format!(
                                "covergroup {}'s sampling event reads {}, which is not a signal \
                                 of the instance (LRM 19.3)",
                                cg.name(),
                                sym.name()
                            ),
                            cg,
                        ));
                    }
                    None => {}
                }
            }
            stack.extend(n.children());
        }
        if slots.is_empty() {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "covergroup {}'s sampling event expression reads no signal, so it never \
                     changes (LRM 19.3)",
                    cg.name()
                ),
                cg,
            ));
        }
        let wake = slots
            .into_iter()
            .map(|slot| {
                terms.push((slot, None));
                (terms.len() - 1) as u32
            })
            .collect();
        exprs.push(ExprTerm {
            expr,
            edge,
            wake,
            gates,
        });
    }
    Ok(())
}