namespace Spice86.Core.Emulator.CPU.CfgCpu.ParsedInstruction;
using Spice86.Core.Emulator.CPU.CfgCpu.Ast;
using Spice86.Core.Emulator.CPU.CfgCpu.ControlFlowGraph;
using Spice86.Core.Emulator.CPU.CfgCpu.InstructionExecutor;
using Spice86.Core.Emulator.CPU.CfgCpu.ParsedInstruction.Prefix;
using Spice86.Core.Emulator.CPU.Exceptions;
using Spice86.Shared.Emulator.Memory;
using InstructionNode = Spice86.Core.Emulator.CPU.CfgCpu.Ast.Instruction.InstructionNode;
using System.Collections.Immutable;
using System.Linq;
///
/// Base of all the instructions: Prefixes (optional) and an opcode that can be either one or 2 bytes.
///
public sealed class CfgInstruction : CfgNode {
///
/// Classifies the control-flow role of this instruction.
///
public InstructionKind Kind { get; init; } = InstructionKind.None;
/// True when this instruction is a RET or IRET.
public bool IsReturn => Kind.HasFlag(InstructionKind.Return);
/// True when this instruction is a CALL.
public bool IsCall => Kind.HasFlag(InstructionKind.Call);
/// True when this instruction is a JMP (any form).
public bool IsJump => Kind.HasFlag(InstructionKind.Jump);
/// True when this instruction represents an invalid opcode.
public bool IsInvalid => Kind.HasFlag(InstructionKind.Invalid);
private bool _canCauseContextRestore;
///
public override bool CanCauseContextRestore => _canCauseContextRestore;
/// Marks this instruction as one that can restore execution context (e.g., IRET).
internal void EnableCanCauseContextRestore() => _canCauseContextRestore = true;
///
/// The call that corresponds to this return instruction, with the successor type the
/// call-to-return-target edge must carry. Only meaningful when is true.
///
public CorrespondingCall? CurrentCorrespondingCall { get; set; }
private InstructionNode? _instructionAst;
private IVisitableAstNode? _executionAst;
///
/// Attaches pre-built ASTs produced by the parser.
/// Each specific parser calls it once, immediately after all fields are registered.
/// calls it again to add the interrupt shadow to an SS write.
///
internal void AttachAsts(InstructionNode instructionAst, IVisitableAstNode executionAst) {
_instructionAst = instructionAst;
_executionAst = executionAst;
}
///
/// Instructions are born observed (not speculative).
///
private bool _isSpeculative;
///
/// Instructions are born live.
///
private bool _isLive = true;
///
/// Explicit block-terminator flag. Set ONLY by the parser via
/// . Combined with and the
/// live in .
///
private bool _explicitBlockTerminator;
///
/// Stored explicit block-starter flag. Set ONLY by the parser via
/// and surfaced by .
///
private bool _isBlockStarter;
///
/// Forces the end of this instruction's while execution still falls through to the next
/// instruction in memory (e.g. STI, POPF): marks it as a block terminator and registers that next
/// instruction as its static successor. Intended to be called by parsers once the instruction is fully parsed.
///
internal void EndBlockAfterFallthrough() {
_explicitBlockTerminator = true;
RegisterStaticSuccessorAddress(NextInMemoryAddress32.ToSegmentedAddress());
}
///
/// Marks this instruction as forcing the start of a new .
/// Intended to be called by parsers (e.g. for CLI) immediately after parsing
/// the instruction. Has no effect on already-set state (the flag is monotonic).
///
internal void MarkAsBlockStarter() => _isBlockStarter = true;
public CfgInstruction(int id, SegmentedAddress address, InstructionField opcodeField,
List prefixes, int? maxSuccessorsCount)
: base(id, address, maxSuccessorsCount) {
InstructionPrefixes = prefixes;
PrefixFields = prefixes.Select(prefix => prefix.PrefixField).ToList();
foreach (InstructionPrefix prefix in prefixes) {
if (prefix is SegmentOverrideInstructionPrefix instructionPrefix) {
SegmentOverrideInstructionPrefix = instructionPrefix;
} else if (prefix is OperandSize32Prefix size32Prefix) {
OperandSize32Prefix = size32Prefix;
} else if (prefix is AddressSize32Prefix addressSize32Prefix) {
AddressSize32Prefix = addressSize32Prefix;
} else if (prefix is RepPrefix repPrefix) {
RepPrefix = repPrefix;
} else if (prefix is LockPrefix lockPrefix) {
LockPrefix = lockPrefix;
}
}
OpcodeField = opcodeField;
AddFields(PrefixFields);
AddField(OpcodeField);
}
///
/// To call after constructor to calculate instruction length
///
private void UpdateLength() {
Length = (byte)FieldsInOrder.Sum(field => field.Length);
NextInMemoryAddress32 = new(Address.Segment, (uint)Address.Offset + Length);
}
///
///
///
public Dictionary SuccessorsPerAddress { get; private set; } = new();
///
///
///
public Dictionary> SuccessorsPerType { get; } = new();
///
/// Successors whose edge from this node was wired speculatively (created by the explorer while the
/// target was speculative), as opposed to being observed during execution. The recorded successor
/// type of such an edge is a speculative guess (typically a Normal fallthrough); when observed
/// execution later reaches the same target via a different edge type, the observed type replaces
/// the speculative one. Membership is dropped once an observed link confirms or re-types the edge.
///
public ISet SpeculativelyWiredSuccessors { get; } = new HashSet();
public override void UpdateSuccessorCache() {
SuccessorsPerAddress = Successors.ToDictionary(node => node.Address);
}
public override ICfgNode? GetNextSuccessor(InstructionExecutionHelper helper) {
if (UniqueSuccessor is not null) {
return UniqueSuccessor;
}
SuccessorsPerAddress.TryGetValue(helper.State.IpSegmentedAddress, out ICfgNode? res);
return res;
}
public override bool IsLive => _isLive;
///
public override bool IsSpeculative => _isSpeculative;
///
///
/// Re-evaluated on every read so that any change to
/// (e.g. via ) is automatically reflected without
/// callers needing to refresh anything. The portion
/// treats null (unbounded) as "not equal to 1" and therefore terminator.
///
public override bool IsBlockTerminator =>
_explicitBlockTerminator
|| (Kind & (InstructionKind.Jump | InstructionKind.Call | InstructionKind.Return)) != 0
|| MaxSuccessorsCount != 1;
///
public override bool IsBlockStarter => _isBlockStarter;
///
///
/// Set exclusively by when this instruction is appended to a
/// . Never cleared on eviction from the current-instructions cache.
///
public override CfgBlock? ContainingBlock { get; set; }
public List FieldsInOrder { get; } = new();
internal void AddField(FieldWithValue fieldWithValue) {
FieldsInOrder.Add(fieldWithValue);
UpdateLength();
}
internal void AddFields(IEnumerable fieldWithValues) {
fieldWithValues.ToList().ForEach(AddField);
}
public SegmentOverrideInstructionPrefix? SegmentOverrideInstructionPrefix { get; }
public OperandSize32Prefix? OperandSize32Prefix { get; }
public AddressSize32Prefix? AddressSize32Prefix { get; }
public RepPrefix? RepPrefix { get; }
public LockPrefix? LockPrefix { get; }
public byte Length { get; private set; }
/// The 32-bit segmented address of the instruction that follows this one in memory.
/// The offset is the raw sum of the instruction's offset and its length, and may exceed 0xFFFF
/// for instructions that cross the 64 KB real-mode segment boundary.
/// Callers that need a real-mode IP value must cast the offset to .
///
public SegmentedAddress32 NextInMemoryAddress32 { get; private set; }
public List InstructionPrefixes { get; }
///
/// List of prefixes for this instruction
///
public List> PrefixFields { get; }
///
/// Opcode
///
public InstructionField OpcodeField { get; }
///
/// What allows to uniquely identify the instruction among other at the same address.
/// Usually all the fields except in some cases when they are modified (example imm value or disp), in this case instead of bytes there will be nulls
///
public Signature Signature {
get {
ImmutableList signatureBytes = ComputeSignatureBytes(FieldsInOrder);
return new Signature(signatureBytes);
}
}
///
/// Same as Signature but only aggregates final fields, ignoring those that can change.
///
public Signature SignatureFinal {
get {
ImmutableList signatureBytes = ComputeSignatureBytes(FieldsInOrder
.Where(x => x.Final));
return new Signature(signatureBytes);
}
}
private ImmutableList ComputeSignatureBytes(IEnumerable bytes) {
return bytes
.Select(field => field.SignatureValue)
.SelectMany(i => i)
.ToImmutableList();
}
///
/// Updates the live state of this instruction.
///
///
/// On an actual transition (when differs from the current value),
/// notifies the exactly once via
/// so the block's non-live
/// instruction counter stays in sync. No-op if the live state is unchanged.
///
public void SetLive(bool isLive) {
if (_isLive == isLive) {
return;
}
_isLive = isLive;
ContainingBlock?.OnContainedInstructionLiveChanged(isLive);
}
///
/// Updates the speculative state of this instruction.
///
///
/// On an actual transition notifies the exactly once via
/// so the block's speculative
/// counter stays in sync. A speculative instruction is always non-live; promotion (clearing the
/// speculative flag) is the only direction that matters for .
/// No-op if the speculative state is unchanged.
///
public override void SetSpeculative(bool isSpeculative) {
if (_isSpeculative == isSpeculative) {
return;
}
_isSpeculative = isSpeculative;
if (isSpeculative) {
SetLive(false);
}
ContainingBlock?.OnContainedInstructionSpeculativeChanged(isSpeculative);
}
///
/// Returns the pre-built display AST set by .
///
public override InstructionNode DisplayAst {
get {
if (_instructionAst is not null) {
return _instructionAst;
}
throw new InvalidOperationException(
$"AttachAsts must be called before accessing DisplayAst for {GetType().Name} at {Address}");
}
}
///
/// Returns the pre-built execution AST set by .
///
public override IVisitableAstNode ExecutionAst {
get {
if (_executionAst is not null) {
return _executionAst;
}
throw new InvalidOperationException(
$"AttachAsts must be called before accessing ExecutionAst for {GetType().Name} at {Address}");
}
}
///
/// Statically-known successor addresses derived from the instruction's decode-time operands.
/// Populated by parsers for instructions with immediate branch
/// targets (Jcc, Jcxz, Loop, near/short jmp imm, near/far call imm). Empty for indirect, RET,
/// IRET, and other forms where the target is not statically knowable.
/// For conditional jumps and loops this contains two entries (taken, fall-through);
/// for unconditional direct jumps/calls it contains the single target.
/// For non-terminator instructions it contains the single fall-through (NextInMemoryAddress32).
/// Every static successor is a Normal control-flow edge; runtime-only classifications
/// (call continuations, misaligned returns, CPU faults) are wired elsewhere, never here.
///
public IReadOnlyList StaticSuccessorAddresses => _staticSuccessorAddresses;
private readonly List _staticSuccessorAddresses = new();
///
/// Records a statically-known successor address. Called by parsers at creation time.
///
internal void RegisterStaticSuccessorAddress(SegmentedAddress address) {
_staticSuccessorAddresses.Add(address);
}
public void IncreaseMaxSuccessorsCount(SegmentedAddress target) {
if (MaxSuccessorsCount is not null && !SuccessorsPerAddress.ContainsKey(target)) {
// Ensure the subsequent link attempt will be done
CanHaveMoreSuccessors = true;
MaxSuccessorsCount++;
// Reset it. Will not be used anymore if MaxSuccessorsCount is now more than 1 or null.
UniqueSuccessor = null;
}
}
}