-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathmodule.rs
More file actions
3365 lines (3178 loc) · 135 KB
/
Copy pathmodule.rs
File metadata and controls
3365 lines (3178 loc) · 135 KB
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::backend::inst::next_test_top_id;
use crate::backend::{ChunkOutput, CompileCtx, CompiledWhole};
use crate::ir::comb_pipeline_cache;
use crate::ir::context::{Context, Conv, ScopeContext};
use crate::ir::declaration::{stable_topo_sort, stable_topo_sort_with_blocks};
use crate::ir::derived_clock::{
DerivedClockSchedule, build_schedule as build_derived_clock_schedule, extract_eval_proto_stmts,
};
use crate::ir::external::{ExternalComponentInst, ProtoExternalComponent};
use crate::ir::inst_layout::InstLayout;
use crate::ir::opt::dead_var_dce;
use crate::ir::opt::dup_assign_dce::dce_aggressive;
use crate::ir::opt::multi_write_analysis::analyze_multi_write;
use crate::ir::opt::multi_write_analysis::collect_dyn_indexed_vars;
use crate::ir::site_table::{SiteInfo, SiteKind, SiteTable};
use crate::ir::variable::{
ModuleVariableMeta, ModuleVariables, VarOffset, Variable, align_up_64, create_variable_meta,
ff_cacheline_pad_enabled, value_size, write_native_value,
};
use crate::ir::{
CompiledBatchStmt, Event, ProtoDeclaration, ProtoStatement, ProtoStatementBlock,
ProtoStatements, Statement, VarId, VarPath,
};
use crate::simulator_error::SimulatorError;
use crate::{HashMap, HashSet};
use daggy::Dag;
use daggy::petgraph::Direction::Outgoing;
use daggy::petgraph::algo;
use std::collections::VecDeque;
use std::sync::Arc;
use veryl_analyzer::ir as air;
use veryl_parser::resource_table::StrId;
pub struct Module {
pub name: StrId,
pub ports: HashMap<VarPath, VarId>,
pub ff_values: Box<[u8]>,
pub comb_values: Box<[u8]>,
pub module_variables: ModuleVariables,
pub event_statements: HashMap<Event, Vec<Statement>>,
/// Unified comb statements: all port connections, child comb, and internal
/// comb combined into a single dependency-sorted list.
pub comb_statements: Vec<Statement>,
/// Number of eval_comb passes needed for full convergence.
/// Pre-computed from backward edges in the sorted comb statement list.
pub required_comb_passes: usize,
/// FF write site table: compile-time metadata for each FF write site
/// reachable from the pre-JIT event ProtoStatements. Consumed for
/// log buffer sizing and NBA invariant checks.
pub site_table: SiteTable,
/// Per-top-level-Inst FF byte range metadata. Foundation for
/// cache-line aligned padding between Inst FF blocks and per-Inst
/// independent commit.
pub inst_layout: InstLayout,
/// Derived (gated / FF-divided) clocks in this module; empty when none.
pub derived_clock_schedule: DerivedClockSchedule,
/// JIT-compiled evaluation chunk for derived clocks; empty when none.
pub derived_clock_eval_stmts: Vec<Statement>,
/// Diagnostic: number of non-trivial strongly-connected components in
/// the pre-JIT `unified_sorted` dataflow graph. Real RTL combinational
/// loops are rejected up-front by `analyze_dependency`, so any non-zero
/// value here is a duplication artifact in the simulator IR assembly.
/// Exposed for regression tests.
pub nontrivial_comb_scc: usize,
/// Whole-comb dispatch handle, populated when a backend committed
/// to a one-function compile via `Backend::compile_whole_comb`.
/// `None` keeps `settle_comb` on the per-chunk Cranelift loop.
pub whole_comb: Option<Arc<dyn CompiledWhole>>,
/// Per-event whole-event dispatch handles (today populated by AOT-C
/// when `Config::aot_c_event` is set). Empty when no backend
/// covered the event.
pub whole_events: HashMap<Event, Arc<dyn CompiledWhole>>,
/// User-defined component instances (`$comp::<name>`), driven by
/// the simulator around event evaluation.
pub external_components: Vec<ExternalComponentInst>,
/// Top-level variables written by RTL statements; component outputs
/// must not overlap them (sole-driver check at load time).
pub rtl_driven: crate::HashSet<air::VarId>,
}
pub struct ProtoModule {
pub name: StrId,
pub ports: HashMap<VarPath, VarId>,
pub ff_bytes: usize,
pub comb_bytes: usize,
pub use_4state: bool,
pub module_variable_meta: ModuleVariableMeta,
pub event_statements: HashMap<Event, ProtoStatements>,
/// Unified comb statements: all port connections, child comb, and internal
/// comb combined into a single dependency-sorted list.
pub comb_statements: ProtoStatements,
/// Number of eval_comb passes needed for full convergence.
pub required_comb_passes: usize,
/// See `Module::site_table`.
pub site_table: SiteTable,
/// See `Module::inst_layout`.
pub inst_layout: InstLayout,
/// See `Module::derived_clock_schedule`.
pub derived_clock_schedule: DerivedClockSchedule,
/// Pre-JIT form of `Module::derived_clock_eval_stmts`.
pub derived_clock_eval: ProtoStatements,
/// See `Module::nontrivial_comb_scc`.
pub nontrivial_comb_scc: usize,
/// See `Module::whole_comb`. Built in `conv()` and shared
/// (`Arc::clone`) with every `Module` produced by `instantiate()`.
pub whole_comb: Option<Arc<dyn CompiledWhole>>,
/// See `Module::whole_events`. Built in `conv()`, shared
/// (`Arc::clone`) with every `Module` from `instantiate()`.
pub whole_events: HashMap<Event, Arc<dyn CompiledWhole>>,
/// See `Module::external_components` (pre-pointer-binding form).
pub external_components: Vec<ProtoExternalComponent>,
/// See `Module::rtl_driven`.
pub rtl_driven: crate::HashSet<air::VarId>,
}
fn create_buffers(
module_variable_meta: &ModuleVariableMeta,
ff_bytes: usize,
comb_bytes: usize,
use_4state: bool,
) -> (Box<[u8]>, Box<[u8]>) {
let mut ff_values = vec![0u8; ff_bytes];
let mut comb_values = vec![0u8; comb_bytes];
fill_buffers_recursive(
module_variable_meta,
&mut ff_values,
&mut comb_values,
use_4state,
);
(ff_values.into_boxed_slice(), comb_values.into_boxed_slice())
}
/// Fill byte buffers with initial values, writing at the offsets stored in VariableElement.
fn fill_buffers_recursive(
module_meta: &ModuleVariableMeta,
ff_values: &mut [u8],
comb_values: &mut [u8],
use_4state: bool,
) {
let mut sorted: Vec<_> = module_meta.variable_meta.iter().collect();
sorted.sort_by_key(|(k, _)| **k);
for (_, meta) in &sorted {
// Single-entry initial_values on a multi-element variable is the
// compact template form used for large arrays.
let template_mode = meta.initial_values.len() == 1 && meta.elements.len() > 1;
for (i, element) in meta.elements.iter().enumerate() {
let initial = if template_mode {
&meta.initial_values[0]
} else {
match meta.initial_values.get(i) {
Some(v) => v,
None => continue,
}
};
let nb = element.native_bytes;
let _vs = value_size(nb, use_4state);
if element.is_ff() {
#[cfg(debug_assertions)]
{
let off = element.current_offset() as usize;
debug_assert!(
off + _vs <= ff_values.len(),
"FF current_offset out of bounds"
);
debug_assert!(
element.next_offset as usize + _vs <= ff_values.len(),
"FF next_offset out of bounds"
);
}
let cur =
&mut ff_values[element.current_offset() as usize..] as *mut [u8] as *mut u8;
let nxt = &mut ff_values[element.next_offset as usize..] as *mut [u8] as *mut u8;
unsafe {
write_native_value(cur, nb, use_4state, initial);
write_native_value(nxt, nb, use_4state, initial);
}
} else {
#[cfg(debug_assertions)]
debug_assert!(
element.current_offset() as usize + _vs <= comb_values.len(),
"Comb current_offset out of bounds"
);
let cur =
&mut comb_values[element.current_offset() as usize..] as *mut [u8] as *mut u8;
unsafe {
write_native_value(cur, nb, use_4state, initial);
}
}
}
}
for child in &module_meta.children {
fill_buffers_recursive(child, ff_values, comb_values, use_4state);
}
}
fn create_variables_recursive(
module_meta: &ModuleVariableMeta,
ff_base: *mut u8,
comb_base: *mut u8,
) -> ModuleVariables {
let mut variables = HashMap::default();
for (id, meta) in &module_meta.variable_meta {
let mut current_values: Vec<*mut u8> = vec![];
let mut next_values: Vec<*mut u8> = vec![];
for element in &meta.elements {
let current = unsafe {
let base = if element.is_ff() { ff_base } else { comb_base };
base.add(element.current_offset() as usize)
};
current_values.push(current);
if element.is_ff() {
let next = unsafe { ff_base.add(element.next_offset as usize) };
next_values.push(next);
}
}
variables.insert(
*id,
Variable {
path: meta.path.clone(),
r#type: meta.r#type.clone(),
width: meta.width,
native_bytes: meta.native_bytes,
current_values,
next_values,
},
);
}
let children = module_meta
.children
.iter()
.map(|child| create_variables_recursive(child, ff_base, comb_base))
.collect();
ModuleVariables {
name: module_meta.name,
variables,
children,
}
}
impl ProtoModule {
pub fn instantiate(&self) -> Module {
log::trace!(
"instantiate: module={}, ff_bytes={}, comb_bytes={}",
self.name,
self.ff_bytes,
self.comb_bytes,
);
let (mut ff_values, mut comb_values) = create_buffers(
&self.module_variable_meta,
self.ff_bytes,
self.comb_bytes,
self.use_4state,
);
let ff_base = ff_values.as_mut_ptr();
let comb_base = comb_values.as_mut_ptr();
let module_variables =
create_variables_recursive(&self.module_variable_meta, ff_base, comb_base);
let ff_ptr = ff_values.as_mut_ptr();
let comb_ptr = comb_values.as_mut_ptr();
let ff_len = self.ff_bytes;
let comb_len = self.comb_bytes;
let event_statements = self
.event_statements
.iter()
.map(|(event, stmts)| {
let s = stmts.to_statements(ff_ptr, ff_len, comb_ptr, comb_len, self.use_4state);
(event.clone(), batch_compiled_statements(s))
})
.collect();
let comb_statements = batch_compiled_statements(self.comb_statements.to_statements(
ff_ptr,
ff_len,
comb_ptr,
comb_len,
self.use_4state,
));
let derived_clock_eval_stmts = if self.derived_clock_eval.0.is_empty() {
Vec::new()
} else {
batch_compiled_statements(self.derived_clock_eval.to_statements(
ff_ptr,
ff_len,
comb_ptr,
comb_len,
self.use_4state,
))
};
#[cfg(debug_assertions)]
self.validate_offsets();
Module {
name: self.name,
ports: self.ports.clone(),
ff_values,
comb_values,
module_variables,
derived_clock_eval_stmts,
event_statements,
comb_statements,
required_comb_passes: self.required_comb_passes,
site_table: self.site_table.clone(),
inst_layout: self.inst_layout.clone(),
derived_clock_schedule: self.derived_clock_schedule.clone(),
nontrivial_comb_scc: self.nontrivial_comb_scc,
whole_comb: self.whole_comb.clone(),
whole_events: self.whole_events.clone(),
external_components: self
.external_components
.iter()
.map(|x| unsafe {
x.instantiate(ff_ptr, ff_len, comb_ptr, comb_len, self.use_4state)
})
.collect(),
rtl_driven: self.rtl_driven.clone(),
}
}
/// Validate that all variable offsets in statements are within buffer bounds.
#[cfg(debug_assertions)]
fn validate_offsets(&self) {
let ff_bytes = self.ff_bytes;
let comb_bytes = self.comb_bytes;
let use_4state = self.use_4state;
let check = |off: &VarOffset, context: &str| {
let raw = off.raw() as usize;
if off.is_ff() {
assert!(
raw < ff_bytes || ff_bytes == 0,
"validate_offsets [{}]: ff offset {} >= ff_bytes {} (module={})",
context,
raw,
ff_bytes,
self.name,
);
} else {
assert!(
raw < comb_bytes || comb_bytes == 0,
"validate_offsets [{}]: comb offset {} >= comb_bytes {} (module={})",
context,
raw,
comb_bytes,
self.name,
);
}
};
let validate_stmts = |stmts: &ProtoStatements, label: &str| {
for block in &stmts.0 {
if let ProtoStatementBlock::Interpreted(proto) = block {
for s in proto {
let mut ins = vec![];
let mut outs = vec![];
s.gather_variable_offsets(&mut ins, &mut outs);
for off in ins.iter().chain(outs.iter()) {
check(off, label);
}
}
}
}
};
for (event, stmts) in &self.event_statements {
validate_stmts(stmts, &format!("event {event:?}"));
}
validate_stmts(&self.comb_statements, "comb");
// Validate variable metadata offsets
validate_meta_offsets(&self.module_variable_meta, ff_bytes, comb_bytes, use_4state);
}
}
#[cfg(debug_assertions)]
fn validate_meta_offsets(
meta: &ModuleVariableMeta,
ff_bytes: usize,
comb_bytes: usize,
use_4state: bool,
) {
for (id, var_meta) in &meta.variable_meta {
let vs = value_size(var_meta.native_bytes, use_4state);
for (i, elem) in var_meta.elements.iter().enumerate() {
let off = elem.current_offset() as usize;
if elem.is_ff() {
// Packed FFs have `next_offset == current_offset`
// (sentinel) and occupy only `vs` bytes; unpacked
// (multi-RMW) FFs have `next_offset == current_offset + vs`
// and need `vs * 2` bytes total.
let packed = elem.next_offset == elem.current_offset();
let span = if packed { vs } else { vs * 2 };
assert!(
off + span <= ff_bytes,
"validate_meta: ff var {:?}[{}] offset {} + span {} > ff_bytes {} (packed={})",
id,
i,
off,
span,
ff_bytes,
packed,
);
} else {
assert!(
off + vs <= comb_bytes,
"validate_meta: comb var {:?}[{}] offset {} + vs {} > comb_bytes {}",
id,
i,
off,
vs,
comb_bytes,
);
}
}
}
for child in &meta.children {
validate_meta_offsets(child, ff_bytes, comb_bytes, use_4state);
}
}
/// Maximum number of statements per JIT function.
/// Keeps regalloc2 cost manageable (O(N^2) in SSA variable count).
/// Sweet spot around 1024-2048: per-step enum-match dispatch overhead
/// grows as chunks shrink below ~256, while Cranelift regalloc spill
/// cascade / load_cache eviction churn grows as chunks exceed ~4096.
/// Overridable via `VERYL_JIT_CHUNK_SIZE` env var for sweeps.
const JIT_CHUNK_SIZE_DEFAULT: usize = 1024;
fn jit_chunk_size() -> usize {
std::env::var("VERYL_JIT_CHUNK_SIZE")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(JIT_CHUNK_SIZE_DEFAULT)
}
/// Per-event JIT path: load_cache CSE enabled, no nested CompiledBlocks
/// expected.
fn try_jit(context: &mut Context, proto: Vec<ProtoStatement>) -> ProtoStatements {
build_chunked_via_registry(context, proto, /* contains_compiled_block= */ false)
}
/// Unified-comb JIT path: nested CompiledBlocks may mutate comb storage
/// between loads, so load_cache CSE is disabled in the emitted chunks.
fn try_jit_no_cache(context: &mut Context, proto: Vec<ProtoStatement>) -> ProtoStatements {
build_chunked_via_registry(context, proto, /* contains_compiled_block= */ true)
}
/// Shared chunk-building helper. Asks `context.backends` to group
/// `proto` into chunks; jittable groups become `Compiled`, others stay
/// `Interpreted`. Empty registry → fully interpreted (wasm /
/// `use_jit=false` paths arrive here with zero backends registered).
fn build_chunked_via_registry(
context: &mut Context,
proto: Vec<ProtoStatement>,
contains_compiled_block: bool,
) -> ProtoStatements {
if context.backends.is_empty() {
return ProtoStatements(vec![ProtoStatementBlock::Interpreted(proto)]);
}
// CompileCtx borrows from `context.config` (shared), while
// `build_chunked` also needs `&mut context.backends` — distinct fields,
// so Rust's split borrow permits both.
let max_chunk_size = jit_chunk_size();
let outputs = {
let ctx = CompileCtx {
config: &context.config,
use_4state: context.config.use_4state,
contains_compiled_block,
};
context.backends.build_chunked(&ctx, proto, max_chunk_size)
};
let mut blocks = Vec::with_capacity(outputs.len());
for out in outputs {
match out {
ChunkOutput::Compiled(artifact) => {
blocks.push(ProtoStatementBlock::Compiled(artifact));
}
ChunkOutput::Interpreted(stmts) => {
blocks.push(ProtoStatementBlock::Interpreted(stmts));
}
}
}
ProtoStatements(blocks)
}
fn pass_diag_phase(phase: &str) {
if std::env::var("VERYL_PASS_DIAG").is_ok() {
log::info!("pass_diag: analyze_dependency exit = {phase}");
}
}
/// Structural key for the whole comb pipeline: the comb list's fingerprint
/// folded with a digest of the event statements and DCE protect set. Those two
/// are the only inputs, besides the comb list, that dead-var DCE reads, so a key
/// match guarantees the memoised pipeline reproduces the exact result. Token-
/// and pointer-agnostic (see `ProtoAssignStatement`/`ChunkArtifact` `Debug`).
fn comb_pipeline_key(
use_4state: bool,
unified: &[ProtoStatement],
events: &HashMap<Event, Vec<ProtoStatement>>,
protect: &HashSet<VarOffset>,
) -> u128 {
use crate::backend::registry::whole_comb_fingerprint;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// Event digest: only the liveness the dead-var DCE actually reads, not the
// full event content — otherwise per-test constants / `$readmemh` paths /
// `$display` strings (which don't change deadness) would make every test a
// miss. Pooled across all events (DCE sees them as one joint census).
let event_slices: Vec<&[ProtoStatement]> = events.values().map(|v| v.as_slice()).collect();
let evt = dead_var_dce::census_digest(&event_slices);
// Protect digest: hash the sorted offsets (order-independent, collision-safe).
let mut prot_offs: Vec<isize> = protect.iter().map(|o| o.raw()).collect();
prot_offs.sort_unstable();
let mut h = DefaultHasher::new();
evt.hash(&mut h);
prot_offs.hash(&mut h);
whole_comb_fingerprint(use_4state, unified, h.finish() as u128)
}
/// Run the comb pipeline: `analyze_dependency` → `reorder_by_level` →
/// `dce_aggressive` → dead-var DCE → `try_jit_no_cache`. Mutates
/// Temporary diagnostic (VERYL_STMT_ORDER_DUMP=1): dump the stmt
/// order at a pipeline stage to localize run-to-run nondeterminism.
pub(crate) fn dump_stmt_order(tag: &str, module_name: StrId, stmts: &[ProtoStatement]) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var("VERYL_STMT_ORDER_DUMP").as_deref() == Ok("1")) {
return;
}
fn dump_one(module_name: StrId, tag: &str, path: &str, s: &ProtoStatement) {
let mut ins = vec![];
let mut outs = vec![];
s.gather_variable_offsets(&mut ins, &mut outs);
let tok = s
.token()
.map(|t| format!("{}:{}", t.beg.source, t.beg.line))
.unwrap_or_default();
let kind = match s {
ProtoStatement::Assign(_) => "Assign",
ProtoStatement::AssignDynamic(_) => "AssignDyn",
ProtoStatement::If(_) => "If",
ProtoStatement::Case(_) => "Case",
ProtoStatement::For(_) => "For",
ProtoStatement::Break => "Break",
ProtoStatement::SystemFunctionCall(_) => "SysFn",
ProtoStatement::CompiledBlock(_) => "CB",
ProtoStatement::SequentialBlock(_) => "SeqBlock",
ProtoStatement::TbMethodCall { .. } => "TbMethod",
};
eprintln!("[stmtord] {module_name} {tag} {path} {kind} tok={tok} out={outs:?} in={ins:?}");
match s {
ProtoStatement::SequentialBlock(inner) => {
for (j, t) in inner.iter().enumerate() {
dump_one(module_name, tag, &format!("{path}.{j}"), t);
}
}
ProtoStatement::If(x) => {
for (j, t) in x.true_side.iter().enumerate() {
dump_one(module_name, tag, &format!("{path}.t{j}"), t);
}
for (j, t) in x.false_side.iter().enumerate() {
dump_one(module_name, tag, &format!("{path}.f{j}"), t);
}
}
ProtoStatement::Case(x) => {
for (a, arm) in x.arms.iter().enumerate() {
for (j, t) in arm.body.iter().enumerate() {
dump_one(module_name, tag, &format!("{path}.a{a}.{j}"), t);
}
}
for (j, t) in x.default.iter().enumerate() {
dump_one(module_name, tag, &format!("{path}.d{j}"), t);
}
}
_ => {}
}
}
for (i, s) in stmts.iter().enumerate() {
dump_one(module_name, tag, &format!("{i}"), s);
}
}
/// `all_event_statements` in place with the dead-var drop (mirroring the miss
/// path); the returned `dead_offsets` let a cache hit reproduce that drop.
fn run_comb_pipeline(
context: &mut Context,
unified: Vec<ProtoStatement>,
all_event_statements: &mut HashMap<Event, Vec<ProtoStatement>>,
protect: &HashSet<VarOffset>,
module_name: StrId,
) -> Result<comb_pipeline_cache::CombPipeline, SimulatorError> {
dump_stmt_order("conv", module_name, &unified);
let (unified_sorted, passes_hint) = analyze_dependency(unified)?;
dump_stmt_order("post-topo", module_name, &unified_sorted);
// No DCE/inlining: unified list includes internal child comb that would be incorrectly removed.
// reorder_by_level preserves the sort's dependency relations (readers
// stay relative to their version writers via the RAW/WAR leveling), so
// an exact pass hint derived from the schedule remains valid.
let unified_sorted = reorder_by_level(unified_sorted);
dump_stmt_order("post-level", module_name, &unified_sorted);
let required_comb_passes =
passes_hint.unwrap_or_else(|| compute_required_passes(&unified_sorted));
if passes_hint.is_some() && std::env::var("VERYL_PASS_DIAG").is_ok() {
log::info!(
"pass_diag: exact hint {} passes (positional metric would give {})",
required_comb_passes,
compute_required_passes(&unified_sorted)
);
}
// A non-trivial SCC in the expanded dataflow view is either
// structurally-cyclic-but-logically-false feedback (the multi-pass
// settle resolves it) or duplicate ProtoStatements from an IR
// assembly bug. Under the positional metric the settled kind
// always leaves a counted backward edge, so SCC + single-pass can
// only be the duplicate bug. Exact-hint paths are exempt (a
// strict block-aware schedule legitimately settles a false SCC in
// one pass); the test-local `nontrivial_comb_scc == 0` assertions
// cover the historical duplicate scenarios there.
//
// Skip the (heavy: Tarjan + per-stmt I/O scan) computation in
// release-without-tests since the assert is a no-op there and the
// field is only consumed by tests.
let nontrivial_comb_scc = if cfg!(any(debug_assertions, test)) {
compute_scc_stats(&unified_sorted).0
} else {
0
};
debug_assert!(
nontrivial_comb_scc == 0 || passes_hint.is_some() || required_comb_passes > 1,
"ProtoModule {:?}: {} nontrivial SCC(s) in unified_sorted but a \
single-pass schedule — this indicates duplicate ProtoStatements \
in the simulator IR.",
module_name,
nontrivial_comb_scc,
);
let unified_sorted = dce_aggressive(unified_sorted);
// Dead Variable DCE: drop full-width `Assign`s whose dst has zero
// consumers anywhere in this module's pre-JIT comb stmts and every
// event stmt set. Complements `dup_assign_dce` (which handles the
// overwriting-store case) by killing writes that nobody reads in
// the first place — typical residue of `comb_to_ff_hoist` leaving
// the original comb-side Variable dead once the FF consumes the
// hoisted expression. Env-gated by `VERYL_DEAD_VAR_DCE`, default
// ON; opt out with `VERYL_DEAD_VAR_DCE=0`. `protect` is built by the
// caller (it feeds the cache key too). The union of every pass's dead
// set is returned so a cache hit can re-apply it to another test's events.
let mut dead_union: HashSet<VarOffset> = HashSet::default();
let unified_sorted = if dead_var_dce::enabled() {
// Multi-pass DCE default ON: iterate to fixpoint so that
// cascaded drops (a dst becomes dead once its only consumer
// was itself dropped) are caught in subsequent passes. Opt
// out via `VERYL_DEAD_VAR_DCE_MULTI=0`.
let multi_pass = std::env::var("VERYL_DEAD_VAR_DCE_MULTI").ok().as_deref() != Some("0");
let mut unified_sorted = unified_sorted;
let mut total_dropped = 0usize;
let mut pass = 0usize;
loop {
let mut slices: Vec<&[ProtoStatement]> =
Vec::with_capacity(1 + all_event_statements.len());
slices.push(unified_sorted.as_slice());
for stmts in all_event_statements.values() {
slices.push(stmts.as_slice());
}
let mut dead = dead_var_dce::collect_dead_offsets(&slices);
for p in protect {
dead.remove(p);
}
if dead.is_empty() {
break;
}
pass += 1;
let (rewritten, dropped_here) = dead_var_dce::apply_counting(unified_sorted, &dead);
unified_sorted = rewritten;
let mut total_dropped_here = dropped_here;
for stmts in all_event_statements.values_mut() {
let taken = std::mem::take(stmts);
let (new_stmts, d) = dead_var_dce::apply_counting(taken, &dead);
*stmts = new_stmts;
total_dropped_here += d;
}
let dead_len = dead.len();
dead_union.extend(dead);
if std::env::var("VERYL_DEAD_VAR_DCE_DIAG").ok().as_deref() == Some("1") {
eprintln!(
"[DeadVarDce] module={} pass={} dead_set={} dropped_stmts={}",
module_name, pass, dead_len, total_dropped_here,
);
}
total_dropped += total_dropped_here;
if total_dropped_here == 0 || !multi_pass {
break;
}
}
if std::env::var("VERYL_DEAD_VAR_DCE_DIAG").ok().as_deref() == Some("1") {
eprintln!(
"[DeadVarDce] module={} total_passes={} total_dropped={}",
module_name, pass, total_dropped,
);
}
unified_sorted
} else {
unified_sorted
};
// Snapshot before JIT consumes it: the whole-comb backend needs the
// pre-JIT stmts (JIT CompiledBlocks hide stmt-level I/O).
let pre_jit_stmts = Arc::new(unified_sorted.clone());
let comb_statements = try_jit_no_cache(context, unified_sorted);
Ok(comb_pipeline_cache::CombPipeline {
pre_jit_stmts,
required_comb_passes,
comb_statements,
dead_offsets: dead_union.into_iter().collect(),
nontrivial_comb_scc,
})
}
/// Returns the scheduled statements plus an exact required-pass hint when the
/// block-aware sort could derive one (see `stable_topo_sort_with_blocks`);
/// `None` means the caller must fall back to `compute_required_passes`.
pub(crate) fn analyze_dependency(
statements: Vec<ProtoStatement>,
) -> Result<(Vec<ProtoStatement>, Option<usize>), SimulatorError> {
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum Node {
Var(VarOffset),
Statement(usize),
}
let mut table = HashMap::default();
for (i, x) in statements.into_iter().enumerate() {
table.insert(i, x);
}
// Helper: build DAG and attempt stable topological sort (Kahn's algorithm).
// Returns Ok(sorted) on success, Err(failed_id) on cycle.
// Uses FIFO queue initialized in source order to preserve source ordering
// for statements that have no explicit dependency between them.
let try_topo_sort =
|table: &HashMap<usize, ProtoStatement>| -> Result<Vec<ProtoStatement>, usize> {
let mut dag = Dag::<Node, ()>::new();
let mut dag_nodes: HashMap<Node, _> = HashMap::default();
let mut sorted_keys: Vec<usize> = table.keys().cloned().collect();
sorted_keys.sort();
let mut node_to_stmt: HashMap<daggy::NodeIndex, usize> = HashMap::default();
for id in &sorted_keys {
let x = &table[id];
let mut inputs = vec![];
let mut outputs = vec![];
x.gather_variable_offsets(&mut inputs, &mut outputs);
let stmt_node = Node::Statement(*id);
let stmt = dag.add_node(stmt_node);
dag_nodes.insert(stmt_node, stmt);
node_to_stmt.insert(stmt, *id);
let output_set: HashSet<VarOffset> = outputs.iter().cloned().collect();
let mut ok = true;
for var_key in inputs {
if output_set.contains(&var_key) {
continue;
}
let var_node = Node::Var(var_key);
let var = *dag_nodes
.entry(var_node)
.or_insert_with(|| dag.add_node(var_node));
if dag.add_edge(var, stmt, ()).is_err() {
ok = false;
break;
}
}
if !ok {
return Err(*id);
}
for var_key in outputs {
let var_node = Node::Var(var_key);
let var = *dag_nodes
.entry(var_node)
.or_insert_with(|| dag.add_node(var_node));
if dag.add_edge(stmt, var, ()).is_err() {
ok = false;
break;
}
}
if !ok {
return Err(*id);
}
}
let graph = dag.graph();
let node_count = graph.node_count();
let mut in_degree: HashMap<daggy::NodeIndex, usize> = HashMap::default();
for idx in graph.node_indices() {
in_degree.insert(idx, 0);
}
for edge in graph.edge_indices() {
if let Some((_src, tgt)) = graph.edge_endpoints(edge) {
*in_degree.entry(tgt).or_insert(0) += 1;
}
}
let mut queue: VecDeque<daggy::NodeIndex> = VecDeque::new();
let mut zero_nodes: Vec<daggy::NodeIndex> = in_degree
.iter()
.filter(|&(_, °)| deg == 0)
.map(|(&idx, _)| idx)
.collect();
zero_nodes.sort_by_key(|&idx| node_to_stmt.get(&idx).copied().unwrap_or(usize::MAX));
for idx in zero_nodes {
queue.push_back(idx);
}
let mut ret = vec![];
let mut t = table.clone();
let mut visited = 0;
while let Some(idx) = queue.pop_front() {
visited += 1;
if let Node::Statement(x) = graph[idx]
&& let Some(s) = t.remove(&x)
{
ret.push(s);
}
let mut successors: Vec<daggy::NodeIndex> =
graph.neighbors_directed(idx, Outgoing).collect();
successors.sort_by_key(|&s| node_to_stmt.get(&s).copied().unwrap_or(usize::MAX));
for succ in successors {
let deg = in_degree.get_mut(&succ).unwrap();
*deg -= 1;
if *deg == 0 {
queue.push_back(succ);
}
}
}
if visited != node_count {
return Err(sorted_keys[0]);
}
Ok(ret)
};
// Phase 1: Try with CompiledBlocks as atomic nodes. The bipartite model
// orders every reader after ALL writers of its inputs, so the schedule
// settles in exactly one pass.
if let Ok(sorted) = try_topo_sort(&table) {
pass_diag_phase("phase1: bipartite, CBs atomic");
return Ok((sorted, Some(1)));
}
// Phase 2: Expand CompiledBlocks and SequentialBlocks and retry.
// Rebuild the table with fresh sequential IDs so expanded sub-statements
// keep their parent's position; Phase 3's fallback sorts by ID and relies
// on that ordering for `let x = expr` vs `always_comb { x = expr; }` to
// produce equivalent schedules when the block participates in a cycle.
let has_expandable = table.values().any(|x| {
matches!(x, ProtoStatement::CompiledBlock(cb) if !cb.original_stmts.is_empty())
|| matches!(x, ProtoStatement::SequentialBlock(_))
});
// Flattened stmt id → source block (original table key); set by the
// Phase-2 full flatten.
let mut block_of: Option<Vec<usize>> = None;
if has_expandable {
// FAST PATH: flatten only blocks WITHOUT an intra-block reorder hazard
// (a write to a comb var an earlier statement of the block read or
// wrote — WAR/WAW/reassignment); those keep their program order by
// staying atomic. A bipartite topological sort then interleaves the
// hazard-free statements across blocks into a backward-edge-free order
// that settles in ONE comb pass — the common case, where the full
// recursive flatten + stable_topo_sort below instead leaves a backward
// edge for cross-block no-prior-writer reads that doubles the passes.
//
// On failure fall through to that full-flatten path: an atomic hazard
// block's conflated I/O can form a phantom cross-block cycle that the
// bipartite sort rejects but the per-statement flatten resolves.
{
fn block_has_reorder_hazard(stmts: &[ProtoStatement]) -> bool {
let mut seen: HashSet<VarOffset> = HashSet::default();
for s in stmts {
let mut ins = vec![];
let mut outs = vec![];
s.gather_variable_offsets(&mut ins, &mut outs);
ins.retain(|o| !o.is_ff());
outs.retain(|o| !o.is_ff());
if outs.iter().any(|o| seen.contains(o)) {
return true;
}
seen.extend(ins);
seen.extend(outs);
}
false
}
fn hazard_flatten(stmt: ProtoStatement, out: &mut Vec<ProtoStatement>) {
match stmt {
ProtoStatement::CompiledBlock(cb) if !cb.original_stmts.is_empty() => {
if block_has_reorder_hazard(&cb.original_stmts) {
out.push(ProtoStatement::CompiledBlock(cb));
} else {
for sub in cb.original_stmts {
hazard_flatten(sub, out);
}
}
}
ProtoStatement::SequentialBlock(body) => {
if block_has_reorder_hazard(&body) {
out.push(ProtoStatement::SequentialBlock(body));
} else {
for sub in body {
hazard_flatten(sub, out);
}
}
}
other => out.push(other),
}
}
let mut keys: Vec<usize> = table.keys().cloned().collect();
keys.sort();
let mut fast: HashMap<usize, ProtoStatement> = HashMap::default();
let mut id = 0usize;
for key in &keys {
let mut flat = Vec::new();
hazard_flatten(table[key].clone(), &mut flat);
for sub in flat {
fast.insert(id, sub);
id += 1;
}
}
if let Ok(sorted) = try_topo_sort(&fast) {
pass_diag_phase("phase2-fast: hazard-flatten + bipartite");
return Ok((sorted, Some(1)));
}
}
// Recursive: SequentialBlock's gather conflates per-stmt I/O, so
// nested SeqBlocks (e.g. inside a CompiledBlock's original_stmts)
// must be unwrapped too or they manufacture phantom edges.
fn flatten(stmt: ProtoStatement, out: &mut Vec<ProtoStatement>) {
match stmt {
ProtoStatement::CompiledBlock(cb) if !cb.original_stmts.is_empty() => {
for sub in cb.original_stmts {
flatten(sub, out);
}
}
ProtoStatement::SequentialBlock(body) => {
for sub in body {
flatten(sub, out);
}
}
other => out.push(other),
}
}
let mut sorted_keys: Vec<usize> = table.keys().cloned().collect();
sorted_keys.sort();
let mut new_table: HashMap<usize, ProtoStatement> = HashMap::default();
let mut flat_block_of: Vec<usize> = Vec::new();
let mut new_id = 0usize;
for key in sorted_keys {
let stmt = table.remove(&key).unwrap();
let mut flat = Vec::new();
flatten(stmt, &mut flat);
for sub in flat {
new_table.insert(new_id, sub);
flat_block_of.push(key);
new_id += 1;
}
}
table = new_table;
block_of = Some(flat_block_of);
// Sort the flattened (program-order) statements with the block-aware