namespace Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration;
using Spice86.Core.Emulator.CPU;
using Spice86.Core.Emulator.CPU.CfgCpu.Ast;
using Spice86.Core.Emulator.CPU.CfgCpu.Ast.Instruction;
using Spice86.Core.Emulator.CPU.CfgCpu.Ast.Operations;
using Spice86.Core.Emulator.CPU.CfgCpu.Ast.Value;
using Spice86.Core.Emulator.CPU.CfgCpu.Ast.Value.Constant;
using Spice86.Core.Emulator.CPU.CfgCpu.ControlFlowGraph;
using Spice86.Core.Emulator.InterruptHandlers.Common.Contracts;
using Spice86.Core.Emulator.InterruptHandlers.Dos;
using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Ast;
using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Ir;
using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Model;
using Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Propagation;
using Spice86.Shared.Emulator.Memory;
using System.Globalization;
using System.Linq;
using static Spice86.Core.Emulator.ReverseEngineer.CfgCodeGeneration.Ast.CodeGenerationAst;
///
/// Writes a tree of runtime and code-generation AST nodes as C# statements. Expressions are printed by
/// ; labels come from . With
/// a ServiceCalled statement is printed before each direct
/// interrupt service call (see ).
///
internal sealed class CSharpStatementPrinter(CSharpSourceWriter writer, CSharpExpressionPrinter expressions,
Func labelOf, bool printAsmComments, bool serviceCallNotifications = false) {
private (SegmentedAddress Address, int FirstLine)? _openInstruction;
/// The line range of every instruction printed so far, in method-relative line
/// indices; populated even when suppresses the comment.
public List InstructionLines { get; } = [];
/// Closes the open instruction's line range; the emitter calls it after the method
/// body so the last instruction ends at the method's last printed line.
public void FinishInstructions() => CloseInstruction();
private void CloseInstruction() {
if (_openInstruction is { } open) {
InstructionLines.Add(new MethodInstructionLine(open.Address, open.FirstLine,
writer.LineCount - 1));
_openInstruction = null;
}
}
/// The goto targets of the whole method being printed. A
/// for rewrite refuses a loop when any statement of the method - not only of the block
/// being dispatched - jumps to its header or its step.
public GotoTargets MethodGotoTargets => expressions.MethodGotoTargets;
/// Writes in statement position. The statement walk runs on an explicit
/// stack - nodes to print interleaved with writer operations - so arbitrarily deep
/// if / else chains cannot overflow the thread's stack.
public void Print(IVisitableAstNode node) {
Stack pending = new();
Dispatch(node, pending);
while (pending.Count > 0) {
switch (pending.Pop()) {
case Action action:
action();
break;
case IVisitableAstNode next:
Dispatch(next, pending);
break;
case CountedLoop countedLoop:
PushCountedLoop(pending, countedLoop);
break;
case BoundaryPrint boundaryPrint:
PushBoundaryPrint(pending, boundaryPrint);
break;
case StatusFlagRun statusFlagRun:
writer.Line(statusFlagRun.Text);
break;
}
}
}
private void Dispatch(IVisitableAstNode node, Stack pending) {
switch (node) {
case BlockNode block:
PushBlockStatements(pending, block);
return;
case IfElseNode ifElse:
PushIfElse(pending, ifElse);
return;
case WhileNode whileNode:
PushBraced(pending, $"while ({Condition(BranchProbeKind.While, whileNode.Condition)})", whileNode.Body);
return;
case DoWhileNode doWhile:
PushDoWhile(pending, doWhile);
return;
case PreTestLoopNode preTestLoop:
PushBraced(pending, $"while ({Condition(BranchProbeKind.While, preTestLoop.Condition)})", preTestLoop.Body);
return;
case InfiniteLoopNode loop:
PushBraced(pending, "while (true)", loop.Body);
return;
case ThrowNode throwNode:
PrintThrow(throwNode);
return;
case SwitchNode switchNode:
PushSwitch(pending, switchNode);
return;
case CyclicJumpNode cyclicJump:
PrintCyclicJump(cyclicJump);
return;
case CpuFaultTryCatchNode cpuFault:
PushCpuFaultTryCatch(pending, cpuFault);
return;
case FailAsUntestedNode failAsUntested:
PrintFailAsUntested(failAsUntested);
return;
case InstructionBoundaryNode boundary:
PushInstructionBoundary(pending, boundary);
return;
case DivisionNode division:
PrintDivision(division);
return;
case MultiplicationNode multiplication:
PrintMultiplication(multiplication);
return;
case GotoNode gotoNode:
writer.Line($"goto {labelOf(gotoNode.Target)};");
return;
case LabelNode label:
CloseInstruction();
writer.Label(labelOf(label.Target));
return;
case EntryDispatcherLabelNode:
CloseInstruction();
writer.Label("entrydispatcher");
return;
case ReturnNode { Value: ProcedureReturnHelperNode helper } when
expressions.TypedSignature is { } typed:
PrintTypedReturn(helper, typed);
return;
case ReturnNode { Value: InterruptServiceCallNode {
Contract.Transfer: ServiceTransferKind.Terminates } terminating }:
// A terminating service never reaches the code after the site: the call is the
// method's exit, and TerminateCall positions CS:IP at the int's return address so
// the implementation pushes the frame bytes the interpreted int pushed.
writer.Line($"return {HelperCallNames.TerminateCallMethodName}(" +
$"{expressions.Print(terminating.ReturnSegment).Text}, " +
$"{expressions.Print(terminating.ReturnOffset).Text}, " +
$"() => {expressions.Print(terminating).Text});");
return;
case ReturnNode { Value: MethodCallNode tailCall }
when expressions.TypedSignature is not null
&& expressions.TypedSignatures?.Of(tailCall.MethodName) is { } tailSignature:
string tailInvocation = $"{tailCall.MethodName}({tailSignature.ArgumentList})";
writer.Line(tailSignature.Outputs.Count == 0
? $"{tailInvocation};" : $"return {tailInvocation};");
if (tailSignature.Outputs.Count == 0) {
writer.Line("return;");
}
return;
case ReturnNode returnNode:
writer.Line($"return {expressions.Print(returnNode.Value)};");
return;
case InterruptReturnNode interruptReturn:
writer.Line(interruptReturn.Width == BitWidth.WORD_16
? $"return InterruptRet(0x{interruptReturn.Offset:X4});"
: $"return InterruptRet32(0x{interruptReturn.Offset:X4});");
return;
case BreakNode:
writer.Line("break;");
return;
case ContinueNode:
writer.Line("continue;");
return;
case CommentNode comment:
writer.Line($"// {comment.Text}");
return;
case InstructionStartNode instructionStart:
CloseInstruction();
if (instructionStart.Address is { } address) {
_openInstruction = (address, writer.LineCount);
}
if (printAsmComments) {
writer.Line($"// {instructionStart.Comment}");
}
return;
case CheckExternalEventsNode checkExternalEvents:
PrintCheckExternalEvents(checkExternalEvents);
return;
case SpeculativeGuardNode speculativeGuard:
PrintSpeculativeGuard(speculativeGuard);
return;
case TupleSwapNode swap:
writer.Line($"({expressions.Print(swap.First).Text}, {expressions.Print(swap.Second).Text}) = ({expressions.Print(swap.Second).Text}, {expressions.Print(swap.First).Text});");
return;
case BinaryOperationNode { BinaryOperation: BinaryOperation.ASSIGN, Left: RegisterNode register } assignment
when IncrementOrDecrement(register, assignment.Right) is string step:
writer.Line($"{expressions.Print(register).Text}{step};");
return;
case BinaryOperationNode { BinaryOperation: BinaryOperation.ASSIGN } assignment
when CompoundAssignment(assignment) is string compound:
writer.Line(compound);
return;
case InterruptServiceCallNode serviceCall:
PrintInterruptServiceCall(serviceCall);
return;
case StackRestoreNode restore:
writer.Line($"({string.Join(", ", restore.Targets.Select(target => target is null ? "_" : expressions.Print(target).Text))}) = Stack.{restore.MethodName}();");
return;
default:
writer.Line(expressions.Print(node).Text + ";");
return;
}
}
///
/// Queues a body print followed by the empty statement C# needs after a label when
/// 's last label is followed only by comments.
///
private void AppendBody(List items, IVisitableAstNode body) {
items.Add(body);
if (TrailingLabel(body) == true) {
items.Add((Action)(() => writer.Line(";")));
}
}
///
/// true when the last thing prints is a label, false when it is a statement,
/// null when it prints only comments or nothing.
///
private static bool? TrailingLabel(IVisitableAstNode node) {
Stack pending = new();
pending.Push(node);
while (pending.Count > 0) {
switch (pending.Pop()) {
case LabelNode:
return true;
case CommentNode:
case InstructionStartNode:
break;
case BlockNode block:
foreach (IVisitableAstNode statement in block.Statements) {
pending.Push(statement);
}
break;
case InstructionBoundaryNode boundary:
pending.Push(boundary.Body);
break;
default:
return false;
}
}
return null;
}
/// A typed service call and the assignment of its return value to the contract's
/// output lvalues. When the call keeps the
/// int frame form: ServiceCall(cs1, 0x0108, Dos, () => Dos.ReadDosVersion()) for a
/// void contract, or (AX, CarryFlag) = ServiceCall(cs1, 0x0108, Dos,
/// () => Dos.OpenFile(0, ...), r => CarryOnInterruptStack(r.carryFlag)) ; the helper pushes
/// the interrupt frame, runs the handler's entry bookkeeping when
/// (the handler argument is printed only
/// then), invokes the service and pops the frame back. A frameless call with entry
/// bookkeeping prints ServiceCall(Dos, () => Dos.ReadDosVersion()) with plain flag
/// outputs, and a call with no bookkeeping prints the bare service call
/// AX = Equipment.GetEquipmentList(); . Register-local
/// promotion can turn an output target into a local (ax = call ), which the existing
/// writeback machinery stores back.
private void PrintInterruptServiceCall(InterruptServiceCallNode call) {
bool hookWritesCallerStack = call.RunsEntryHook && !serviceCallNotifications;
if (call.Vector == 0x21 && !hookWritesCallerStack
&& DosInt21Handler.SavesCallerStack((byte)call.SelectorValue)) {
// The saved pointer addresses the frame top, six bytes below this caller SP. In a check
// build it is printed for an entry-hook call too: a duplicate write of the same value, so
// the save still precedes the ServiceCalled event as it does through the stub.
writer.Line($"{call.PropertyPath}.{nameof(DosInt21Handler.RecordCallerStack)}(SS, SP);");
}
if (serviceCallNotifications) {
writer.Line(ServiceCallNotification(call));
}
if (call.Contract.Transfer is ServiceTransferKind.RunsChild) {
// A typed EXEC call: (AX, flag1, DS, ES) = ExecChild(cs1, 0x0193, 0x21).
string returnAddress = $"{expressions.Print(call.ReturnSegment).Text}, " +
$"{expressions.Print(call.ReturnOffset).Text}";
writer.Line($"{ResultTargets(call)} = {HelperCallNames.ExecChildMethodName}(" +
$"{returnAddress}, 0x{call.Vector:X2});");
return;
}
string invocation = expressions.Print(call).Text;
if (!call.WritesFrame && !call.RunsEntryHook) {
if (call.Results.Count == 0) {
writer.Line(invocation + ";");
return;
}
writer.Line($"{ResultTargets(call)} = {invocation};");
return;
}
string helper;
if (call.WritesFrame) {
string returnAddress = $"{expressions.Print(call.ReturnSegment).Text}, " +
$"{expressions.Print(call.ReturnOffset).Text}";
string handlerArgument = call.RunsEntryHook ? $"{call.PropertyPath}, " : string.Empty;
helper = $"{HelperCallNames.ServiceCallMethodName}({returnAddress}, " +
$"{handlerArgument}() => {invocation}";
} else {
helper = $"{HelperCallNames.ServiceCallMethodName}({call.PropertyPath}, " +
$"() => {invocation}";
}
if (call.Results.Count == 0) {
writer.Line(helper + ");");
return;
}
string stackedFlags = call.WritesFrame
&& expressions.ServiceCallStackedFlags(call) is { } writer_
? $", {writer_}"
: string.Empty;
writer.Line($"{ResultTargets(call)} = {helper}{stackedFlags});");
}
private string ResultTargets(InterruptServiceCallNode call) {
string targets = string.Join(", ",
call.Results.Select(result => expressions.Print(result).Text));
return call.Results.Count == 1 ? targets : $"({targets})";
}
/// The ServiceCalled(vector, selector, inputs); statement of a direct service call. The
/// inputs are the call's own argument expressions, each encoded the way
/// encodes the register its parameter is bound to, so the event the
/// statement raises equals the one the service raises when it is reached through its stub. The
/// expressions are register reads, locals, constants and flags: evaluating them a second time has no
/// effect.
private string ServiceCallNotification(InterruptServiceCallNode call) {
List arguments = [
$"0x{call.Vector:X2}",
call.Selector is null ? "null" : $"0x{call.SelectorValue:X2}"
];
for (int index = 0; index < call.Arguments.Count; index++) {
arguments.Add(ServiceCallInput(call.Service.Inputs[index], call.Arguments[index]));
}
return $"{nameof(CSharpOverrideHelper.ServiceCalled)}({string.Join(", ", arguments)});";
}
private string ServiceCallInput(CpuValues binding, IVisitableAstNode argument) {
if (argument is SegmentedAddressNode address) {
string segment = $"unchecked((ushort)({expressions.Print(address.Segment).Text}))";
string offset = $"unchecked((ushort)({expressions.Print(address.Offset).Text}))";
return $"((uint){segment} << 16) | {offset}";
}
string value = expressions.Print(argument).Text;
return ServiceCallInputs.EncodingOf(binding) switch {
ServiceCallInputs.Encoding.Byte => $"unchecked((byte)({value}))",
ServiceCallInputs.Encoding.Word => $"unchecked((ushort)({value}))",
ServiceCallInputs.Encoding.DoubleWord => $"unchecked((uint)({value}))",
ServiceCallInputs.Encoding.Flag => $"({value}) ? 1u : 0u",
_ => throw new InvalidOperationException(
$"{binding}: only a DS:DX string argument is bound to a segmented address")
};
}
/// The text of a statement condition. Without branch probes it is the printed condition. With
/// them, it is : one probe per operand of a
/// combined condition, none around a constant.
private string Condition(BranchProbeKind kind, ValueNode condition) {
if (expressions.BranchProbes is not { } probes) {
return expressions.Print(condition).Text;
}
return expressions.ProbedCondition(probes, kind, condition, false, null);
}
/// The text of a switch value, inside a Selector probe when branch probes are
/// on. The probe records the address in the value's .
private string SwitchValue(ValueNode value) {
string text = expressions.Print(value).Text;
if (expressions.BranchProbes is not { } probes) {
return text;
}
return probes.Selector(text, value.BranchOrigin?.Address);
}
private void PushIfElse(Stack pending, IfElseNode node) {
List items = [
(Action)(() => writer.OpenBlock($"if ({Condition(BranchProbeKind.If, node.Condition)})"))
];
AppendBody(items, node.TrueCase);
items.Add((Action)(() => writer.CloseBlock()));
IVisitableAstNode falseCase = node.FalseCase;
while (OnlyIfElse(falseCase) is IfElseNode elseIf) {
IfElseNode arm = elseIf;
items.Add((Action)(() => writer.OpenBlock($"else if ({Condition(BranchProbeKind.If, arm.Condition)})")));
AppendBody(items, arm.TrueCase);
items.Add((Action)(() => writer.CloseBlock()));
falseCase = arm.FalseCase;
}
if (!IsEmptyBlock(falseCase)) {
items.Add((Action)(() => writer.OpenBlock("else")));
AppendBody(items, falseCase);
items.Add((Action)(() => writer.CloseBlock()));
}
PushItems(pending, items);
}
private void PushBraced(Stack pending, string header, IVisitableAstNode body) {
List items = [
(Action)(() => writer.OpenBlock(header))
];
AppendBody(items, body);
items.Add((Action)(() => writer.CloseBlock()));
PushItems(pending, items);
}
private void PushDoWhile(Stack pending, DoWhileNode node) {
List items = [
(Action)(() => writer.OpenBlock("do"))
];
AppendBody(items, node.Body);
items.Add((Action)(() => writer.CloseBlock($" while ({Condition(BranchProbeKind.DoWhile, node.Condition)});")));
PushItems(pending, items);
}
private static void PushItems(Stack pending, List items) {
for (int index = items.Count - 1; index >= 0; index--) {
pending.Push(items[index]);
}
}
/// A while loop ( or ) that prints as
/// for : runs once before the first test, runs at
/// the end of every iteration (removed from ), the condition is the loop's own.
private sealed record CountedLoop(ValueNode Condition, IVisitableAstNode Init, IVisitableAstNode Step, BlockNode Body);
/// An whose body is queued as ,
/// which can hold markers; prints with the boundary's local variable
/// suffix like .
private sealed record BoundaryPrint(InstructionBoundaryNode Boundary, IReadOnlyList Items);
/// A whole six-flag run merged into one SetStatusFlags(...) line.
private sealed record StatusFlagRun(string Text);
/// The condition, step and rewritten body of a eligible for the
/// for form, before its init statement is located.
private sealed record CountedLoopShape(string Counter, IVisitableAstNode Step, BlockNode Body);
private static readonly ISet CountedLoopComparisons = new HashSet {
BinaryOperation.EQUAL, BinaryOperation.NOT_EQUAL,
BinaryOperation.LESS_THAN, BinaryOperation.GREATER_THAN,
BinaryOperation.LESS_THAN_OR_EQUAL, BinaryOperation.GREATER_THAN_OR_EQUAL
};
/// Queues the statements of ; a whose
/// counter is a register local initialized right before the loop, tested against a constant and stepped
/// by a constant as the body's last statement is queued as for (init; test; step) instead of
/// while .
private void PushBlockStatements(Stack pending, BlockNode block) {
IReadOnlyList statements = block.Statements;
object?[] slots = new object?[statements.Count];
for (int index = 0; index < statements.Count; index++) {
slots[index] = statements[index];
}
if (expressions.LocalReads is not null) {
for (int index = 0; index < statements.Count; index++) {
switch (statements[index]) {
case PreTestLoopNode loop:
if (CountedLoopShapeOf(block, MethodGotoTargets, loop.Condition, loop.Body, loop.HeaderTarget) is { } shape
&& InitBefore(slots, statements, index, shape.Counter) is { } init) {
slots[index] = new CountedLoop(loop.Condition, init, shape.Step, shape.Body);
}
break;
case WhileNode whileNode:
if (CountedLoopShapeOf(block, MethodGotoTargets, whileNode.Condition, whileNode.Body, null) is { } whileShape
&& InitBefore(slots, statements, index, whileShape.Counter) is { } whileInit) {
slots[index] = new CountedLoop(whileNode.Condition, whileInit, whileShape.Step, whileShape.Body);
}
break;
case InstructionBoundaryNode boundary:
BoundaryCountedLoops(block, MethodGotoTargets, slots, index, boundary);
break;
}
}
}
MergeStatusFlagRuns(slots);
for (int index = statements.Count - 1; index >= 0; index--) {
if (slots[index] is { } item) {
pending.Push(item);
}
}
}
private static readonly ushort[] StatusFlagMasks = [
Flags.Carry, Flags.Parity, Flags.Auxiliary, Flags.Zero, Flags.Sign, Flags.Overflow];
private static readonly string[] StatusFlagArgumentNames = [
"carry", "parity", "auxiliary", "zero", "sign", "overflow"];
/// Replaces every run of six consecutive statements assigning each of the six status flags
/// once - the flag result of one operation, kept for an observer - with a single
/// . Any other statement between them, a repeated or non-status flag, or a
/// value that reads a status flag, or a flag target printed as a local keeps the run unmerged.
private void MergeStatusFlagRuns(object?[] slots) {
for (int index = 0; index + StatusFlagMasks.Length <= slots.Length; index++) {
if (StatusFlagRunOf(slots, index) is not { } run) {
continue;
}
slots[index] = run;
for (int skip = 1; skip < StatusFlagMasks.Length; skip++) {
slots[index + skip] = null;
}
index += StatusFlagMasks.Length - 1;
}
}
private StatusFlagRun? StatusFlagRunOf(object?[] slots, int index) {
string?[] values = new string?[StatusFlagMasks.Length];
for (int offset = 0; offset < StatusFlagMasks.Length; offset++) {
if (slots[index + offset] is not BinaryOperationNode {
BinaryOperation: BinaryOperation.ASSIGN,
Left: CpuFlagNode flag, Right: ValueNode value }) {
return null;
}
int position = Array.IndexOf(StatusFlagMasks, flag.FlagMask);
if (position < 0 || values[position] is not null || ReadsStatusFlag(value)
|| expressions.LocalReads?.ContainsKey(flag) == true) {
return null;
}
values[position] = expressions.Print(value).Text;
}
string arguments = string.Join(", ", StatusFlagArgumentNames
.Select((name, position) => $"{name}: {values[position]}"));
return new StatusFlagRun($"SetStatusFlags({arguments});");
}
/// Whether reads a status flag, directly or through a local that
/// stands for one (a promoted flag's read node stays a ).
private static bool ReadsStatusFlag(ValueNode value) =>
IrAstChildren.Descendants(value).OfType()
.Any(flag => StatusFlagMasks.Contains(flag.FlagMask));
/// Queues a boundary body's statements in which every counted loop whose init is the last
/// statement of the previous sibling boundary became a marker.
private void BoundaryCountedLoops(BlockNode block, GotoTargets targets, object?[] slots, int index,
InstructionBoundaryNode boundary) {
IReadOnlyList inner = boundary.Body.Statements;
List? items = null;
for (int position = 0; position < inner.Count; position++) {
if (inner[position] is not (PreTestLoopNode or WhileNode)) {
continue;
}
(ValueNode condition, BlockNode body, IGotoTarget? header) = inner[position] switch {
PreTestLoopNode preTestLoop => (preTestLoop.Condition, preTestLoop.Body, preTestLoop.HeaderTarget),
WhileNode whileNode => (whileNode.Condition, whileNode.Body, null),
_ => throw new InvalidOperationException()
};
int previous = position - 1;
while (previous >= 0 && CommentOnly(inner[previous])) {
previous--;
}
// A real statement inside the boundary precedes the loop: it, not a sibling boundary, is the
// only possible init, and the body block itself decides that case when it is dispatched.
if (previous >= 0
|| CountedLoopShapeOf(block, targets, condition, body, header) is not { } shape
|| InitBefore(slots, block.Statements, index, shape.Counter) is not { } init) {
continue;
}
items ??= inner.Cast().ToList();
items[position] = new CountedLoop(condition, init, shape.Step, shape.Body);
}
if (items is not null) {
slots[index] = new BoundaryPrint(boundary, items);
}
}
/// The statement right before position of
/// (only comment lines are skipped) when it assigns the local
/// : the statement itself, or the last statement of the previous instruction
/// boundary. Consumed slots are replaced so the init is not printed twice.
private IVisitableAstNode? InitBefore(object?[] slots, IReadOnlyList statements, int index,
string counter) {
int previous = index - 1;
while (previous >= 0 && CommentOnly(statements[previous])) {
previous--;
}
if (previous < 0 || slots[previous] is not IVisitableAstNode candidate) {
return null;
}
if (AssignTo(candidate, counter) is { } init) {
slots[previous] = null;
return init;
}
if (candidate is InstructionBoundaryNode boundary) {
IReadOnlyList inner = boundary.Body.Statements;
if (inner.Count > 0 && AssignTo(inner[^1], counter) is { } boundaryInit) {
slots[previous] = boundary with { Body = new BlockNode(inner.Take(inner.Count - 1).ToArray()) };
return boundaryInit;
}
}
return null;
}
/// A line that only prints a comment: an , a
/// , or an instruction boundary left with only its comment lines.
private static bool CommentOnly(IVisitableAstNode statement) =>
statement is InstructionStartNode or CommentNode
|| statement is InstructionBoundaryNode boundary
&& boundary.Body.Statements.All(inner => inner is InstructionStartNode or CommentNode);
/// The condition, step and rewritten body making a counted loop,
/// or null : the condition compares a register local with a constant; the body's last statement
/// (possibly the last statement of its last instruction boundary) adds or subtracts a constant to that
/// local; no binds to the loop, no goto of the method targets its header,
/// and nothing jumps to the step.
private CountedLoopShape? CountedLoopShapeOf(BlockNode block, GotoTargets targets, ValueNode condition,
BlockNode loopBody, IGotoTarget? headerTarget) {
if (CounterName(condition) is not { } counter) {
return null;
}
IReadOnlyList body = loopBody.Statements;
if (body.Count == 0) {
return null;
}
IVisitableAstNode last = body[^1];
InstructionBoundaryNode? stepBoundary = last as InstructionBoundaryNode;
IReadOnlyList stepList = stepBoundary?.Body.Statements ?? body;
IVisitableAstNode step = stepList[^1];
if (stepBoundary is not null && stepList.Count - 1 <= InstructionStartIndex(stepList)) {
return null;
}
if (!IsStep(step, counter)) {
return null;
}
if (headerTarget is not null && targets.Labels.Contains(headerTarget)) {
return null;
}
if (StepIsJumpedInto(stepBoundary, stepList, targets)) {
return null;
}
if (BindsContinue(loopBody)) {
return null;
}
return new CountedLoopShape(counter, step, ForBody(body, stepBoundary, stepList));
}
private static BlockNode ForBody(IReadOnlyList body,
InstructionBoundaryNode? stepBoundary, IReadOnlyList stepList) {
if (stepBoundary is null) {
return new BlockNode(body.Take(body.Count - 1).ToArray());
}
return new BlockNode([
.. body.Take(body.Count - 1),
stepBoundary with { Body = new BlockNode(stepList.Take(stepList.Count - 1).ToArray()) }]);
}
/// Whether the method jumps to the step's boundary anchor or to a label inside the
/// boundary just before the step: either jump would land past the step in the while but
/// at the step in the for .
private static bool StepIsJumpedInto(InstructionBoundaryNode? stepBoundary,
IReadOnlyList stepList, GotoTargets targets) {
if (stepBoundary?.Anchor is { } anchor && targets.Labels.Contains(anchor)) {
return true;
}
return stepList.Count > 1 && stepList[^2] is LabelNode beforeStep
&& targets.Labels.Contains(beforeStep.Target);
}
private static int InstructionStartIndex(IReadOnlyList statements) {
for (int index = 0; index < statements.Count; index++) {
if (statements[index] is InstructionStartNode) {
return index;
}
}
return -1;
}
/// A directly inside - one outside any nested
/// loop binds to the loop being rewritten, and in a for it would wrongly run the step.
private static bool BindsContinue(BlockNode body) {
Stack pending = new();
foreach (IVisitableAstNode statement in body.Statements) {
pending.Push(statement);
}
while (pending.Count > 0) {
IVisitableAstNode current = pending.Pop();
if (current is ContinueNode) {
return true;
}
if (current is not (WhileNode or WhileWithExitNode or InfiniteLoopNode or DoWhileNode or PreTestLoopNode)) {
foreach (IVisitableAstNode child in ChildStatements(current)) {
pending.Push(child);
}
}
}
return false;
}
/// The local name a comparison operand of substitutes to, when the
/// other operand resolves to a constant; null when neither side matches.
private string? CounterName(ValueNode condition) {
if (condition is not BinaryOperationNode comparison
|| !CountedLoopComparisons.Contains(comparison.BinaryOperation)) {
return null;
}
return CounterOperand(comparison.Left, comparison.Right) ?? CounterOperand(comparison.Right, comparison.Left);
}
private string? CounterOperand(ValueNode localSide, ValueNode constantSide) {
if (ConstantEvaluation.Resolved(constantSide) is not null) {
return LocalNameOf(UnwrapConversions(localSide));
}
return null;
}
/// The name of the local prints as; null when the plan does not
/// substitute it.
private string? LocalNameOf(IVisitableAstNode node) {
IReadOnlyDictionary? reads = expressions.LocalReads;
if (reads is null || !reads.TryGetValue(node, out SubstitutedRead? read) || read is null) {
return null;
}
int castEnd = read.Text.LastIndexOf(')');
return castEnd < 0 ? read.Text : read.Text[(castEnd + 1)..];
}
private static ValueNode UnwrapConversions(ValueNode node) => node switch {
TypeConversionNode conversion => UnwrapConversions(conversion.Value),
ExplicitCastNode { Value: ValueNode value } => UnwrapConversions(value),
_ => node
};
/// when it assigns the local , else
/// null .
private IVisitableAstNode? AssignTo(IVisitableAstNode statement, string counter) =>
statement is BinaryOperationNode { BinaryOperation: BinaryOperation.ASSIGN } assignment
&& LocalNameOf(assignment.Left) == counter ? statement : null;
/// Whether assigns the local from itself
/// plus or minus a constant.
private bool IsStep(IVisitableAstNode statement, string counter) =>
statement is BinaryOperationNode { BinaryOperation: BinaryOperation.ASSIGN } assignment
&& LocalNameOf(assignment.Left) == counter
&& UnwrapConversions(assignment.Right) is BinaryOperationNode {
BinaryOperation: BinaryOperation.PLUS or BinaryOperation.MINUS } arithmetic
&& LocalNameOf(UnwrapConversions(arithmetic.Left)) == counter
&& ConstantEvaluation.Resolved(arithmetic.Right) is not null;
/// The text prints, without its trailing semicolon, for a
/// for header slot.
private string StatementText(IVisitableAstNode statement) => statement switch {
BinaryOperationNode { BinaryOperation: BinaryOperation.ASSIGN, Left: RegisterNode register } assignment
when IncrementOrDecrement(register, assignment.Right) is { } step =>
expressions.Print(register).Text + step,
BinaryOperationNode { BinaryOperation: BinaryOperation.ASSIGN } assignment
when CompoundAssignment(assignment) is { } compound =>
compound[..^1],
_ => expressions.Print(statement).Text
};
private void PushCountedLoop(Stack pending, CountedLoop loop) {
List items = [
(Action)(() => writer.OpenBlock(
$"for ({StatementText(loop.Init)}; {Condition(BranchProbeKind.For, loop.Condition)}; {StatementText(loop.Step)})"))
];
AppendBody(items, loop.Body);
items.Add((Action)(() => writer.CloseBlock()));
PushItems(pending, items);
}
private void PushBoundaryPrint(Stack pending, BoundaryPrint boundaryPrint) {
string savedSuffix = expressions.LocalVariableSuffix;
List items = [
(Action)(() => expressions.LocalVariableSuffix = boundaryPrint.Boundary.LocalVariableSuffix)
];
items.AddRange(boundaryPrint.Items);
items.Add((Action)(() => expressions.LocalVariableSuffix = savedSuffix));
PushItems(pending, items);
}
/// The if that is the only statement of , or null .
private static IfElseNode? OnlyIfElse(IVisitableAstNode node) =>
StatementsOf(node).ToList() is [IfElseNode ifElse] ? ifElse : null;
private static bool IsEmptyBlock(IVisitableAstNode node) => node is BlockNode { Statements.Count: 0 };
private void PrintThrow(ThrowNode node) =>
writer.Line($"throw new {node.ExceptionType.FullName}(\"{CSharpExpressionPrinter.EscapeString(node.Message)}\");");
private void PushSwitch(Stack pending, SwitchNode node) {
List items = [
(Action)(() => writer.OpenBlock($"switch ({SwitchValue(node.Value)})"))
];
foreach (SwitchSection arm in node.Sections) {
items.Add((Action)(() => writer.Line($"case {CaseLabel(node, arm.Label)}:")));
items.Add((Action)(() => writer.Indent()));
AppendBody(items, arm.Body);
items.Add((Action)(() => writer.Dedent()));
}
items.Add((Action)(() => writer.Line("default:")));
items.Add((Action)(() => writer.Indent()));
AppendBody(items, node.Default);
items.Add((Action)(() => writer.Dedent()));
items.Add((Action)(() => writer.CloseBlock()));
PushItems(pending, items);
}
/// The case label text: a switch value holds a segmented
/// address and prints segment and offset as 0xSSSS_OOOO ; any other switch keeps
/// 0x{label:X4} .
private static string CaseLabel(SwitchNode node, uint label) {
if (node.Value.DataType == DataType.UINT32) {
return $"0x{label >> 16:X4}_{label & 0xFFFF:X4}";
}
return $"0x{label:X4}";
}
/// A typed method's ret / retf : the NearReturn(n) /
/// FarReturn(n) statement, then return of the signature's outputs. A count of
/// 0 prints the parameterless overload.
private void PrintTypedReturn(ProcedureReturnHelperNode helper, TypedSignature typed) {
string helperName = (helper.Distance, helper.Width) switch {
(CallDistance.Near, BitWidth.DWORD_32) => "NearReturn32",
(CallDistance.Far, BitWidth.DWORD_32) => "FarReturn32",
(CallDistance.Near, _) => "NearReturn",
_ => "FarReturn"
};
string arguments = TypedReturnArguments(helper);
writer.Line(arguments == "0" ? $"{helperName}();" : $"{helperName}({arguments});");
writer.Line(ReturnText(helper, typed));
}
/// The return text of a typed ret : the outputs' register names, or the
/// local the register-local plan serves an output's exit read from.
private string ReturnText(ProcedureReturnHelperNode helper, TypedSignature typed) {
IReadOnlyList? outputs = null;
expressions.ReturnOutputs?.TryGetValue(helper, out outputs);
IReadOnlyList? merged = null;
expressions.ReturnExpressions?.TryGetValue(helper, out merged);
if (outputs is null && merged is null) {
return typed.ReturnStatement;
}
string[] elements = new string[typed.Outputs.Count];
for (int index = 0; index < elements.Length; index++) {
elements[index] = merged is not null && index < merged.Count
&& merged[index] is { } mergedElement
? CSharpExpressionPrinter.Cast(mergedElement.Type,
expressions.Print(mergedElement.Expression))
: outputs is not null && index < outputs.Count && outputs[index] is { } text
? text : typed.Outputs[index].Register;
}
return TypedSignature.ReturnStatementText(elements);
}
private string TypedReturnArguments(ProcedureReturnHelperNode helper) {
if (helper.Arguments.Count == 0) {
return "0";
}
return string.Join(", ", helper.Arguments.Select(TypedReturnArgumentText));
}
private string TypedReturnArgumentText(IVisitableAstNode argument) {
if (ConstantEvaluation.Resolved(argument) is { } constant) {
return constant.Value.ToString(CultureInfo.InvariantCulture);
}
return expressions.Print(argument).Text;
}
private void PrintCyclicJump(CyclicJumpNode node) {
string delegateName = expressions.TypedSignatures?.DelegateNameOf(node.MethodName) ?? node.MethodName;
string target = node.SingleEntry
? GeneratedOverrideNames.EntryFieldNameOf(delegateName)
: delegateName;
writer.OpenBlock($"if (JumpDispatcher.Jump({target}, 0x{node.LoadOffset:X4}))");
if (expressions.NeedsEntryDispatch) {
writer.Line("loadOffset = JumpDispatcher.NextEntryAddress;");
}
writer.Line("goto entrydispatcher;");
writer.CloseBlock();
writer.Line("return JumpDispatcher.RequiredJumpAsmReturn;");
}
private void PushCpuFaultTryCatch(Stack pending, CpuFaultTryCatchNode node) {
List items = [
(Action)(() => writer.OpenBlock("try"))
];
AppendBody(items, node.Body);
items.Add((Action)(() => writer.CloseBlock()));
items.Add((Action)(() => writer.OpenBlock("catch (CpuException cpuException)")));
items.Add((Action)(() => {
string resumeSegment = expressions.SegmentVariable(node.FaultingInstruction.Segment);
writer.Line($"return DispatchCpuFault(cpuException, {resumeSegment}, 0x{node.FaultingInstruction.Offset:X4}, [{FaultHandlers(node.Handlers)}], [{ResumeTargets(node.ResumeTargets)}]);");
}));
items.Add((Action)(() => writer.CloseBlock()));
PushItems(pending, items);
}
private string FaultHandlers(IReadOnlyList handlers) =>
string.Join(", ", handlers.Select(FaultHandler));
private string ResumeTargets(IReadOnlyList targets) =>
string.Join(", ", targets.Select(target =>
$"new SegmentedAddress({expressions.SegmentVariable(target.Segment)}, 0x{target.Offset:X4})"));
private string FaultHandler(CpuFaultHandler handler) {
string handlerSegment = expressions.SegmentVariable(handler.Handler.Segment);
string invoke = FaultInvoke(handler);
return $"new CpuFaultTarget(new SegmentedAddress({handlerSegment}, 0x{handler.Handler.Offset:X4}), {invoke})";
}
private string FaultInvoke(CpuFaultHandler handler) {
if (handler.SingleEntry) {
return expressions.TypedSignatures?.DelegateNameOf(handler.MethodName) ?? handler.MethodName;
}
return $"() => {handler.MethodName}(0x{handler.LoadOffset:X4})";
}
private void PrintFailAsUntested(FailAsUntestedNode node) {
bool interpolated = node.Parts.Any(part => part.Value is not null);
string message = interpolated ? InterpolatedMessage(node.Parts) : PlainMessage(node.Parts);
writer.Line($"throw FailAsUntested({message});");
}
private static string PlainMessage(IReadOnlyList parts) {
string text = string.Concat(parts.Select(part => CSharpExpressionPrinter.EscapeString(part.Text)));
return $"\"{text}\"";
}
private string InterpolatedMessage(IReadOnlyList parts) {
string text = string.Concat(parts.Select(InterpolatedPart));
return $"$\"{text}\"";
}
private string InterpolatedPart(UntestedMessagePart part) {
if (part.Value is null) {
return EscapeInterpolatedLiteral(part.Text);
}
return Hole(part, part.Value);
}
private static string EscapeInterpolatedLiteral(string text) =>
CSharpExpressionPrinter.EscapeString(text).Replace("{", "{{").Replace("}", "}}");
private string Hole(UntestedMessagePart part, ValueNode value) {
string expression = expressions.Print(value).Text;
if (expression.Contains(':') || expression.Contains('?')) {
expression = $"({expression})";
}
string format = part.Format.Length == 0 ? string.Empty : $":{part.Format}";
return $"{{{expression}{format}}}";
}
private void PushInstructionBoundary(Stack pending, InstructionBoundaryNode node) {
string savedSuffix = expressions.LocalVariableSuffix;
List items = [
(Action)(() => expressions.LocalVariableSuffix = node.LocalVariableSuffix),
node.Body,
(Action)(() => expressions.LocalVariableSuffix = savedSuffix)
];
PushItems(pending, items);
}
private void PrintDivision(DivisionNode node) {
DivisionPattern division = node.Division;
string helperName = (division.Signed, division.Width) switch {
(false, BitWidth.BYTE_8) => nameof(CSharpOverrideHelper.Div8),
(false, BitWidth.WORD_16) => nameof(CSharpOverrideHelper.Div16),
(false, BitWidth.DWORD_32) => nameof(CSharpOverrideHelper.Div32),
(true, BitWidth.BYTE_8) => nameof(CSharpOverrideHelper.IDiv8),
(true, BitWidth.WORD_16) => nameof(CSharpOverrideHelper.IDiv16),
_ => nameof(CSharpOverrideHelper.IDiv32)
};
DataType divisorType = DataType.FromBitWidth(division.Width, division.Signed);
DataType dividendType = DataType.FromBitWidth(division.Width.Double(), division.Signed);
string divisor = CSharpExpressionPrinter.Cast(divisorType, expressions.Print(division.Divisor));
string dividend = CSharpExpressionPrinter.Cast(dividendType, expressions.Print(division.Dividend));
string low = expressions.Print(division.Low);
string high = expressions.Print(division.High);
writer.Line($"({low}, {high}) = {helperName}(divisor: {divisor}, dividend: {dividend});");
}
private void PrintMultiplication(MultiplicationNode node) {
string helperName = (node.Signed, node.Width) switch {
(false, BitWidth.WORD_16) => nameof(CSharpOverrideHelper.Mul16),
(false, BitWidth.DWORD_32) => nameof(CSharpOverrideHelper.Mul32),
(true, BitWidth.WORD_16) => nameof(CSharpOverrideHelper.IMul16),
_ => nameof(CSharpOverrideHelper.IMul32)
};
DataType operandType = DataType.FromBitWidth(node.Width, node.Signed);
string left = CSharpExpressionPrinter.Cast(operandType, expressions.Print(node.Left));
string right = CSharpExpressionPrinter.Cast(operandType, expressions.Print(node.Right));
string low = expressions.Print(node.Low);
string high = expressions.Print(node.High);
writer.Line($"({low}, {high}) = {helperName}({left}, {right});");
}
private void PrintCheckExternalEvents(CheckExternalEventsNode node) {
string resumeSegment = expressions.SegmentVariable(node.ResumeAddress.Segment);
writer.Line($"CheckExternalEvents({resumeSegment}, 0x{node.ResumeAddress.Offset:X4});");
}
private void PrintSpeculativeGuard(SpeculativeGuardNode node) {
string segment = expressions.SegmentVariable(node.Address.Segment);
if (node.SignatureFields.Count == 1) {
writer.Line($"VerifySpeculativeEntryOrFail({segment}, 0x{node.Address.Offset:X4}, {node.SignatureFields[0]});");
return;
}
writer.Line($"VerifySpeculativeRunOrFail({segment}, 0x{node.Address.Offset:X4}, {node.RunFieldName});");
}
/// The X op= y; form of when it is X = X op y in the
/// target's own type and C# accepts 's right operand in a compound assignment,
/// otherwise null . The right operand prints at assignment precedence.
private string? CompoundAssignment(BinaryOperationNode assignment) {
if (assignment.Left.DataType == DataType.BOOL
|| assignment.Right is not BinaryOperationNode operation
|| CompoundOperator(operation.BinaryOperation) is not string compoundOperator
|| operation.DataType != assignment.Left.DataType
|| !SimpleTarget(assignment.Left)
|| expressions.Print(operation.Left).Text != expressions.Print(assignment.Left).Text) {
return null;
}
if (operation.BinaryOperation == BinaryOperation.PLUS
&& ConstantEvaluation.Resolved(operation.Right) is { } added
&& ConstantEvaluation.TrySubtractionMagnitude(added, operation.DataType.BitWidth, out ulong subtracted)) {
ConstantNode magnitude = new(
DataType.UnsignedFromBitWidth(added.DataType.BitWidth), subtracted);
return $"{expressions.Print(assignment.Left).Text} -= {expressions.Print(magnitude).Text};";
}
if (!CompoundOperand(operation, assignment.Left.DataType, out string operand)) {
return null;
}
return $"{expressions.Print(assignment.Left).Text} {compoundOperator}= {operand};";
}
private static string? CompoundOperator(BinaryOperation operation) => operation switch {
BinaryOperation.PLUS => "+",
BinaryOperation.MINUS => "-",
BinaryOperation.BITWISE_AND => "&",
BinaryOperation.BITWISE_OR => "|",
BinaryOperation.BITWISE_XOR => "^",
BinaryOperation.LEFT_SHIFT => "<<",
BinaryOperation.RIGHT_SHIFT => ">>",
_ => null
};
/// The right operand of a compound assignment: a shift takes anything, other operators need a
/// fragment already of the target type or a constant whose value fits it.
private bool CompoundOperand(BinaryOperationNode operation, DataType targetType, out string operand) {
ValueNode right = operation.Right;
CSharpFragment fragment = expressions.Print(right);
if (operation.BinaryOperation is BinaryOperation.LEFT_SHIFT or BinaryOperation.RIGHT_SHIFT) {
operand = ShiftOperandText(right, fragment);
return true;
}
if (fragment.Type != targetType && !FitsInType(ConstantEvaluation.Resolved(right), targetType)) {
operand = string.Empty;
return false;
}
operand = ParenthesizedOperand(fragment);
return true;
}
/// The operand text of a shift compound assignment: the resolved count's text, or the
/// operand parenthesized for assignment precedence.
private static string ShiftOperandText(ValueNode right, CSharpFragment fragment) {
if (ConstantEvaluation.Resolved(right) is { } shiftCount) {
return CSharpExpressionPrinter.ShiftCountText(shiftCount);
}
return ParenthesizedOperand(fragment);
}
/// The operand parenthesized just above assignment precedence.
private static string ParenthesizedOperand(CSharpFragment fragment) =>
CSharpExpressionPrinter.Parenthesize(fragment, CSharpExpressionPrinter.AssignmentPrecedence + 1);
/// Whether 's value fits , which is what C#
/// requires of a compound assignment's constant operand.
private static bool FitsInType(ConstantNode? constant, DataType targetType) {
if (constant is null) {
return false;
}
if (!targetType.Signed) {
return !constant.IsNegative && constant.Value <= ConstantNode.Mask(targetType.BitWidth);
}
ulong maximum = ConstantNode.Mask(targetType.BitWidth) >> 1;
return constant.IsNegative
? constant.SignedValue >= -(long)maximum - 1
: constant.Value <= maximum;
}
/// A target a compound assignment may write: a register or a variable, or a memory slot whose
/// address parts are built only from registers, constants, type conversions and non-assignment binary
/// operations - evaluating them once, as C# does, cannot differ from evaluating them twice.
private static bool SimpleTarget(ValueNode target) => target switch {
RegisterNode or VariableReferenceNode => true,
SegmentedPointerNode or AbsolutePointerNode =>
IrAstChildren.ChildrenOf(target).OfType().All(SimpleOperand),
_ => false
};
private static bool SimpleOperand(ValueNode node) => node switch {
RegisterNode or ConstantNode => true,
InstructionFieldNode or TypeConversionNode or ExplicitCastNode { Value: ValueNode }
or BinaryOperationNode { BinaryOperation: not BinaryOperation.ASSIGN } =>
IrAstChildren.ChildrenOf(node).OfType().All(SimpleOperand),
_ => false
};
///
/// ++ or -- when is plus or minus one in the
/// register's own type, otherwise null .
///
private string? IncrementOrDecrement(RegisterNode register, ValueNode value) {
if (value is not BinaryOperationNode { BinaryOperation: BinaryOperation.PLUS or BinaryOperation.MINUS } arithmetic
|| arithmetic.DataType != register.DataType
|| expressions.Print(arithmetic.Left).Text != expressions.Print(register).Text) {
return null;
}
if (IsOne(arithmetic.Right)) {
return arithmetic.BinaryOperation == BinaryOperation.PLUS ? "++" : "--";
}
if (arithmetic.BinaryOperation == BinaryOperation.PLUS
&& arithmetic.Right is ConstantNode added
&& ConstantEvaluation.TrySubtractionMagnitude(added, arithmetic.DataType.BitWidth, out ulong magnitude)
&& magnitude == 1) {
return "--";
}
return null;
}
private static bool IsOne(ValueNode node) =>
node is ConstantNode { Value: 1 } or InstructionFieldNode { ResolvedNode: ConstantNode { Value: 1 } };
}