diff --git a/src/coreclr/jit/emitwasm.cpp b/src/coreclr/jit/emitwasm.cpp index 16e78849bdd3ba..a58668facde3fa 100644 --- a/src/coreclr/jit/emitwasm.cpp +++ b/src/coreclr/jit/emitwasm.cpp @@ -167,9 +167,9 @@ void emitter::emitIns_Call(const EmitCallParams& params) // TODO-WASM: Generate actual list of types and generate reloc // This is here to exercise the new JIT-EE API - CorInfoWasmType types[] = {CORINFO_WASM_TYPE_VOID}; + CorInfoWasmType types[] = {CORINFO_WASM_TYPE_VOID, CORINFO_WASM_TYPE_I32, CORINFO_WASM_TYPE_I32}; CORINFO_WASM_TYPE_SYMBOL_HANDLE typeHandle = - codeGen->GetCompiler()->info.compCompHnd->getWasmTypeSymbol(types, 1); + codeGen->GetCompiler()->info.compCompHnd->getWasmTypeSymbol(types, 3); id = emitNewInstrSC(EA_HANDLE_CNS_RELOC, (cnsval_ssize_t)(void*)typeHandle); id->idIns(ins); diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs index 95a2ffef04ab21..fa68031839b1d4 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs @@ -637,17 +637,14 @@ public static unsafe void WriteValue(RelocType relocType, void* location, long v PutRiscV64AuipcCombo((uint*)location, value, isStype); break; - case RelocType.WASM_FUNCTION_INDEX_LEB: - case RelocType.WASM_TABLE_INDEX_SLEB: case RelocType.WASM_TYPE_INDEX_LEB: case RelocType.WASM_GLOBAL_INDEX_LEB: - // These wasm relocs do not have offsets, just targets - return; - + case RelocType.WASM_FUNCTION_INDEX_LEB: case RelocType.WASM_MEMORY_ADDR_LEB: DwarfHelper.WritePaddedULEB128(new Span((byte*)location, WASM_PADDED_RELOC_SIZE_32), checked((ulong)value)); return; + case RelocType.WASM_TABLE_INDEX_SLEB: case RelocType.WASM_MEMORY_ADDR_SLEB: DwarfHelper.WritePaddedSLEB128(new Span((byte*)location, WASM_PADDED_RELOC_SIZE_32), value); return; @@ -658,6 +655,9 @@ public static unsafe void WriteValue(RelocType relocType, void* location, long v } } + public static readonly int MaxSize = 8; + // Note: Please update the above field if the max size + // changes when adding a new case to this method. public static int GetSize(RelocType relocType) { return relocType switch @@ -681,6 +681,14 @@ public static int GetSize(RelocType relocType) RelocType.IMAGE_REL_BASED_RISCV64_CALL_PLT => 8, RelocType.IMAGE_REL_BASED_RISCV64_PCREL_I => 8, RelocType.IMAGE_REL_BASED_RISCV64_PCREL_S => 8, + + RelocType.WASM_FUNCTION_INDEX_LEB => WASM_PADDED_RELOC_SIZE_32, + RelocType.WASM_TABLE_INDEX_SLEB => WASM_PADDED_RELOC_SIZE_32, + RelocType.WASM_TYPE_INDEX_LEB => WASM_PADDED_RELOC_SIZE_32, + RelocType.WASM_GLOBAL_INDEX_LEB => WASM_PADDED_RELOC_SIZE_32, + RelocType.WASM_MEMORY_ADDR_LEB => WASM_PADDED_RELOC_SIZE_32, + RelocType.WASM_MEMORY_ADDR_SLEB => WASM_PADDED_RELOC_SIZE_32, + _ => throw new NotSupportedException(), }; } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs index b515c093ba5240..de3352f3aebd67 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs @@ -105,6 +105,11 @@ protected internal enum ObjectNodeOrder StackTraceEmbeddedMetadataNode, StackTraceMethodMappingNode, ArrayOfEmbeddedDataNode, + + // + // Wasm type signatures (need to be emitted some time before the unordered phase) + // + WasmTypeNode, } public class EmbeddedObjectNodeComparer : IComparer diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs index 4bf06bfb6bb9f2..4ef0659e166c1a 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Linq; using ILCompiler.DependencyAnalysis; -using Internal.JitInterface; +using ILCompiler.ObjectWriter; namespace ILCompiler.DependencyAnalysis.Wasm { @@ -12,59 +11,63 @@ namespace ILCompiler.DependencyAnalysis.Wasm // Represents a WASM type signature, e.g. "(i32, i32) -> (i64)". Used as a relocation target for things like 'call_indirect'. // Does not currently support multiple return values; the return type is always the first type in the array and may be Void. // - public class WasmTypeNode : ObjectNode, ISymbolNode + public class WasmTypeNode : ObjectNode, ISymbolNode, ISymbolDefinitionNode { - private readonly CorInfoWasmType[] _types; + private readonly WasmFuncType _type; + public WasmFuncType Type => _type; - public WasmTypeNode(CorInfoWasmType[] types) + public WasmTypeNode(WasmFuncType type) { - _types = types; + _type = type; } public override bool IsShareable => true; - public override int ClassCode => -45678931; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + + public override int ClassCode => (int)ObjectNodeOrder.WasmTypeNode; public override bool StaticDependenciesAreComputed => true; public override ObjectNodeSection GetSection(NodeFactory factory) => ObjectNodeSection.WasmTypeSection; protected override string GetName(NodeFactory factory) - => $"Wasm Type ({string.Join(",", _types.Skip(1))}) -> {_types.FirstOrDefault()}"; + => $"Wasm Type Signature: {Type.ToString()}"; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) - => new ObjectData( - Array.Empty(), - Array.Empty(), - 1, - Array.Empty()); + { + if (relocsOnly) + { + return new ObjectData( + data: Array.Empty(), + relocs: Array.Empty(), + alignment: 1, + definedSymbols: new ISymbolDefinitionNode[] { this }); + } + + byte[] data = new byte[_type.EncodeSize()]; + _type.Encode(data); + + return new ObjectData( + data: data, + relocs: Array.Empty(), + alignment: 1, + definedSymbols: new ISymbolDefinitionNode[] { this }); + } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { - var wtm = (WasmTypeNode)other; - ReadOnlySpan lhs = _types, rhs = wtm._types; + var wtn = (WasmTypeNode)other; // Put shorter signatures earlier in the sort order, on the assumption that they are more likely to be used. - int result = lhs.Length.CompareTo(rhs.Length); + int result = _type.SignatureLength.CompareTo(wtn.Type.SignatureLength); if (result == 0) - result = MemoryExtensions.SequenceCompareTo(lhs, rhs); + return _type.CompareTo(wtn.Type); return result; } public void AppendMangledName(NameMangler nameMangler, Internal.Text.Utf8StringBuilder sb) { - sb.Append(nameMangler.CompilationUnitPrefix); - sb.Append("__wasmtype_"u8); - - foreach (var type in _types) - sb.Append(type switch { - CorInfoWasmType.CORINFO_WASM_TYPE_VOID => 'v', - CorInfoWasmType.CORINFO_WASM_TYPE_V128 => 'V', - CorInfoWasmType.CORINFO_WASM_TYPE_F64 => 'd', - CorInfoWasmType.CORINFO_WASM_TYPE_F32 => 'f', - CorInfoWasmType.CORINFO_WASM_TYPE_I64 => 'j', - CorInfoWasmType.CORINFO_WASM_TYPE_I32 => 'i', - _ => throw new NotImplementedException($"Unknown CorInfoWasmType: {type}"), - }); + _type.AppendMangledName(nameMangler, sb); } public int Offset => 0; diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs new file mode 100644 index 00000000000000..da37129e4b501e --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -0,0 +1,272 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics; +using System.Linq; +using ILCompiler.ObjectWriter; +using Internal.JitInterface; + +namespace ILCompiler.DependencyAnalysis.Wasm +{ + // For now, we only encode Wasm numeric value types. + // These are encoded as a single byte. However, + // not all value types can be encoded this way. + // For example, reference types (see https://webassembly.github.io/spec/core/binary/types.html#reference-types) + // require a more complex encoding. + public enum WasmValueType : byte + { + I32 = 0x7F, + I64 = 0x7E, + F32 = 0x7D, + F64 = 0x7C, + V128 = 0x7B + } + + public enum WasmMutabilityType : byte + { + Const = 0x00, + Mut = 0x01 + } + + public static class WasmValueTypeExtensions + { + public static string ToTypeString(this WasmValueType valueType) + { + return valueType switch + { + WasmValueType.I32 => "i32", + WasmValueType.I64 => "i64", + WasmValueType.F32 => "f32", + WasmValueType.F64 => "f64", + WasmValueType.V128 => "v128", + _ => "unknown", + }; + } + + public static WasmValueType FromCorInfoType(CorInfoWasmType ty) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan((int)ty, byte.MaxValue); + if (Enum.IsDefined(typeof(WasmValueType), (byte)ty)) + { + return (WasmValueType)ty; + } + else + { + throw new InvalidOperationException("Unsupported CorInfoWasmType: " + ty); + } + } + } + +#nullable enable + public readonly struct WasmResultType : IEquatable, IComparable + { + private readonly WasmValueType[] _types; + public ReadOnlySpan Types => _types; + + /// + /// Initializes a new instance of the WasmResultType class with the specified value types. + /// + /// An array of WasmValueType elements representing the types included in the result. If null, an empty array is + /// used. + public WasmResultType(WasmValueType[]? types) + { + _types = types ?? Array.Empty(); + } + + public bool Equals(WasmResultType other) => Types.SequenceEqual(other.Types); + public override bool Equals(object? obj) + { + return obj is WasmResultType other && Equals(other); + } + + public override int GetHashCode() + { + if (_types.Length == 0) + return 0; + + int code = _types[0].GetHashCode(); + for (int i = 1; i < _types.Length; i++) + { + code = HashCode.Combine(code, _types[i].GetHashCode()); + } + + return code; + } + + public int EncodeSize() + { + uint sizeLength = DwarfHelper.SizeOfULEB128((ulong)_types.Length); + return (int)(sizeLength + (uint)_types.Length); + } + + public int Encode(Span buffer) + { + int sizeLength = DwarfHelper.WriteULEB128(buffer, (ulong)_types.Length); + Span rest = buffer.Slice(sizeLength); + for (int i = 0; i < _types.Length; i++) + { + rest[i] = (byte)_types[i]; + } + return (int)(sizeLength + (uint)_types.Length); + } + + public int CompareTo(WasmResultType other) => MemoryExtensions.SequenceCompareTo(Types, other.Types); + + public void AppendMangledName(Internal.Text.Utf8StringBuilder sb, bool isReturn = false) + { + if (isReturn && _types.Length == 0) + { + sb.Append("v"); + return; + } + + foreach (var type in _types) + { + sb.Append(type switch + { + WasmValueType.V128 => 'V', + WasmValueType.F64 => 'd', + WasmValueType.F32 => 'f', + WasmValueType.I64 => 'j', + WasmValueType.I32 => 'i', + _ => throw new NotImplementedException($"Unknown WasmValueType: {type}"), + }); + } + } + } + + public static class WasmResultTypeExtensions + { + public static string ToTypeListString(this WasmResultType result) + { + return string.Join(" ", result.Types.ToArray().Select(t => t.ToTypeString())); + } + } + + public struct WasmFuncType : IEquatable, IComparable + { + private readonly WasmResultType _params; + private readonly WasmResultType _returns; + + public int SignatureLength => _params.Types.Length + _returns.Types.Length; + + public WasmFuncType(WasmResultType paramTypes, WasmResultType returnTypes) + { + _params = paramTypes; + _returns = returnTypes; + } + + public static WasmFuncType FromCorInfoSignature(CorInfoWasmType[] types) + { + WasmResultType rs; + if (types.Length == 0) + { + throw new ArgumentException("Signature must have at least one type for the return value"); + } + + // The first type is the return type + rs = types[0] switch + { + // "void" is actually encoded as an empty type list in Wasm + CorInfoWasmType.CORINFO_WASM_TYPE_VOID => new WasmResultType(Array.Empty()), + _ => new WasmResultType([WasmValueTypeExtensions.FromCorInfoType(types[0])]) + }; + + // The rest are parameter types + WasmResultType ps; + if (types.Length > 1) + { + WasmValueType[] paramTypes = new WasmValueType[types.Length - 1]; + int idx = 0; + foreach (CorInfoWasmType paramType in types.AsSpan().Slice(1)) + { + paramTypes[idx++] = WasmValueTypeExtensions.FromCorInfoType(paramType); + } + ps = new WasmResultType(paramTypes); + } + else + { + ps = new WasmResultType(Array.Empty()); + } + + return new WasmFuncType(ps, rs); + } + + public readonly int EncodeSize() + { + return 1 + _params.EncodeSize() + _returns.EncodeSize(); + } + + public readonly int Encode(Span buffer) + { + int totalSize = EncodeSize(); + buffer[0] = 0x60; // function type indicator + + int paramSize = _params.Encode(buffer.Slice(1)); + int returnSize = _returns.Encode(buffer.Slice(1 + paramSize)); + Debug.Assert(totalSize == 1 + paramSize + returnSize); + + return totalSize; + } + + public bool Equals(WasmFuncType other) + { + return _params.Equals(other._params) && _returns.Equals(other._returns); + } + + public override bool Equals(object? obj) + { + return obj is WasmFuncType other && Equals(other); + } + + public override int GetHashCode() + { + return HashCode.Combine(_params.GetHashCode(), _returns.GetHashCode()); + } + + public override string ToString() + { + string paramList = _params.ToTypeListString(); + string returnList = _returns.ToTypeListString(); + + if (string.IsNullOrEmpty(returnList) && string.IsNullOrEmpty(paramList)) + { + return "(func)"; + } + else if (string.IsNullOrEmpty(returnList)) + { + return $"(func (param {paramList}))"; + } + else if (string.IsNullOrEmpty(paramList)) + { + return $"(func (result {returnList}))"; + } + + return $"(func (param {paramList}) (result {returnList}))"; + } + + public int CompareTo(WasmFuncType other) + { + int paramComparison = _params.CompareTo(other._params); + if (paramComparison != 0) + return paramComparison; + return _returns.CompareTo(other._returns); + } + + public void AppendMangledName(NameMangler nameMangler, Internal.Text.Utf8StringBuilder sb) + { + sb.Append(nameMangler.CompilationUnitPrefix); + sb.Append("__wasmtype_"u8); + _returns.AppendMangledName(sb, isReturn: true); + _params.AppendMangledName(sb); + } + + public Internal.Text.Utf8String GetMangledName(NameMangler mangler) + { + Internal.Text.Utf8StringBuilder sb = new(); + AppendMangledName(mangler, sb); + return sb.ToUtf8String(); + } + } +} diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs index d7dcb15a7a2fe3..9f0f397a364a07 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs @@ -16,6 +16,7 @@ using static ILCompiler.DependencyAnalysis.RelocType; using ObjectData = ILCompiler.DependencyAnalysis.ObjectNode.ObjectData; using CodeDataLayout = CodeDataLayoutMode.CodeDataLayout; +using ILCompiler.DependencyAnalysis.Wasm; namespace ILCompiler.ObjectWriter { @@ -178,12 +179,6 @@ private unsafe void EmitOrResolveRelocation( Utf8String symbolName, long addend) { - if (_nodeFactory.Target.IsWasm) - { - // TODO-WASM: Implement or resolve relocations - return; - } - if (!UsesSubsectionsViaSymbols && relocType is IMAGE_REL_BASED_REL32 or IMAGE_REL_BASED_RELPTR32 or IMAGE_REL_BASED_ARM64_BRANCH26 or IMAGE_REL_BASED_THUMB_BRANCH24 or IMAGE_REL_BASED_THUMB_MOV32_PCREL && @@ -441,12 +436,17 @@ public virtual void EmitObject(Stream outputFileStream, IReadOnlyCollection _params.LengthEncodeFormat != LengthEncodeFormat.None; + internal SectionWriter( ObjectWriter objectWriter, int sectionIndex, @@ -43,7 +45,7 @@ internal SectionWriter( _params = ps; } - private readonly void EmitLengthPrefix(ulong length) + public readonly void EmitLengthPrefix(ulong length) { switch (_params.LengthEncodeFormat) { @@ -57,6 +59,17 @@ private readonly void EmitLengthPrefix(ulong length) } } + public readonly uint LengthPrefixSize(int length) + { + switch (_params.LengthEncodeFormat) + { + case LengthEncodeFormat.ULEB128: + return DwarfHelper.SizeOfULEB128((ulong)length); + default: + return 0; + } + } + public readonly void EmitData(ReadOnlyMemory data) { EmitLengthPrefix((ulong)data.Length); diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs index bcca86d4c73918..875fc4df4c7913 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.Linq; using System.Collections.Generic; +using ILCompiler.DependencyAnalysis.Wasm; namespace ILCompiler.ObjectWriter { @@ -44,156 +45,6 @@ public static WasmFuncType CreateWasmFunc_i32_i32() } } - // For now, we only encode Wasm numeric value types. - // These are encoded as a single byte. However, - // not all value types can be encoded this way. - // For example, reference types (see https://webassembly.github.io/spec/core/binary/types.html#reference-types) - // require a more complex encoding. - public enum WasmValueType : byte - { - I32 = 0x7F, - I64 = 0x7E, - F32 = 0x7D, - F64 = 0x7C - } - - public enum WasmMutabilityType : byte - { - Const = 0x00, - Mut = 0x01 - } - - public static class WasmValueTypeExtensions - { - public static string ToTypeString(this WasmValueType valueType) - { - return valueType switch - { - WasmValueType.I32 => "i32", - WasmValueType.I64 => "i64", - WasmValueType.F32 => "f32", - WasmValueType.F64 => "f64", - _ => "unknown", - }; - } - } - -#nullable enable - public readonly struct WasmResultType : IEquatable - { - private readonly WasmValueType[] _types; - public ReadOnlySpan Types => _types; - - /// - /// Initializes a new instance of the WasmResultType class with the specified value types. - /// - /// An array of WasmValueType elements representing the types included in the result. If null, an empty array is - /// used. - public WasmResultType(WasmValueType[]? types) - { - _types = types ?? Array.Empty(); - } - - public bool Equals(WasmResultType other) => Types.SequenceEqual(other.Types); - public override bool Equals(object? obj) - { - return obj is WasmResultType other && Equals(other); - } - - public override int GetHashCode() - { - if (_types == null || _types.Length == 0) - return 0; - - int code = _types[0].GetHashCode(); - for (int i = 1; i < _types.Length; i++) - { - code = HashCode.Combine(code, _types[i].GetHashCode()); - } - - return code; - } - - public int EncodeSize() - { - uint sizeLength = DwarfHelper.SizeOfULEB128((ulong)_types.Length); - return (int)(sizeLength + (uint)_types.Length); - } - - public int Encode(Span buffer) - { - int sizeLength = DwarfHelper.WriteULEB128(buffer, (ulong)_types.Length); - Span rest = buffer.Slice(sizeLength); - for (int i = 0; i < _types.Length; i++) - { - rest[i] = (byte)_types[i]; - } - return (int)(sizeLength + (uint)_types.Length); - } - } - - public static class WasmResultTypeExtensions - { - public static string ToTypeListString(this WasmResultType result) - { - return string.Join(" ", result.Types.ToArray().Select(t => t.ToTypeString())); - } - } - - public struct WasmFuncType : IEquatable - { - private readonly WasmResultType _params; - private readonly WasmResultType _returns; - - public WasmFuncType(WasmResultType paramTypes, WasmResultType returnTypes) - { - _params = paramTypes; - _returns = returnTypes; - } - - public readonly int EncodeSize() - { - return 1 + _params.EncodeSize() + _returns.EncodeSize(); - } - - public readonly int Encode(Span buffer) - { - int totalSize = EncodeSize(); - buffer[0] = 0x60; // function type indicator - - int paramSize = _params.Encode(buffer.Slice(1)); - int returnSize = _returns.Encode(buffer.Slice(1 + paramSize)); - Debug.Assert(totalSize == 1 + paramSize + returnSize); - - return totalSize; - } - - public bool Equals(WasmFuncType other) - { - return _params.Equals(other._params) && _returns.Equals(other._returns); - } - - public override bool Equals(object? obj) - { - return obj is WasmFuncType other && Equals(other); - } - - public override int GetHashCode() - { - return HashCode.Combine(_params.GetHashCode(), _returns.GetHashCode()); - } - - public override string ToString() - { - string paramList = _params.ToTypeListString(); - string returnList = _returns.ToTypeListString(); - - if (string.IsNullOrEmpty(returnList)) - return $"(func (param {paramList}))"; - return $"(func (param {paramList}) (result {returnList}))"; - } - } - public abstract class WasmImportType : IWasmEncodable { public readonly WasmExternalKind Kind; diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index f69b003b0e9f91..61ca39fac17022 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -17,6 +17,7 @@ using CodeDataLayout = CodeDataLayoutMode.CodeDataLayout; using System.Collections.Immutable; using ILCompiler.ObjectWriter.WasmInstructions; +using ILCompiler.DependencyAnalysis.Wasm; namespace ILCompiler.ObjectWriter { @@ -50,39 +51,29 @@ private void EmitWasmHeader(Stream outputFileStream) outputFileStream.Write([0x1, 0x0, 0x0, 0x0]); } - private Dictionary _uniqueSignatures = new(); + private Dictionary _uniqueSignatures = new(); private Dictionary _uniqueSymbols = new(); private int _signatureCount = 0; private int _methodCount = 0; - private protected override void RecordMethodSignature(ISymbolDefinitionNode symbol, MethodDesc desc) + private protected override void RecordMethodSignature(WasmTypeNode signature) { - // Ensure the signature is recorded with a unique index if we haven't seen an equivalent one yet. - MaybeWriteType(desc); - // Use the signature index to write a new function signature index into the function signature section. - WriteSignatureIndexForFunction(desc); - - _uniqueSymbols.Add(symbol.GetMangledName(_nodeFactory.NameMangler), _methodCount); - _methodCount++; + int signatureIndex = _signatureCount; + var mangledNameBuilder = new Utf8StringBuilder(); + signature.AppendMangledName(_nodeFactory.NameMangler, mangledNameBuilder); + Utf8String mangledName = mangledNameBuilder.ToUtf8String(); + // Note that we do not expect duplicates here, since crossgen's node cache should handle this and all nodes representing + // identical signatures in a module should point to the same node instance + _uniqueSignatures.Add(mangledName, signatureIndex); + _signatureCount++; } - private void MaybeWriteType(MethodDesc desc) + private protected override void RecordMethodDeclaration(ISymbolDefinitionNode symbol, MethodDesc desc) { - WasmFuncType signature = Internal.JitInterface.WasmLowering.GetSignature(desc); - if (_uniqueSignatures.ContainsKey(signature)) - { - return; - } - - // assign the next available index for the signature - int signatureIndex = _signatureCount; - _uniqueSignatures[signature] = signatureIndex; - _signatureCount++; + WriteSignatureIndexForFunction(desc); - SectionWriter writer = GetOrCreateSection(ObjectNodeSection.WasmTypeSection); - int signatureSize = signature.EncodeSize(); - signature.Encode(writer.Buffer.GetSpan(signatureSize)); - writer.Buffer.Advance(signatureSize); + _uniqueSymbols.Add(symbol.GetMangledName(_nodeFactory.NameMangler), _methodCount); + _methodCount++; } private void WriteSignatureIndexForFunction(MethodDesc desc) @@ -90,15 +81,15 @@ private void WriteSignatureIndexForFunction(MethodDesc desc) SectionWriter writer = GetOrCreateSection(WasmObjectNodeSection.FunctionSection); WasmFuncType signature = Internal.JitInterface.WasmLowering.GetSignature(desc); - if (!_uniqueSignatures.TryGetValue(signature, out int signatureIndex)) + Utf8String key = signature.GetMangledName(_nodeFactory.NameMangler); + if (!_uniqueSignatures.TryGetValue(key, out int signatureIndex)) { - throw new InvalidOperationException($"Signature index not found for function: {desc.GetName()}"); + throw new InvalidOperationException($"Signature index of {key} not found for function: {desc.GetName()}"); } writer.WriteULEB128((ulong)signatureIndex); } - private int _numImports; /// /// Writes the given import entry, including its prefix (module/name/kind) and body (external ref). @@ -269,6 +260,8 @@ private protected override void EmitSectionsAndLayout() { GetOrCreateSection(WasmObjectNodeSection.CombinedDataSection); WriteTableSection(); + + PrependCount(SectionByName(ObjectNodeSection.WasmCodeSection.Name), _methodCount); } private void WriteTableSection() @@ -292,31 +285,129 @@ private WasmSection SectionByName(string name) return _sections[index]; } + readonly string[] SectionOrder = + [ + ObjectNodeSection.WasmTypeSection.Name, + WasmObjectNodeSection.ImportSection.Name, + WasmObjectNodeSection.FunctionSection.Name, + WasmObjectNodeSection.TableSection.Name, + WasmObjectNodeSection.ExportSection.Name, + ObjectNodeSection.WasmCodeSection.Name, + WasmObjectNodeSection.CombinedDataSection.Name, + ]; + + private int[] _sectionEmitOrder = null; + private int[] SectionEmitOrder + { + get + { + if (_sectionEmitOrder == null) + { + _sectionEmitOrder = SectionOrder + .Where(name => _sectionNameToIndex.ContainsKey(name)) + .Select(name => _sectionNameToIndex[name]) + .ToArray(); + } + + return _sectionEmitOrder; + } + } + private protected override void EmitObjectFile(Stream outputFileStream) { EmitWasmHeader(outputFileStream); + foreach (int index in SectionEmitOrder) + { + WasmSection section = _sections[index]; + // TODO-WASM: handle data section relocations (this is dependent on the WebCIL structure being in place) + if (_resolvableRelocations.TryGetValue(index, out List relocations) && + section.Type is not WasmSectionType.Data) + { + using (Stream originalStream = section.Stream) + { + MemoryStream stream = new MemoryStream((int)originalStream.Length); + originalStream.Position = 0; + originalStream.CopyTo(stream); + ResolveRelocations(stream, relocations); + section.Stream = stream; + // originalStream may be disposed, section.Stream now points to resolved stream + } + } - // Type section (1) - SectionByName(ObjectNodeSection.WasmTypeSection.Name).Emit(outputFileStream); - // Import section (2) - SectionByName(WasmObjectNodeSection.ImportSection.Name).Emit(outputFileStream); - // Function section (3) - SectionByName(WasmObjectNodeSection.FunctionSection.Name).Emit(outputFileStream); - // Table section (4) - SectionByName(WasmObjectNodeSection.TableSection.Name).Emit(outputFileStream); - // Export section (7) - SectionByName(WasmObjectNodeSection.ExportSection.Name).Emit(outputFileStream); - // Code section (10) - WasmSection codeSection = SectionByName(ObjectNodeSection.WasmCodeSection.Name); - PrependCount(codeSection, _methodCount); - codeSection.Emit(outputFileStream); - // Data section (11) (all data segments combined) - SectionByName(WasmObjectNodeSection.CombinedDataSection.Name).Emit(outputFileStream); + section.Emit(outputFileStream); + } } + Dictionary> _resolvableRelocations = new(); + private protected override void EmitRelocations(int sectionIndex, List relocationList) { - // This is a no-op for now under Wasm + foreach (var reloc in relocationList) + { + if (!_resolvableRelocations.TryGetValue(sectionIndex, out List resolvable)) + { + _resolvableRelocations[sectionIndex] = resolvable = new List(); + } + // Unconditionally add the reloc to our resolvable list; all relocs must be resolvable for Wasm since we are linker-less + // and do not emit any relocations in the output object file. + resolvable.Add(reloc); + } + } + + // TODO-WASM: Currently, all Wasm relocs are resolved to 5 byte values unconditionally (the same size as the original placeholder padding), which is wasteful. + // We should remove the padding and shrink the resolved values to their minimal size so we don't bloat the binary size. + private unsafe void ResolveRelocations(MemoryStream sectionStream, List relocs) + { + byte[] relocScratchBuffer = new byte[Relocation.MaxSize]; + + foreach (SymbolicRelocation reloc in relocs) + { + int size = Relocation.GetSize(reloc.Type); + if (size > relocScratchBuffer.Length) + { + throw new InvalidOperationException($"Unsupported relocation size for relocation: {reloc.Type}"); + } + + // We need a pinned raw pointer here for manipulation with Relocation.WriteValue + fixed (byte* pData = ReadRelocToDataSpan(reloc, relocScratchBuffer)) + { + switch (reloc.Type) + { + case RelocType.WASM_TYPE_INDEX_LEB: + { + if (_uniqueSignatures.TryGetValue(reloc.SymbolName, out int index)) + { + Relocation.WriteValue(reloc.Type, pData, index); + WriteRelocFromDataSpan(reloc, pData); + } + else + { + throw new InvalidDataException($"Type signature symbol definition '{reloc.SymbolName}' not found"); + } + + break; + } + default: + // TODO-WASM: add other cases as needed; + // ignoring other reloc types for now + throw new NotSupportedException($"Relocation type {reloc.Type} not yet implemented"); + } + } + } + + Span ReadRelocToDataSpan(SymbolicRelocation reloc, byte[] buffer) + { + Span relocContents = buffer.AsSpan(0, Relocation.GetSize(reloc.Type)); + sectionStream.Position = reloc.Offset; + sectionStream.ReadExactly(relocContents); + return relocContents; + } + + void WriteRelocFromDataSpan(SymbolicRelocation reloc, byte *pData) + { + sectionStream.Position = reloc.Offset; + sectionStream.Write(new Span(pData, Relocation.GetSize(reloc.Type))); + } } const int StackPointerGlobalIndex = 0; @@ -407,9 +498,15 @@ public Stream Stream { get { - Debug.Assert(_dataStream != null); + Debug.Assert(_dataStream != null, $"{this.Name} has null data stream"); return _dataStream; } + + set + { + Debug.Assert(value != null); + _dataStream = value; + } } Stream _dataStream; @@ -458,7 +555,7 @@ public virtual int Emit(Stream outputFileStream) outputFileStream.Write(prependCount); } - + Stream.Position = 0; Stream.CopyTo(outputFileStream); return HeaderSize + (int)(PrependCountSize + Stream.Length); diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index f82c3914a4cf57..8b48b027e9de13 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -25,14 +25,13 @@ using ILCompiler; using ILCompiler.DependencyAnalysis; +using ILCompiler.DependencyAnalysis.Wasm; #if READYTORUN using System.Reflection.Metadata.Ecma335; using ILCompiler.DependencyAnalysis.ReadyToRun; #endif -using ILCompiler.ObjectWriter; - using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; #pragma warning disable IDE0060 diff --git a/src/coreclr/tools/Common/JitInterface/WasmLowering.cs b/src/coreclr/tools/Common/JitInterface/WasmLowering.cs index 961686f5d27c64..2a1e6812429d35 100644 --- a/src/coreclr/tools/Common/JitInterface/WasmLowering.cs +++ b/src/coreclr/tools/Common/JitInterface/WasmLowering.cs @@ -4,8 +4,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using ILCompiler.DependencyAnalysis.Wasm; using Internal.TypeSystem; -using ILCompiler.ObjectWriter; namespace Internal.JitInterface { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index 8d138b97ce980e..fecf02a45a3c46 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -325,6 +325,8 @@ + + diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs index a2a846481e3091..07651cfc6e0c7e 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs @@ -362,7 +362,7 @@ private void CreateNodeCaches() _wasmTypeNodes = new(key => { - return new WasmTypeNode(key.Types); + return new WasmTypeNode(key); }); } @@ -1079,26 +1079,12 @@ public Utf8String GetSymbolAlternateName(ISymbolNode node, out bool isHidden) return default; } - private struct WasmTypeNodeKey : IEquatable - { - public readonly CorInfoWasmType[] Types; - - public WasmTypeNodeKey(CorInfoWasmType[] types) - { - Types = types; - } - - public bool Equals(WasmTypeNodeKey other) => Types.SequenceEqual(other.Types); - public override bool Equals(object obj) => obj is WasmTypeNodeKey wtnk && Equals(wtnk); - public override int GetHashCode() - => Types.Length; // TODO-WASM: Hash all the types - } - - private NodeCache _wasmTypeNodes; + private NodeCache _wasmTypeNodes; public WasmTypeNode WasmTypeNode(CorInfoWasmType[] types) { - return _wasmTypeNodes.GetOrAdd(new WasmTypeNodeKey(types)); + WasmFuncType funcType = WasmFuncType.FromCorInfoSignature(types); + return _wasmTypeNodes.GetOrAdd(funcType); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj index 1cff95dd437131..51f9e89fd11ad8 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj @@ -111,6 +111,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs index 84909203962716..d2d1528b59198c 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -3431,6 +3431,7 @@ private bool notifyMethodInfoUsage(CORINFO_METHOD_STRUCT_* ftn) private CORINFO_WASM_TYPE_SYMBOL_STRUCT_* getWasmTypeSymbol(CorInfoWasmType* types, nuint typesSize) { CorInfoWasmType[] typeArray = new ReadOnlySpan(types, (int)typesSize).ToArray(); + WasmTypeNode typeNode = _compilation.NodeFactory.WasmTypeNode(typeArray); return (CORINFO_WASM_TYPE_SYMBOL_STRUCT_*)ObjectToHandle(typeNode); }