SILICON
Loading...
Searching...
No Matches
Simulator Class Reference

Executes event-driven simulation of a Circuit. More...

#include <simulator.hpp>

Collaboration diagram for Simulator:

Classes

struct  WaveformInputDriver
 Bus driven by one column of an input waveform. More...
struct  PendingTransitionKeyHash
struct  PendingTransition
struct  StagedWireTransition
struct  StagedCyclicWire
struct  CyclicStaging
struct  ExecutionStep
class  EvaluationStateGuard

Public Types

enum class  RunResult { Completed , Cancelled , StepLimitReached }
 Outcome of a cancellable simulator operation. More...
enum class  EdgeType { RISE , FALL , UNKNOWN , NO_CHANGE }
 Logical edge observed for one wire during a reactive evaluation. More...
using TraceSink = std::function<void(uint64_t, const std::vector<BusValue>&)>
 Receives encoded waveform values for a simulation timestamp.
using CancellationCheck = std::function<bool()>
 Framework-independent cooperative cancellation callback.

Public Member Functions

 Simulator (std::shared_ptr< const Circuit > c, uint64_t initialSimulationTime=0, std::unique_ptr< CircuitWriter > fstWriter=nullptr, CancellationCheck isCancelled={})
 Constructs a Simulator for the given circuit.
RunResult run (uint64_t duration, CancellationCheck isCancelled={})
 Executes the simulation for a specified duration.
RunResult runUntilIdle (CancellationCheck isCancelled={})
 Runs pending timed events until no further propagation is scheduled.
RunResult simulateWaveform (uint64_t duration, std::span< const Sample > inputSnapshots, std::span< const WaveformInputDriver > inputDrivers, CancellationCheck isCancelled={})
 Drives input buses from a sampled internal waveform and runs to duration.
void enableFstTracing (std::string_view fileName, CircuitWriter::Options options={})
 Enables FST tracing for this simulator.
void setFstWriter (std::unique_ptr< CircuitWriter > writer)
 Installs a caller-created FST writer.
void setTraceBuses (std::vector< CircuitWriter::NamedBus > buses)
 Configures bus-level waveform snapshots emitted by the simulator.
void setTraceSink (TraceSink sink)
RunResult setBus (Bus bus, BusValue value, CancellationCheck isCancelled={})
 Forces a bus to a specific value and propagates the change through the circuit.
RunResult setBus (Bus bus, BusValue value, const Component_weakPtr &source, CancellationCheck isCancelled={})
 Forces a bus to a specific value with a source component and propagates the change through the circuit.
RunResult simulateBus (const Bus &bus, CancellationCheck isCancelled={})
 Propagates changes from a bus through the circuit in reverse direction.
void updateWire (const Wire_ptr &target, State newState, uint64_t delay, const Component_weakPtr &source)
 Updates a wire with a new state and optional delay.
void updateBus (const Bus &bus, const BusValue &value, uint64_t delay, const Component_weakPtr &source)
 Updates a bus to a new value through the normal wire-update path.
uint64_t getCurrentTime () const
 Gets the current simulation time.

Static Public Member Functions

static EdgeType edgeType (const Context &context, const Wire_ptr &wire)
 Classifies one wire's transition in a simulation context.
static void setMaxSimulationSteps (uint64_t value)
static void setMaxTransitionsPerDeltaCycle (int value)
static uint64_t getMaxSimulationSteps ()
static int getMaxTransitionsPerDeltaCycle ()

Private Types

using ExecutionStepSet = boost::dynamic_bitset<>
using PendingTransitionKey = std::pair<uint64_t, std::uintptr_t>
using StagedTransitions

Private Member Functions

void initializeExecutionPlan ()
 Builds execution and reachability caches once, during construction.
void emitTraceSnapshot ()
 Emits a waveform snapshot when tracing is enabled.
void scheduleDelayedWireUpdate (const Wire_ptr &target, State newState, uint64_t delay, const Component_weakPtr &source)
bool shouldStageSequentialOutput (const Component_weakPtr &source) const
void stageSequentialWireUpdate (const Wire_ptr &target, State newState, const Component_weakPtr &source)
void stageCyclicWireUpdate (const Wire_ptr &target, State newState, const Component_weakPtr &source)
bool commitStagedCyclicTransitions (CyclicStaging &staging)
void discardStagedCyclicTransitions (CyclicStaging &staging)
std::vector< Bus > commitStagedSequentialTransitions (std::unordered_map< uint64_t, State > &previousWireStates)
RunResult evaluateForwardConeAndTrace (std::span< const Bus > changedBuses, std::unordered_map< uint64_t, State > previousWireStates, const CancellationCheck &isCancelled={}, bool enableSequentialStaging=true)
bool isDelayedEventPending (const TimedEvent &event) const
bool evaluateExecutionStep (const ExecutionStep &step, const Context &context, const CancellationCheck &isCancelled={})
bool evaluateExecutionPlan (std::span< const ExecutionStep > steps, const Context &context, const CancellationCheck &isCancelled={})
bool evaluateExecutionSteps (const ExecutionStepSet &steps, const Context &context, const CancellationCheck &isCancelled={})
ExecutionStepSet getForwardExecutionSteps (std::span< const Bus > changedBuses) const
RunResult applyWaveformInputSample (std::span< const BusValue > values, std::span< const WaveformInputDriver > inputDrivers, const CancellationCheck &isCancelled)
RunResult processNextEventBatch (const CancellationCheck &isCancelled)
RunResult evaluateExecutionPlanAndTrace (std::span< const ExecutionStep > steps, const Context &context, const CancellationCheck &isCancelled={})
 Evaluates a plan and emits a trace snapshot on success.

Static Private Member Functions

static PendingTransitionKey pendingTransitionKey (const Wire_ptr &target, const Component_weakPtr &source)
static std::vector< ExecutionStep > compileExecutionPlan (std::span< const Circuit::SimulationBlock > blocks)

Private Attributes

std::shared_ptr< const Circuit > circuit
 The circuit being simulated.
std::vector< ExecutionStep > executionPlan
 Compiled component/SCC execution plan in topological order.
std::unordered_map< uint64_t, ExecutionStepSet > forwardExecutionStepsByWire
 Cached downstream execution-step membership for each input wire ID.
std::priority_queue< TimedEvent, std::vector< TimedEvent >, std::greater<> > eventQueue
 Priority queue of timed events sorted by time.
std::unordered_map< PendingTransitionKey, PendingTransition, PendingTransitionKeyHash > pendingTransitions
 Latest valid delayed transition for each component-output wire.
StagedTransitions stagedSequentialTransitions
 Zero-delay sequential writes waiting for the active pass to finish.
CyclicStaging * activeCyclicStaging = nullptr
 Active SCC's reusable staging buffer; null outside a cyclic step.
uint64_t currentTime = 0
 Current simulation time.
std::unique_ptr< CircuitWriter > fstWriter
 Optional waveform writer for simulation tracing.
std::vector< CircuitWriter::NamedBus > traceBuses
 Bus list observed by waveform tracing.
TraceSink traceSink
 Optional callback for live waveform viewers.
std::unordered_map< uint64_t, State > * activePreviousWireStates = nullptr
 Previous-state index being populated during the active reactive pass.
bool stageSequentialOutputs = false
 True while reactive evaluation should stage opted-in zero-delay writes.

Static Private Attributes

static uint64_t maxSimulationSteps = 100000
static int maxTransitionsPerDeltaCycle = 1000

Detailed Description

Executes event-driven simulation of a Circuit.

The Simulator manages the execution of a digital circuit using an event-driven simulation paradigm. It handles both acyclic circuit parts (executed once in topological order) and cyclic parts (executed iteratively using delta cycles until convergence).

Note
The simulator compiles the circuit topology into a reusable execution plan. The topology must remain fixed for the simulator's lifetime.

Definition at line 74 of file simulator.hpp.

Member Typedef Documentation

◆ CancellationCheck

using CancellationCheck = std::function<bool()>

Framework-independent cooperative cancellation callback.

Returns
True when the active operation should stop at its next checkpoint

Definition at line 89 of file simulator.hpp.

◆ ExecutionStepSet

using ExecutionStepSet = boost::dynamic_bitset<>
private

Definition at line 274 of file simulator.hpp.

◆ PendingTransitionKey

using PendingTransitionKey = std::pair<uint64_t, std::uintptr_t>
private

Definition at line 276 of file simulator.hpp.

◆ StagedTransitions

◆ TraceSink

using TraceSink = std::function<void(uint64_t, const std::vector<BusValue>&)>

Receives encoded waveform values for a simulation timestamp.

Definition at line 77 of file simulator.hpp.

Member Enumeration Documentation

◆ EdgeType

enum class EdgeType
strong

Logical edge observed for one wire during a reactive evaluation.

Enumerator
RISE 

LOW -> HIGH

FALL 

HIGH -> LOW

UNKNOWN 

A changed transition involving UNKNOWN or ERROR state

NO_CHANGE 

No captured change for this evaluation

Definition at line 99 of file simulator.hpp.

◆ RunResult

enum class RunResult
strong

Outcome of a cancellable simulator operation.

Enumerator
Completed 

The requested operation completed normally

Cancelled 

The caller requested cancellation

StepLimitReached 

The configured simulation step limit was reached

Definition at line 92 of file simulator.hpp.

Constructor & Destructor Documentation

◆ Simulator()

Simulator ( std::shared_ptr< const Circuit > c,
uint64_t initialSimulationTime = 0,
std::unique_ptr< CircuitWriter > fstWriter = nullptr,
CancellationCheck isCancelled = {} )
explicit

Constructs a Simulator for the given circuit.

Parameters
cThe circuit to simulate
initialSimulationTimeIf != 0 also simulate the circuit using initialSimulationTime as duration
fstWriterOptional waveform writer used to trace simulation snapshots
isCancelledOptional cancellation callback used during initial evaluation
Exceptions
std::invalid_argumentIf c is null

Definition at line 144 of file simulator.cpp.

Member Function Documentation

◆ applyWaveformInputSample()

Simulator::RunResult applyWaveformInputSample ( std::span< const BusValue > values,
std::span< const WaveformInputDriver > inputDrivers,
const CancellationCheck & isCancelled )
nodiscardprivate

Definition at line 852 of file simulator.cpp.

◆ commitStagedCyclicTransitions()

bool commitStagedCyclicTransitions ( CyclicStaging & staging)
nodiscardprivate

Definition at line 427 of file simulator.cpp.

◆ commitStagedSequentialTransitions()

std::vector< Bus > commitStagedSequentialTransitions ( std::unordered_map< uint64_t, State > & previousWireStates)
nodiscardprivate

Definition at line 458 of file simulator.cpp.

◆ compileExecutionPlan()

std::vector< Simulator::ExecutionStep > compileExecutionPlan ( std::span< const Circuit::SimulationBlock > blocks)
staticnodiscardprivate

Definition at line 490 of file simulator.cpp.

◆ discardStagedCyclicTransitions()

void discardStagedCyclicTransitions ( CyclicStaging & staging)
private

Definition at line 415 of file simulator.cpp.

◆ edgeType()

Simulator::EdgeType edgeType ( const Context & context,
const Wire_ptr & wire )
staticnodiscard

Classifies one wire's transition in a simulation context.

Parameters
contextReactive evaluation context with previous wire states
wireWire to inspect
Returns
RISE, FALL, UNKNOWN, or NO_CHANGE for this evaluation

Definition at line 125 of file simulator.cpp.

◆ emitTraceSnapshot()

void emitTraceSnapshot ( )
private

Emits a waveform snapshot when tracing is enabled.

Definition at line 297 of file simulator.cpp.

◆ enableFstTracing()

void enableFstTracing ( std::string_view fileName,
CircuitWriter::Options options = {} )

Enables FST tracing for this simulator.

The writer is initialized from the simulator's circuit and immediately receives a snapshot for the current simulation time.

Definition at line 268 of file simulator.cpp.

◆ evaluateExecutionPlan()

bool evaluateExecutionPlan ( std::span< const ExecutionStep > steps,
const Context & context,
const CancellationCheck & isCancelled = {} )
nodiscardprivate

Definition at line 582 of file simulator.cpp.

◆ evaluateExecutionPlanAndTrace()

Simulator::RunResult evaluateExecutionPlanAndTrace ( std::span< const ExecutionStep > steps,
const Context & context,
const CancellationCheck & isCancelled = {} )
nodiscardprivate

Evaluates a plan and emits a trace snapshot on success.

Definition at line 680 of file simulator.cpp.

◆ evaluateExecutionStep()

bool evaluateExecutionStep ( const ExecutionStep & step,
const Context & context,
const CancellationCheck & isCancelled = {} )
nodiscardprivate

Definition at line 536 of file simulator.cpp.

◆ evaluateExecutionSteps()

bool evaluateExecutionSteps ( const ExecutionStepSet & steps,
const Context & context,
const CancellationCheck & isCancelled = {} )
nodiscardprivate

Definition at line 593 of file simulator.cpp.

◆ evaluateForwardConeAndTrace()

Simulator::RunResult evaluateForwardConeAndTrace ( std::span< const Bus > changedBuses,
std::unordered_map< uint64_t, State > previousWireStates,
const CancellationCheck & isCancelled = {},
bool enableSequentialStaging = true )
nodiscardprivate

Definition at line 691 of file simulator.cpp.

◆ getCurrentTime()

uint64_t getCurrentTime ( ) const
inlinenodiscard

Gets the current simulation time.

Returns
Current time in simulation units

Definition at line 265 of file simulator.hpp.

◆ getForwardExecutionSteps()

Simulator::ExecutionStepSet getForwardExecutionSteps ( std::span< const Bus > changedBuses) const
nodiscardprivate

Definition at line 610 of file simulator.cpp.

◆ getMaxSimulationSteps()

uint64_t getMaxSimulationSteps ( )
staticnodiscard

Definition at line 893 of file simulator.cpp.

◆ getMaxTransitionsPerDeltaCycle()

int getMaxTransitionsPerDeltaCycle ( )
staticnodiscard

Definition at line 898 of file simulator.cpp.

◆ initializeExecutionPlan()

void initializeExecutionPlan ( )
private

Builds execution and reachability caches once, during construction.

Definition at line 164 of file simulator.cpp.

◆ isDelayedEventPending()

bool isDelayedEventPending ( const TimedEvent & event) const
nodiscardprivate

Definition at line 478 of file simulator.cpp.

◆ pendingTransitionKey()

Simulator::PendingTransitionKey pendingTransitionKey ( const Wire_ptr & target,
const Component_weakPtr & source )
staticnodiscardprivate

Definition at line 316 of file simulator.cpp.

◆ processNextEventBatch()

Simulator::RunResult processNextEventBatch ( const CancellationCheck & isCancelled)
nodiscardprivate

Definition at line 784 of file simulator.cpp.

◆ run()

Simulator::RunResult run ( uint64_t duration,
CancellationCheck isCancelled = {} )

Executes the simulation for a specified duration.

Uses an event-driven simulation paradigm with a priority queue sorted by time. Processes events in chronological order, re-evaluating blocks when wire states change.

Parameters
durationThe simulation duration in time units
isCancelledOptional cooperative cancellation callback
Returns
Completion, cancellation, or step-limit outcome

Definition at line 733 of file simulator.cpp.

◆ runUntilIdle()

Simulator::RunResult runUntilIdle ( CancellationCheck isCancelled = {})

Runs pending timed events until no further propagation is scheduled.

Unlike run(duration), this is not bounded by a caller-provided time window. It is intended for interactive settling after direct input changes, where the full propagation delay depends on the circuit. Unstable circuits are still bounded by maxSimulationSteps.

Parameters
isCancelledOptional cooperative cancellation callback
Returns
Completion, cancellation, or step-limit outcome

Definition at line 761 of file simulator.cpp.

◆ scheduleDelayedWireUpdate()

void scheduleDelayedWireUpdate ( const Wire_ptr & target,
State newState,
uint64_t delay,
const Component_weakPtr & source )
private

Definition at line 322 of file simulator.cpp.

◆ setBus() [1/2]

Simulator::RunResult setBus ( Bus bus,
BusValue value,
CancellationCheck isCancelled = {} )

Forces a bus to a specific value and propagates the change through the circuit.

Optimized for pass-by-value buses (copies the bus). Evaluates the cached forward execution steps affected by the bus.

Parameters
busThe bus to set
valueThe value to set
isCancelledOptional cooperative cancellation callback
Returns
Completion or cancellation outcome

Definition at line 903 of file simulator.cpp.

◆ setBus() [2/2]

Simulator::RunResult setBus ( Bus bus,
BusValue value,
const Component_weakPtr & source,
CancellationCheck isCancelled = {} )

Forces a bus to a specific value with a source component and propagates the change through the circuit.

Tracks the source component that authorized this state change for proper event propagation. Evaluates the cached forward execution steps affected by the bus.

Parameters
busThe bus to set
valueThe value to set
sourceThe component that authorized this change
isCancelledOptional cooperative cancellation callback
Returns
Completion or cancellation outcome

Definition at line 909 of file simulator.cpp.

◆ setFstWriter()

void setFstWriter ( std::unique_ptr< CircuitWriter > writer)

Installs a caller-created FST writer.

Ownership transfers to the simulator. Passing nullptr disables tracing.

Definition at line 279 of file simulator.cpp.

◆ setMaxSimulationSteps()

void setMaxSimulationSteps ( uint64_t value)
static

Definition at line 883 of file simulator.cpp.

◆ setMaxTransitionsPerDeltaCycle()

void setMaxTransitionsPerDeltaCycle ( int value)
static

Definition at line 888 of file simulator.cpp.

◆ setTraceBuses()

void setTraceBuses ( std::vector< CircuitWriter::NamedBus > buses)

Configures bus-level waveform snapshots emitted by the simulator.

The same registered buses are used for UI waveform snapshots and optional FST export, ensuring both observe exactly the same simulation timing.

Definition at line 285 of file simulator.cpp.

◆ setTraceSink()

void setTraceSink ( TraceSink sink)

Definition at line 291 of file simulator.cpp.

◆ shouldStageSequentialOutput()

bool shouldStageSequentialOutput ( const Component_weakPtr & source) const
nodiscardprivate

Definition at line 343 of file simulator.cpp.

◆ simulateBus()

Simulator::RunResult simulateBus ( const Bus & bus,
CancellationCheck isCancelled = {} )

Propagates changes from a bus through the circuit in reverse direction.

Used when the bus value has changed externally and needs to update upstream components. Extracts backwards subgraph and evaluates each block.

Parameters
busThe bus that changed
isCancelledOptional cooperative cancellation callback
Returns
Completion or cancellation outcome

Definition at line 935 of file simulator.cpp.

◆ simulateWaveform()

Simulator::RunResult simulateWaveform ( uint64_t duration,
std::span< const Sample > inputSnapshots,
std::span< const WaveformInputDriver > inputDrivers,
CancellationCheck isCancelled = {} )

Drives input buses from a sampled internal waveform and runs to duration.

Snapshot values are matched to input drivers by index. Missing values and extra values are ignored, mirroring the viewer's input-only waveform behavior.

Parameters
durationTotal simulation duration in time units
inputSnapshotsTimestamped input values ordered like inputDrivers
inputDriversOrdered buses to drive from each snapshot
isCancelledOptional cooperative cancellation callback
Returns
Completion, cancellation, or step-limit outcome

Definition at line 817 of file simulator.cpp.

◆ stageCyclicWireUpdate()

void stageCyclicWireUpdate ( const Wire_ptr & target,
State newState,
const Component_weakPtr & source )
private

Definition at line 364 of file simulator.cpp.

◆ stageSequentialWireUpdate()

void stageSequentialWireUpdate ( const Wire_ptr & target,
State newState,
const Component_weakPtr & source )
private

Definition at line 350 of file simulator.cpp.

◆ updateBus()

void updateBus ( const Bus & bus,
const BusValue & value,
uint64_t delay,
const Component_weakPtr & source )

Updates a bus to a new value through the normal wire-update path.

Normalizes value to the bus width, then delegates each bit to updateWire() so immediate and delayed updates share the usual simulator bookkeeping.

Parameters
busThe bus to update
valueThe new value
delay
sourceThe component that authorized this change

Definition at line 665 of file simulator.cpp.

◆ updateWire()

void updateWire ( const Wire_ptr & target,
State newState,
uint64_t delay,
const Component_weakPtr & source )

Updates a wire with a new state and optional delay.

Parameters
targetThe wire to update
newStateThe new state
delayDelay in time units (0 for immediate)
sourceThe component that is the source of this change

Definition at line 633 of file simulator.cpp.

Member Data Documentation

◆ activeCyclicStaging

CyclicStaging* activeCyclicStaging = nullptr
private

Active SCC's reusable staging buffer; null outside a cyclic step.

Definition at line 351 of file simulator.hpp.

◆ activePreviousWireStates

std::unordered_map<uint64_t, State>* activePreviousWireStates = nullptr
private

Previous-state index being populated during the active reactive pass.

Definition at line 366 of file simulator.hpp.

◆ circuit

std::shared_ptr<const Circuit> circuit
private

The circuit being simulated.

Definition at line 329 of file simulator.hpp.

◆ currentTime

uint64_t currentTime = 0
private

Current simulation time.

Definition at line 354 of file simulator.hpp.

◆ eventQueue

std::priority_queue<TimedEvent, std::vector<TimedEvent>, std::greater<> > eventQueue
private

Priority queue of timed events sorted by time.

Definition at line 341 of file simulator.hpp.

◆ executionPlan

std::vector<ExecutionStep> executionPlan
private

Compiled component/SCC execution plan in topological order.

Definition at line 335 of file simulator.hpp.

◆ forwardExecutionStepsByWire

std::unordered_map<uint64_t, ExecutionStepSet> forwardExecutionStepsByWire
private

Cached downstream execution-step membership for each input wire ID.

Definition at line 338 of file simulator.hpp.

◆ fstWriter

std::unique_ptr<CircuitWriter> fstWriter
private

Optional waveform writer for simulation tracing.

Definition at line 357 of file simulator.hpp.

◆ maxSimulationSteps

uint64_t maxSimulationSteps = 100000
staticprivate

Definition at line 371 of file simulator.hpp.

◆ maxTransitionsPerDeltaCycle

int maxTransitionsPerDeltaCycle = 1000
staticprivate

Definition at line 372 of file simulator.hpp.

◆ pendingTransitions

std::unordered_map<PendingTransitionKey, PendingTransition, PendingTransitionKeyHash> pendingTransitions
private

Latest valid delayed transition for each component-output wire.

Definition at line 345 of file simulator.hpp.

◆ stagedSequentialTransitions

StagedTransitions stagedSequentialTransitions
private

Zero-delay sequential writes waiting for the active pass to finish.

Definition at line 348 of file simulator.hpp.

◆ stageSequentialOutputs

bool stageSequentialOutputs = false
private

True while reactive evaluation should stage opted-in zero-delay writes.

Definition at line 369 of file simulator.hpp.

◆ traceBuses

std::vector<CircuitWriter::NamedBus> traceBuses
private

Bus list observed by waveform tracing.

Definition at line 360 of file simulator.hpp.

◆ traceSink

TraceSink traceSink
private

Optional callback for live waveform viewers.

Definition at line 363 of file simulator.hpp.


The documentation for this class was generated from the following files: