QBE writer

This commit is contained in:
nub31
2025-07-03 21:49:50 +02:00
parent 7f63180b00
commit 0d0fc14e61
3 changed files with 165 additions and 224 deletions

View File

@@ -1,85 +0,0 @@
using System.Text;
using Syntax;
using Syntax.Tokenization;
using Syntax.Typing.BoundNode;
namespace Generation.QBE;
public class QBEDebugEmitter
{
private readonly StringBuilder _builder;
private int _currentLine = -1;
private readonly Dictionary<string, int> _fileMap = new();
private int _nextFileId = 0;
public QBEDebugEmitter(StringBuilder builder)
{
_builder = builder;
}
public int RegisterFile(string fileName)
{
if (_fileMap.TryGetValue(fileName, out var existingId))
{
return existingId;
}
var fileId = _nextFileId++;
_fileMap[fileName] = fileId;
_builder.AppendLine($"# Debug file {fileId}: {fileName}");
return fileId;
}
public void EmitDebugLocation(SourceSpan span)
{
if (span.IsEmpty)
return;
var line = span.Start.Line;
if (_currentLine != line)
{
_builder.AppendLine($" dbgloc {line}");
_currentLine = line;
}
}
public void EmitDebugLocation(Token token)
{
EmitDebugLocation(token.Span);
}
public void EmitDebugLocation(BoundNode node)
{
var firstToken = node.Tokens.FirstOrDefault();
if (firstToken != null)
{
EmitDebugLocation(firstToken);
}
}
public void EmitDebugLocation(IEnumerable<Token> tokens)
{
var firstToken = tokens.FirstOrDefault();
if (firstToken != null)
{
EmitDebugLocation(firstToken);
}
}
public void ForceEmitDebugLocation(SourceSpan span)
{
if (!span.IsEmpty)
{
_builder.AppendLine($" dbgloc {span.Start.Line}");
_currentLine = span.Start.Line;
}
}
public void ResetLineTracker()
{
_currentLine = -1;
}
}

View File

@@ -15,9 +15,7 @@ public static class QBEGenerator
private static BoundSyntaxTree _syntaxTree = null!; private static BoundSyntaxTree _syntaxTree = null!;
private static BoundDefinitionTable _definitionTable = null!; private static BoundDefinitionTable _definitionTable = null!;
private static QBEDebugEmitter _debugEmitter = null!; private static QBEWriter _writer = new();
private static StringBuilder _builder = new();
private static List<CStringLiteral> _cStringLiterals = []; private static List<CStringLiteral> _cStringLiterals = [];
private static List<StringLiteral> _stringLiterals = []; private static List<StringLiteral> _stringLiterals = [];
private static Stack<string> _breakLabels = []; private static Stack<string> _breakLabels = [];
@@ -37,8 +35,7 @@ public static class QBEGenerator
_syntaxTree = syntaxTree; _syntaxTree = syntaxTree;
_definitionTable = definitionTable; _definitionTable = definitionTable;
_builder = new StringBuilder(); _writer = new QBEWriter();
_debugEmitter = new QBEDebugEmitter(_builder);
_cStringLiterals = []; _cStringLiterals = [];
_stringLiterals = []; _stringLiterals = [];
@@ -54,39 +51,39 @@ public static class QBEGenerator
_stringLiteralIndex = 0; _stringLiteralIndex = 0;
_codeIsReachable = true; _codeIsReachable = true;
_builder.AppendLine($"dbgfile \"{file}\""); _writer.WriteLine($"dbgfile \"{file}\"");
_builder.AppendLine(); _writer.WriteLine();
foreach (var structDef in _definitionTable.GetStructs()) foreach (var structDef in _definitionTable.GetStructs())
{ {
EmitStructDefinition(structDef); EmitStructDefinition(structDef);
_builder.AppendLine(); _writer.WriteLine();
} }
foreach (var funcDef in _syntaxTree.Definitions.OfType<BoundLocalFuncDefinitionNode>()) foreach (var funcDef in _syntaxTree.Definitions.OfType<BoundLocalFuncDefinitionNode>())
{ {
EmitFuncDefinition(funcDef, FuncName(funcDef), funcDef.Parameters, funcDef.ReturnType, funcDef.Body, funcDef.Exported); EmitFuncDefinition(funcDef, FuncName(funcDef), funcDef.Parameters, funcDef.ReturnType, funcDef.Body, funcDef.Exported);
_builder.AppendLine(); _writer.WriteLine();
} }
while (_anonymousFunctions.TryDequeue(out var anon)) while (_anonymousFunctions.TryDequeue(out var anon))
{ {
EmitFuncDefinition(anon.Func, anon.Name, anon.Func.Parameters, anon.Func.ReturnType, anon.Func.Body, false); EmitFuncDefinition(anon.Func, anon.Name, anon.Func.Parameters, anon.Func.ReturnType, anon.Func.Body, false);
_builder.AppendLine(); _writer.WriteLine();
} }
foreach (var cStringLiteral in _cStringLiterals) foreach (var cStringLiteral in _cStringLiterals)
{ {
_builder.AppendLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}"); _writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}");
} }
foreach (var stringLiteral in _stringLiterals) foreach (var stringLiteral in _stringLiterals)
{ {
var bytes = Encoding.UTF8.GetBytes(stringLiteral.Value).Select(b => $"b {b}"); var bytes = Encoding.UTF8.GetBytes(stringLiteral.Value).Select(b => $"b {b}");
_builder.AppendLine($"data {stringLiteral.Name} = {{ l {stringLiteral.Value.Length}, {string.Join(", ", bytes)} }}"); _writer.WriteLine($"data {stringLiteral.Name} = {{ l {stringLiteral.Value.Length}, {string.Join(", ", bytes)} }}");
} }
return _builder.ToString(); return _writer.ToString();
} }
private static string VarName() private static string VarName()
@@ -144,7 +141,7 @@ public static class QBEGenerator
_ => throw new NotSupportedException($"'{type}' type cannot be used in store instructions") _ => throw new NotSupportedException($"'{type}' type cannot be used in store instructions")
}; };
_builder.AppendLine($" {store} {value}, {destination}"); _writer.WriteLine($" {store} {value}, {destination}");
} }
private static Val EmitLoad(NubType type, string from) private static Val EmitLoad(NubType type, string from)
@@ -168,38 +165,38 @@ public static class QBEGenerator
_ => throw new NotSupportedException($"'{type}' type cannot be used in load instructions") _ => throw new NotSupportedException($"'{type}' type cannot be used in load instructions")
}; };
_builder.AppendLine($" {into} {QBEAssign(type)} {load} {from}"); _writer.WriteLine($" {into} {QBEAssign(type)} {load} {from}");
return new Val(into, type, ValKind.Direct); return new Val(into, type, ValKind.Direct);
} }
private static void EmitMemcpy(string source, string destination, string length) private static void EmitMemcpy(string source, string destination, string length)
{ {
_builder.AppendLine($" call $nub_memcpy(l {source}, l {destination}, l {length})"); _writer.WriteLine($" call $nub_memcpy(l {source}, l {destination}, l {length})");
} }
private static string EmitArraySizeInBytes(NubArrayType type, string array) private static string EmitArraySizeInBytes(NubArrayType type, string array)
{ {
var size = VarName(); var size = VarName();
_builder.AppendLine($" {size} =l loadl {array}"); _writer.WriteLine($" {size} =l loadl {array}");
_builder.AppendLine($" {size} =l mul {size}, {SizeOf(type.ElementType)}"); _writer.WriteLine($" {size} =l mul {size}, {SizeOf(type.ElementType)}");
_builder.AppendLine($" {size} =l add {size}, 8"); _writer.WriteLine($" {size} =l add {size}, 8");
return size; return size;
} }
private static string EmitCStringSizeInBytes(string cstring) private static string EmitCStringSizeInBytes(string cstring)
{ {
var size = VarName(); var size = VarName();
_builder.AppendLine($" {size} =l call $nub_cstring_length(l {cstring})"); _writer.WriteLine($" {size} =l call $nub_cstring_length(l {cstring})");
_builder.AppendLine($" {size} =l add {size}, 1"); _writer.WriteLine($" {size} =l add {size}, 1");
return size; return size;
} }
private static string EmitStringSizeInBytes(string nubstring) private static string EmitStringSizeInBytes(string nubstring)
{ {
var size = VarName(); var size = VarName();
_builder.AppendLine($" {size} =l loadl {nubstring}"); _writer.WriteLine($" {size} =l loadl {nubstring}");
_builder.AppendLine($" {size} =l add {size}, 8"); _writer.WriteLine($" {size} =l add {size}, 8");
return size; return size;
} }
@@ -257,7 +254,7 @@ public static class QBEGenerator
case NubStringType: case NubStringType:
{ {
var buffer = VarName(); var buffer = VarName();
_builder.AppendLine($" {buffer} =l alloc8 {size}"); _writer.WriteLine($" {buffer} =l alloc8 {size}");
EmitMemcpy(value, buffer, size); EmitMemcpy(value, buffer, size);
EmitStore(source.Type, buffer, destinationPointer); EmitStore(source.Type, buffer, destinationPointer);
return; return;
@@ -327,7 +324,7 @@ public static class QBEGenerator
_ => throw new ArgumentOutOfRangeException(nameof(complexType)) _ => throw new ArgumentOutOfRangeException(nameof(complexType))
}; };
_builder.AppendLine($" {destination} =l alloc8 {size}"); _writer.WriteLine($" {destination} =l alloc8 {size}");
EmitMemcpy(value, destination, size); EmitMemcpy(value, destination, size);
return destination; return destination;
} }
@@ -465,20 +462,22 @@ public static class QBEGenerator
private static void EmitFuncDefinition(BoundNode debugNode, string name, List<BoundFuncParameter> parameters, NubType returnType, BoundBlockNode body, bool exported) private static void EmitFuncDefinition(BoundNode debugNode, string name, List<BoundFuncParameter> parameters, NubType returnType, BoundBlockNode body, bool exported)
{ {
_debugEmitter.ResetLineTracker(); _writer.ResetLineTracker();
_variables.Clear(); _variables.Clear();
_variableScopes.Clear(); _variableScopes.Clear();
var builder = new StringBuilder();
if (exported) if (exported)
{ {
_builder.Append("export "); builder.Append("export ");
} }
_builder.Append("function "); builder.Append("function ");
if (returnType is not NubVoidType) if (returnType is not NubVoidType)
{ {
_builder.Append(returnType switch builder.Append(returnType switch
{ {
NubPrimitiveType primitiveType => primitiveType.Kind switch NubPrimitiveType primitiveType => primitiveType.Kind switch
{ {
@@ -496,10 +495,10 @@ public static class QBEGenerator
NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l", NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l",
_ => throw new NotSupportedException($"'{returnType}' type cannot be used as a function return type") _ => throw new NotSupportedException($"'{returnType}' type cannot be used as a function return type")
}); });
_builder.Append(' '); builder.Append(' ');
} }
_builder.Append(name); builder.Append(name);
var parameterStrings = parameters.Select(parameter => var parameterStrings = parameters.Select(parameter =>
{ {
@@ -525,10 +524,10 @@ public static class QBEGenerator
return $"{qbeType} %{parameter.Name}"; return $"{qbeType} %{parameter.Name}";
}); });
_builder.AppendLine($"({string.Join(", ", parameterStrings)}) {{"); builder.Append($"({string.Join(", ", parameterStrings)}) {{");
_builder.AppendLine("@start");
_debugEmitter.EmitDebugLocation(debugNode); _writer.WriteLine(builder.ToString());
_writer.WriteLine("@start");
List<Variable> parameterVars = []; List<Variable> parameterVars = [];
@@ -542,19 +541,19 @@ public static class QBEGenerator
{ {
case PrimitiveTypeKind.I16: case PrimitiveTypeKind.I16:
parameterName = VarName(); parameterName = VarName();
_builder.AppendLine($" {parameterName} =w extsh %{parameter.Name}"); _writer.WriteLine($" {parameterName} =w extsh %{parameter.Name}");
break; break;
case PrimitiveTypeKind.I8: case PrimitiveTypeKind.I8:
parameterName = VarName(); parameterName = VarName();
_builder.AppendLine($" {parameterName} =w extsb %{parameter.Name}"); _writer.WriteLine($" {parameterName} =w extsb %{parameter.Name}");
break; break;
case PrimitiveTypeKind.U16: case PrimitiveTypeKind.U16:
parameterName = VarName(); parameterName = VarName();
_builder.AppendLine($" {parameterName} =w extuh %{parameter.Name}"); _writer.WriteLine($" {parameterName} =w extuh %{parameter.Name}");
break; break;
case PrimitiveTypeKind.U8: case PrimitiveTypeKind.U8:
parameterName = VarName(); parameterName = VarName();
_builder.AppendLine($" {parameterName} =w extub %{parameter.Name}"); _writer.WriteLine($" {parameterName} =w extub %{parameter.Name}");
break; break;
} }
} }
@@ -568,16 +567,18 @@ public static class QBEGenerator
{ {
if (returnType is NubVoidType) if (returnType is NubVoidType)
{ {
_builder.AppendLine(" ret"); _writer.WriteLine(" ret");
} }
} }
_builder.AppendLine("}"); _writer.WriteLine("}");
} }
private static void EmitStructDefinition(BoundStructDefinitionNode structDefinition) private static void EmitStructDefinition(BoundStructDefinitionNode structDefinition)
{ {
_builder.Append($"type {StructName(structDefinition)} = {{ "); var builder = new StringBuilder();
builder.Append($"type {StructName(structDefinition)} = {{ ");
foreach (var structDefinitionField in structDefinition.Fields) foreach (var structDefinitionField in structDefinition.Fields)
{ {
var qbeType = structDefinitionField.Type switch var qbeType = structDefinitionField.Type switch
@@ -596,10 +597,12 @@ public static class QBEGenerator
NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l", NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l",
_ => throw new NotSupportedException($"'{structDefinitionField.Type}' type cannot be used in structs") _ => throw new NotSupportedException($"'{structDefinitionField.Type}' type cannot be used in structs")
}; };
_builder.Append(qbeType + ", "); builder.Append(qbeType + ", ");
} }
_builder.AppendLine("}"); builder.Append("}");
_writer.WriteLine(builder.ToString());
} }
private static void EmitStatement(BoundStatementNode statement) private static void EmitStatement(BoundStatementNode statement)
@@ -637,8 +640,6 @@ public static class QBEGenerator
private static void EmitAssignment(BoundAssignmentNode assignment) private static void EmitAssignment(BoundAssignmentNode assignment)
{ {
_debugEmitter.EmitDebugLocation(assignment);
var destination = EmitExpression(assignment.Expression); var destination = EmitExpression(assignment.Expression);
Debug.Assert(destination.Kind == ValKind.Pointer); Debug.Assert(destination.Kind == ValKind.Pointer);
EmitCopyIntoOrInitialize(assignment.Value, destination.Name); EmitCopyIntoOrInitialize(assignment.Value, destination.Name);
@@ -646,8 +647,6 @@ public static class QBEGenerator
private static void EmitBlock(BoundBlockNode block, List<Variable>? variables = null) private static void EmitBlock(BoundBlockNode block, List<Variable>? variables = null)
{ {
_debugEmitter.EmitDebugLocation(block);
_variableScopes.Push(_variables.Count); _variableScopes.Push(_variables.Count);
if (variables != null) if (variables != null)
{ {
@@ -673,34 +672,28 @@ public static class QBEGenerator
private static void EmitBreak(BoundBreakNode @break) private static void EmitBreak(BoundBreakNode @break)
{ {
_debugEmitter.EmitDebugLocation(@break); _writer.WriteLine($" jmp {_breakLabels.Peek()}");
_builder.AppendLine($" jmp {_breakLabels.Peek()}");
_codeIsReachable = false; _codeIsReachable = false;
} }
private static void EmitContinue(BoundContinueNode @continue) private static void EmitContinue(BoundContinueNode @continue)
{ {
_debugEmitter.EmitDebugLocation(@continue); _writer.WriteLine($" jmp {_continueLabels.Peek()}");
_builder.AppendLine($" jmp {_continueLabels.Peek()}");
_codeIsReachable = false; _codeIsReachable = false;
} }
private static void EmitIf(BoundIfNode ifStatement) private static void EmitIf(BoundIfNode ifStatement)
{ {
_debugEmitter.EmitDebugLocation(ifStatement);
var trueLabel = LabelName(); var trueLabel = LabelName();
var falseLabel = LabelName(); var falseLabel = LabelName();
var endLabel = LabelName(); var endLabel = LabelName();
var result = EmitUnwrap(EmitExpression(ifStatement.Condition)); var result = EmitUnwrap(EmitExpression(ifStatement.Condition));
_builder.AppendLine($" jnz {result}, {trueLabel}, {falseLabel}"); _writer.WriteLine($" jnz {result}, {trueLabel}, {falseLabel}");
_builder.AppendLine(trueLabel); _writer.WriteLine(trueLabel);
EmitBlock(ifStatement.Body); EmitBlock(ifStatement.Body);
_builder.AppendLine($" jmp {endLabel}"); _writer.WriteLine($" jmp {endLabel}");
_builder.AppendLine(falseLabel); _writer.WriteLine(falseLabel);
if (ifStatement.Else.HasValue) if (ifStatement.Else.HasValue)
{ {
ifStatement.Else.Value.Match ifStatement.Else.Value.Match
@@ -710,30 +703,26 @@ public static class QBEGenerator
); );
} }
_builder.AppendLine(endLabel); _writer.WriteLine(endLabel);
} }
private static void EmitReturn(BoundReturnNode @return) private static void EmitReturn(BoundReturnNode @return)
{ {
_debugEmitter.EmitDebugLocation(@return);
if (@return.Value.HasValue) if (@return.Value.HasValue)
{ {
var result = EmitUnwrap(EmitExpression(@return.Value.Value)); var result = EmitUnwrap(EmitExpression(@return.Value.Value));
_builder.AppendLine($" ret {result}"); _writer.WriteLine($" ret {result}");
} }
else else
{ {
_builder.AppendLine(" ret"); _writer.WriteLine(" ret");
} }
} }
private static void EmitVariableDeclaration(BoundVariableDeclarationNode variableDeclaration) private static void EmitVariableDeclaration(BoundVariableDeclarationNode variableDeclaration)
{ {
_debugEmitter.EmitDebugLocation(variableDeclaration);
var variable = VarName(); var variable = VarName();
_builder.AppendLine($" {variable} =l alloc8 {SizeOf(variableDeclaration.Type)}"); _writer.WriteLine($" {variable} =l alloc8 {SizeOf(variableDeclaration.Type)}");
if (variableDeclaration.Assignment.HasValue) if (variableDeclaration.Assignment.HasValue)
{ {
@@ -745,8 +734,6 @@ public static class QBEGenerator
private static void EmitWhile(BoundWhileNode whileStatement) private static void EmitWhile(BoundWhileNode whileStatement)
{ {
_debugEmitter.EmitDebugLocation(whileStatement);
var conditionLabel = LabelName(); var conditionLabel = LabelName();
var iterationLabel = LabelName(); var iterationLabel = LabelName();
var endLabel = LabelName(); var endLabel = LabelName();
@@ -754,13 +741,13 @@ public static class QBEGenerator
_breakLabels.Push(endLabel); _breakLabels.Push(endLabel);
_continueLabels.Push(conditionLabel); _continueLabels.Push(conditionLabel);
_builder.AppendLine($" jmp {conditionLabel}"); _writer.WriteLine($" jmp {conditionLabel}");
_builder.AppendLine(iterationLabel); _writer.WriteLine(iterationLabel);
EmitBlock(whileStatement.Body); EmitBlock(whileStatement.Body);
_builder.AppendLine(conditionLabel); _writer.WriteLine(conditionLabel);
var result = EmitUnwrap(EmitExpression(whileStatement.Condition)); var result = EmitUnwrap(EmitExpression(whileStatement.Condition));
_builder.AppendLine($" jnz {result}, {iterationLabel}, {endLabel}"); _writer.WriteLine($" jnz {result}, {iterationLabel}, {endLabel}");
_builder.AppendLine(endLabel); _writer.WriteLine(endLabel);
_continueLabels.Pop(); _continueLabels.Pop();
_breakLabels.Pop(); _breakLabels.Pop();
@@ -788,8 +775,6 @@ public static class QBEGenerator
private static Val EmitAnonymousFunc(BoundAnonymousFuncNode anonymousFunc) private static Val EmitAnonymousFunc(BoundAnonymousFuncNode anonymousFunc)
{ {
_debugEmitter.EmitDebugLocation(anonymousFunc);
var name = $"$anon_func{++_anonymousFuncIndex}"; var name = $"$anon_func{++_anonymousFuncIndex}";
_anonymousFunctions.Enqueue((anonymousFunc, name)); _anonymousFunctions.Enqueue((anonymousFunc, name));
return new Val(name, anonymousFunc.Type, ValKind.Direct); return new Val(name, anonymousFunc.Type, ValKind.Direct);
@@ -797,71 +782,65 @@ public static class QBEGenerator
private static Val EmitArrayIndexAccess(BoundArrayIndexAccessNode arrayIndexAccess) private static Val EmitArrayIndexAccess(BoundArrayIndexAccessNode arrayIndexAccess)
{ {
_debugEmitter.EmitDebugLocation(arrayIndexAccess);
var array = EmitUnwrap(EmitExpression(arrayIndexAccess.Array)); var array = EmitUnwrap(EmitExpression(arrayIndexAccess.Array));
var index = EmitUnwrap(EmitExpression(arrayIndexAccess.Index)); var index = EmitUnwrap(EmitExpression(arrayIndexAccess.Index));
var elementType = ((NubArrayType)arrayIndexAccess.Array.Type).ElementType; var elementType = ((NubArrayType)arrayIndexAccess.Array.Type).ElementType;
var pointer = VarName(); var pointer = VarName();
_builder.AppendLine($" {pointer} =l mul {index}, {SizeOf(elementType)}"); _writer.WriteLine($" {pointer} =l mul {index}, {SizeOf(elementType)}");
_builder.AppendLine($" {pointer} =l add {pointer}, 8"); _writer.WriteLine($" {pointer} =l add {pointer}, 8");
_builder.AppendLine($" {pointer} =l add {array}, {pointer}"); _writer.WriteLine($" {pointer} =l add {array}, {pointer}");
return new Val(pointer, arrayIndexAccess.Type, ValKind.Pointer); return new Val(pointer, arrayIndexAccess.Type, ValKind.Pointer);
} }
private static void EmitArrayBoundsCheck(string array, string index) private static void EmitArrayBoundsCheck(string array, string index)
{ {
var count = VarName(); var count = VarName();
_builder.AppendLine($" {count} =l loadl {array}"); _writer.WriteLine($" {count} =l loadl {array}");
var isNegative = VarName(); var isNegative = VarName();
_builder.AppendLine($" {isNegative} =w csltl {index}, 0"); _writer.WriteLine($" {isNegative} =w csltl {index}, 0");
var isOob = VarName(); var isOob = VarName();
_builder.AppendLine($" {isOob} =w csgel {index}, {count}"); _writer.WriteLine($" {isOob} =w csgel {index}, {count}");
var anyOob = VarName(); var anyOob = VarName();
_builder.AppendLine($" {anyOob} =w or {isNegative}, {isOob}"); _writer.WriteLine($" {anyOob} =w or {isNegative}, {isOob}");
var oobLabel = LabelName(); var oobLabel = LabelName();
var notOobLabel = LabelName(); var notOobLabel = LabelName();
_builder.AppendLine($" jnz {anyOob}, {oobLabel}, {notOobLabel}"); _writer.WriteLine($" jnz {anyOob}, {oobLabel}, {notOobLabel}");
_builder.AppendLine(oobLabel); _writer.WriteLine(oobLabel);
_builder.AppendLine($" call $nub_panic_array_oob()"); _writer.WriteLine($" call $nub_panic_array_oob()");
_builder.AppendLine(notOobLabel); _writer.WriteLine(notOobLabel);
} }
private static Val EmitArrayInitializer(BoundArrayInitializerNode arrayInitializer) private static Val EmitArrayInitializer(BoundArrayInitializerNode arrayInitializer)
{ {
_debugEmitter.EmitDebugLocation(arrayInitializer);
var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity)); var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity));
var elementSize = SizeOf(arrayInitializer.ElementType); var elementSize = SizeOf(arrayInitializer.ElementType);
var capacityInBytes = VarName(); var capacityInBytes = VarName();
_builder.AppendLine($" {capacityInBytes} =l mul {capacity}, {elementSize}"); _writer.WriteLine($" {capacityInBytes} =l mul {capacity}, {elementSize}");
var totalSize = VarName(); var totalSize = VarName();
_builder.AppendLine($" {totalSize} =l add {capacityInBytes}, 8"); _writer.WriteLine($" {totalSize} =l add {capacityInBytes}, 8");
var arrayPointer = VarName(); var arrayPointer = VarName();
_builder.AppendLine($" {arrayPointer} =l alloc8 {totalSize}"); _writer.WriteLine($" {arrayPointer} =l alloc8 {totalSize}");
_builder.AppendLine($" storel {capacity}, {arrayPointer}"); _writer.WriteLine($" storel {capacity}, {arrayPointer}");
var dataPointer = VarName(); var dataPointer = VarName();
_builder.AppendLine($" {dataPointer} =l add {arrayPointer}, 8"); _writer.WriteLine($" {dataPointer} =l add {arrayPointer}, 8");
_builder.AppendLine($" call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})"); _writer.WriteLine($" call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})");
return new Val(arrayPointer, arrayInitializer.Type, ValKind.Direct); return new Val(arrayPointer, arrayInitializer.Type, ValKind.Direct);
} }
private static Val EmitDereference(BoundDereferenceNode dereference) private static Val EmitDereference(BoundDereferenceNode dereference)
{ {
_debugEmitter.EmitDebugLocation(dereference);
var pointerType = (NubPointerType)dereference.Expression.Type; var pointerType = (NubPointerType)dereference.Expression.Type;
var pointer = EmitExpression(dereference.Expression); var pointer = EmitExpression(dereference.Expression);
@@ -877,8 +856,6 @@ public static class QBEGenerator
private static Val EmitAddressOf(BoundAddressOfNode addressOf) private static Val EmitAddressOf(BoundAddressOfNode addressOf)
{ {
_debugEmitter.EmitDebugLocation(addressOf);
var value = EmitExpression(addressOf.Expression); var value = EmitExpression(addressOf.Expression);
Debug.Assert(value.Kind == ValKind.Pointer); Debug.Assert(value.Kind == ValKind.Pointer);
return new Val(value.Name, addressOf.Type, ValKind.Direct); return new Val(value.Name, addressOf.Type, ValKind.Direct);
@@ -886,8 +863,6 @@ public static class QBEGenerator
private static Val EmitBinaryExpression(BoundBinaryExpressionNode binaryExpression) private static Val EmitBinaryExpression(BoundBinaryExpressionNode binaryExpression)
{ {
_debugEmitter.EmitDebugLocation(binaryExpression);
var left = EmitUnwrap(EmitExpression(binaryExpression.Left)); var left = EmitUnwrap(EmitExpression(binaryExpression.Left));
var right = EmitUnwrap(EmitExpression(binaryExpression.Right)); var right = EmitUnwrap(EmitExpression(binaryExpression.Right));
@@ -895,7 +870,7 @@ public static class QBEGenerator
var instruction = EmitBinaryInstructionFor(binaryExpression.Operator, binaryExpression.Left.Type, left, right); var instruction = EmitBinaryInstructionFor(binaryExpression.Operator, binaryExpression.Left.Type, left, right);
_builder.AppendLine($" {outputName} {QBEAssign(binaryExpression.Left.Type)} {instruction} {left}, {right}"); _writer.WriteLine($" {outputName} {QBEAssign(binaryExpression.Left.Type)} {instruction} {left}, {right}");
return new Val(outputName, binaryExpression.Type, ValKind.Direct); return new Val(outputName, binaryExpression.Type, ValKind.Direct);
} }
@@ -915,13 +890,13 @@ public static class QBEGenerator
{ {
if (type.IsSignedInteger) if (type.IsSignedInteger)
{ {
_builder.AppendLine($" {left} =w extsb {left}"); _writer.WriteLine($" {left} =w extsb {left}");
_builder.AppendLine($" {right} =w extsb {right}"); _writer.WriteLine($" {right} =w extsb {right}");
} }
else else
{ {
_builder.AppendLine($" {left} =w extub {left}"); _writer.WriteLine($" {left} =w extub {left}");
_builder.AppendLine($" {right} =w extub {right}"); _writer.WriteLine($" {right} =w extub {right}");
} }
suffix = 'w'; suffix = 'w';
@@ -930,13 +905,13 @@ public static class QBEGenerator
{ {
if (type.IsSignedInteger) if (type.IsSignedInteger)
{ {
_builder.AppendLine($" {left} =w extsh {left}"); _writer.WriteLine($" {left} =w extsh {left}");
_builder.AppendLine($" {right} =w extsh {right}"); _writer.WriteLine($" {right} =w extsh {right}");
} }
else else
{ {
_builder.AppendLine($" {left} =w extuh {left}"); _writer.WriteLine($" {left} =w extuh {left}");
_builder.AppendLine($" {right} =w extuh {right}"); _writer.WriteLine($" {right} =w extuh {right}");
} }
suffix = 'w'; suffix = 'w';
@@ -1005,8 +980,6 @@ public static class QBEGenerator
private static Val EmitIdentifier(BoundIdentifierNode identifier) private static Val EmitIdentifier(BoundIdentifierNode identifier)
{ {
_debugEmitter.EmitDebugLocation(identifier);
if (_definitionTable.LookupFunc(identifier.Namespace.Or(_syntaxTree.Namespace), identifier.Name).TryGetValue(out var func)) if (_definitionTable.LookupFunc(identifier.Namespace.Or(_syntaxTree.Namespace), identifier.Name).TryGetValue(out var func))
{ {
return new Val(FuncName(func), identifier.Type, ValKind.Direct); return new Val(FuncName(func), identifier.Type, ValKind.Direct);
@@ -1022,8 +995,6 @@ public static class QBEGenerator
private static Val EmitLiteral(BoundLiteralNode literal) private static Val EmitLiteral(BoundLiteralNode literal)
{ {
_debugEmitter.EmitDebugLocation(literal);
switch (literal.Kind) switch (literal.Kind)
{ {
case LiteralKind.Integer: case LiteralKind.Integer:
@@ -1106,15 +1077,13 @@ public static class QBEGenerator
private static Val EmitStructInitializer(BoundStructInitializerNode structInitializer, string? destination = null) private static Val EmitStructInitializer(BoundStructInitializerNode structInitializer, string? destination = null)
{ {
_debugEmitter.EmitDebugLocation(structInitializer);
var structDefinition = _definitionTable.LookupStruct(structInitializer.StructType.Namespace, structInitializer.StructType.Name).GetValue(); var structDefinition = _definitionTable.LookupStruct(structInitializer.StructType.Namespace, structInitializer.StructType.Name).GetValue();
if (destination == null) if (destination == null)
{ {
destination = VarName(); destination = VarName();
var size = SizeOf(structInitializer.StructType); var size = SizeOf(structInitializer.StructType);
_builder.AppendLine($" {destination} =l alloc8 {size}"); _writer.WriteLine($" {destination} =l alloc8 {size}");
} }
foreach (var field in structDefinition.Fields) foreach (var field in structDefinition.Fields)
@@ -1127,7 +1096,7 @@ public static class QBEGenerator
Debug.Assert(valueExpression != null); Debug.Assert(valueExpression != null);
var offset = VarName(); var offset = VarName();
_builder.AppendLine($" {offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}"); _writer.WriteLine($" {offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}");
EmitCopyIntoOrInitialize(valueExpression, offset); EmitCopyIntoOrInitialize(valueExpression, offset);
} }
@@ -1136,8 +1105,6 @@ public static class QBEGenerator
private static Val EmitUnaryExpression(BoundUnaryExpressionNode unaryExpression) private static Val EmitUnaryExpression(BoundUnaryExpressionNode unaryExpression)
{ {
_debugEmitter.EmitDebugLocation(unaryExpression);
var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand)); var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand));
var outputName = VarName(); var outputName = VarName();
@@ -1148,16 +1115,16 @@ public static class QBEGenerator
switch (unaryExpression.Operand.Type) switch (unaryExpression.Operand.Type)
{ {
case NubPrimitiveType { Kind: PrimitiveTypeKind.I64 }: case NubPrimitiveType { Kind: PrimitiveTypeKind.I64 }:
_builder.AppendLine($" {outputName} =l neg {operand}"); _writer.WriteLine($" {outputName} =l neg {operand}");
return new Val(outputName, unaryExpression.Type, ValKind.Direct); return new Val(outputName, unaryExpression.Type, ValKind.Direct);
case NubPrimitiveType { Kind: PrimitiveTypeKind.I32 or PrimitiveTypeKind.I16 or PrimitiveTypeKind.I8 }: case NubPrimitiveType { Kind: PrimitiveTypeKind.I32 or PrimitiveTypeKind.I16 or PrimitiveTypeKind.I8 }:
_builder.AppendLine($" {outputName} =w neg {operand}"); _writer.WriteLine($" {outputName} =w neg {operand}");
return new Val(outputName, unaryExpression.Type, ValKind.Direct); return new Val(outputName, unaryExpression.Type, ValKind.Direct);
case NubPrimitiveType { Kind: PrimitiveTypeKind.F64 }: case NubPrimitiveType { Kind: PrimitiveTypeKind.F64 }:
_builder.AppendLine($" {outputName} =d neg {operand}"); _writer.WriteLine($" {outputName} =d neg {operand}");
return new Val(outputName, unaryExpression.Type, ValKind.Direct); return new Val(outputName, unaryExpression.Type, ValKind.Direct);
case NubPrimitiveType { Kind: PrimitiveTypeKind.F32 }: case NubPrimitiveType { Kind: PrimitiveTypeKind.F32 }:
_builder.AppendLine($" {outputName} =s neg {operand}"); _writer.WriteLine($" {outputName} =s neg {operand}");
return new Val(outputName, unaryExpression.Type, ValKind.Direct); return new Val(outputName, unaryExpression.Type, ValKind.Direct);
} }
@@ -1168,7 +1135,7 @@ public static class QBEGenerator
switch (unaryExpression.Operand.Type) switch (unaryExpression.Operand.Type)
{ {
case NubPrimitiveType { Kind: PrimitiveTypeKind.Bool }: case NubPrimitiveType { Kind: PrimitiveTypeKind.Bool }:
_builder.AppendLine($" {outputName} =w xor {operand}, 1"); _writer.WriteLine($" {outputName} =w xor {operand}, 1");
return new Val(outputName, unaryExpression.Type, ValKind.Direct); return new Val(outputName, unaryExpression.Type, ValKind.Direct);
} }
@@ -1185,8 +1152,6 @@ public static class QBEGenerator
private static Val EmitMemberAccess(BoundMemberAccessNode memberAccess) private static Val EmitMemberAccess(BoundMemberAccessNode memberAccess)
{ {
_debugEmitter.EmitDebugLocation(memberAccess);
var item = EmitUnwrap(EmitExpression(memberAccess.Expression)); var item = EmitUnwrap(EmitExpression(memberAccess.Expression));
var output = VarName(); var output = VarName();
@@ -1196,7 +1161,7 @@ public static class QBEGenerator
{ {
if (memberAccess.Member == "count") if (memberAccess.Member == "count")
{ {
_builder.AppendLine($" {output} =l loadl {item}"); _writer.WriteLine($" {output} =l loadl {item}");
return new Val(output, memberAccess.Type, ValKind.Direct); return new Val(output, memberAccess.Type, ValKind.Direct);
} }
@@ -1206,7 +1171,7 @@ public static class QBEGenerator
{ {
if (memberAccess.Member == "count") if (memberAccess.Member == "count")
{ {
_builder.AppendLine($" {output} =l call $nub_string_length(l {item})"); _writer.WriteLine($" {output} =l call $nub_string_length(l {item})");
return new Val(output, memberAccess.Type, ValKind.Direct); return new Val(output, memberAccess.Type, ValKind.Direct);
} }
@@ -1216,7 +1181,7 @@ public static class QBEGenerator
{ {
if (memberAccess.Member == "count") if (memberAccess.Member == "count")
{ {
_builder.AppendLine($" {output} =l call $nub_cstring_length(l {item})"); _writer.WriteLine($" {output} =l call $nub_cstring_length(l {item})");
return new Val(output, memberAccess.Type, ValKind.Direct); return new Val(output, memberAccess.Type, ValKind.Direct);
} }
@@ -1227,7 +1192,7 @@ public static class QBEGenerator
var structDefinition = _definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue(); var structDefinition = _definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue();
var offset = OffsetOf(structDefinition, memberAccess.Member); var offset = OffsetOf(structDefinition, memberAccess.Member);
_builder.AppendLine($" {output} =l add {item}, {offset}"); _writer.WriteLine($" {output} =l add {item}, {offset}");
return new Val(output, memberAccess.Type, ValKind.Pointer); return new Val(output, memberAccess.Type, ValKind.Pointer);
} }
} }
@@ -1237,8 +1202,6 @@ public static class QBEGenerator
private static Val EmitFuncCall(BoundFuncCallNode funcCall) private static Val EmitFuncCall(BoundFuncCallNode funcCall)
{ {
_debugEmitter.EmitDebugLocation(funcCall);
var funcType = (NubFuncType)funcCall.Expression.Type; var funcType = (NubFuncType)funcCall.Expression.Type;
var parameterStrings = new List<string>(); var parameterStrings = new List<string>();
@@ -1274,12 +1237,12 @@ public static class QBEGenerator
{ {
var outputName = VarName(); var outputName = VarName();
_builder.AppendLine($" {outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})"); _writer.WriteLine($" {outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})");
return new Val(outputName, funcCall.Type, ValKind.Direct); return new Val(outputName, funcCall.Type, ValKind.Direct);
} }
else else
{ {
_builder.AppendLine($" call {funcPointer}({string.Join(", ", parameterStrings)})"); _writer.WriteLine($" call {funcPointer}({string.Join(", ", parameterStrings)})");
return new Val(string.Empty, funcCall.Type, ValKind.Direct); return new Val(string.Empty, funcCall.Type, ValKind.Direct);
} }
} }

View File

@@ -0,0 +1,63 @@
using System.Text;
using Syntax;
using Syntax.Typing.BoundNode;
namespace Generation.QBE;
public class QBEWriter
{
private int _currentLine = -1;
private readonly StringBuilder _builder = new();
public void ResetLineTracker()
{
_currentLine = -1;
}
private void WriteDebugLocation(SourceSpan span)
{
if (span.IsEmpty)
return;
var line = span.Start.Line;
if (_currentLine != line)
{
_builder.AppendLine($" dbgloc {line}");
_currentLine = line;
}
}
private void WriteDebugLocation(BoundNode node)
{
var firstToken = node.Tokens.FirstOrDefault();
if (firstToken != null)
{
WriteDebugLocation(firstToken.Span);
}
}
public QBEWriter WriteLine(BoundNode node, string value)
{
WriteDebugLocation(node);
WriteLine(value);
return this;
}
public QBEWriter WriteLine(string value)
{
_builder.AppendLine(value);
return this;
}
public QBEWriter WriteLine()
{
_builder.AppendLine();
return this;
}
public override string ToString()
{
return _builder.ToString();
}
}