From cedc59f719d8406580670c90d8b34469651927cc Mon Sep 17 00:00:00 2001 From: adamperlin Date: Mon, 9 Feb 2026 16:30:11 -0800 Subject: [PATCH 01/23] Move WasmValueType/ResultType/FuncType definitions out of object writer for common use in crossgen, use WasmFuncType as backing data for WasmTypeNode --- .../Target_Wasm/WasmTypeNode.cs | 29 +- .../Target_Wasm/WasmTypes.cs | 252 ++++++++++++++++++ .../Compiler/ObjectWriter/WasmNative.cs | 155 +---------- .../Compiler/ObjectWriter/WasmObjectWriter.cs | 1 + .../ReadyToRunCodegenNodeFactory.cs | 16 +- .../ILCompiler.ReadyToRun.csproj | 1 + 6 files changed, 279 insertions(+), 175 deletions(-) create mode 100644 src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs 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..f3fd76b46ab16e 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -4,7 +4,9 @@ using System; using System.Linq; using ILCompiler.DependencyAnalysis; +using ILCompiler.ObjectWriter; using Internal.JitInterface; +using Internal.Text; namespace ILCompiler.DependencyAnalysis.Wasm { @@ -14,11 +16,12 @@ namespace ILCompiler.DependencyAnalysis.Wasm // public class WasmTypeNode : ObjectNode, ISymbolNode { - private readonly CorInfoWasmType[] _types; + readonly WasmFuncType _type; + public WasmFuncType Type => _type; - public WasmTypeNode(CorInfoWasmType[] types) + public WasmTypeNode(WasmFuncType type) { - _types = types; + _type = type; } public override bool IsShareable => true; @@ -30,7 +33,7 @@ public WasmTypeNode(CorInfoWasmType[] types) 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( @@ -41,12 +44,11 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) 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 wtn.Type.CompareTo(_type); return result; } @@ -55,16 +57,7 @@ public void AppendMangledName(NameMangler nameMangler, Internal.Text.Utf8StringB 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(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..716fefe1e40a45 --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -0,0 +1,252 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using ILCompiler.DependencyAnalysis; +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", + _ => "unknown", + }; + } + + public static WasmValueType FromCorInfoType(CorInfoWasmType ty) + { + ArgumentOutOfRangeException.ThrowIfGreaterThan(byte.MaxValue, (int)ty); + if (Enum.IsDefined(typeof(WasmValueType), (int)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 == 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 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, string sep = " ") + { + return string.Join(sep, 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]; + for (int i = 1; i < paramTypes.Length; i++) + { + paramTypes[i] = WasmValueTypeExtensions.FromCorInfoType(types[i]); + } + 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)) + return $"(func (param {paramList}))"; + 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(Internal.Text.Utf8StringBuilder sb) + { + _returns.AppendMangledName(sb, isReturn: true); + _params.AppendMangledName(sb); + } + } +} + + diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs index bcca86d4c73918..a87a80c3592f59 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs @@ -5,6 +5,11 @@ using System.Diagnostics; using System.Linq; using System.Collections.Generic; +using Internal.JitInterface; +using System.Runtime.CompilerServices; +using Internal.TypeSystem; +using System.IO; +using ILCompiler.DependencyAnalysis.Wasm; namespace ILCompiler.ObjectWriter { @@ -44,156 +49,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 c3b677b9a9e08f..a84e2b2a1b2321 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 { 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..fda1da18afdf76 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs @@ -20,6 +20,7 @@ using Internal.CorConstants; using Internal.ReadyToRunConstants; using ILCompiler.ReadyToRun.TypeSystem; +using ILCompiler.ObjectWriter; namespace ILCompiler.DependencyAnalysis { @@ -362,7 +363,7 @@ private void CreateNodeCaches() _wasmTypeNodes = new(key => { - return new WasmTypeNode(key.Types); + return new WasmTypeNode(key.Type); }); } @@ -1081,24 +1082,25 @@ public Utf8String GetSymbolAlternateName(ISymbolNode node, out bool isHidden) private struct WasmTypeNodeKey : IEquatable { - public readonly CorInfoWasmType[] Types; + public readonly WasmFuncType Type; - public WasmTypeNodeKey(CorInfoWasmType[] types) + public WasmTypeNodeKey(WasmFuncType type) { - Types = types; + Type = type; } - public bool Equals(WasmTypeNodeKey other) => Types.SequenceEqual(other.Types); + public bool Equals(WasmTypeNodeKey other) => Type.Equals(other.Type); public override bool Equals(object obj) => obj is WasmTypeNodeKey wtnk && Equals(wtnk); public override int GetHashCode() - => Types.Length; // TODO-WASM: Hash all the types + => Type.GetHashCode(); // TODO-WASM: Hash all the types } private NodeCache _wasmTypeNodes; public WasmTypeNode WasmTypeNode(CorInfoWasmType[] types) { - return _wasmTypeNodes.GetOrAdd(new WasmTypeNodeKey(types)); + WasmFuncType funcType = WasmFuncType.FromCorInfoSignature(types); + return _wasmTypeNodes.GetOrAdd(new WasmTypeNodeKey(funcType)); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj index cb7b001082722b..ab785bc19c6e52 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 @@ + From b0530ff3a824b19c9a74b4eab0c0be3436ef240f Mon Sep 17 00:00:00 2001 From: adamperlin Date: Fri, 20 Feb 2026 16:09:05 -0800 Subject: [PATCH 02/23] Use WasmTypeNode for encoding and recording type signatures in WasmObjectWriter and add support for resolving type index relocations --- src/coreclr/jit/emitwasm.cpp | 4 +- .../Compiler/DependencyAnalysis/Relocation.cs | 15 +- .../Target_Wasm/WasmTypeNode.cs | 27 +-- .../Target_Wasm/WasmTypes.cs | 41 +++-- .../Compiler/ObjectWriter/ObjectWriter.cs | 33 ++-- .../Compiler/ObjectWriter/SectionWriter.cs | 15 +- .../Compiler/ObjectWriter/WasmObjectWriter.cs | 164 +++++++++++++----- .../ILCompiler.Compiler.csproj | 2 + .../JitInterface/CorInfoImpl.ReadyToRun.cs | 5 +- 9 files changed, 221 insertions(+), 85 deletions(-) diff --git a/src/coreclr/jit/emitwasm.cpp b/src/coreclr/jit/emitwasm.cpp index d214c03f2755ed..86e2ff07c60cb5 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..87d2ac11eabe5e 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; @@ -681,6 +678,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/Target_Wasm/WasmTypeNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs index f3fd76b46ab16e..6e5ead8113961a 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -14,19 +14,24 @@ 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 { - readonly WasmFuncType _type; + private readonly WasmFuncType _type; public WasmFuncType Type => _type; public WasmTypeNode(WasmFuncType type) { _type = type; + + _data = new byte[_type.EncodeSize()]; + _type.Encode(_data); } public override bool IsShareable => true; - public override int ClassCode => -45678931; + protected internal override int Phase => (int)ObjectNodePhase.Ordered; + + public override int ClassCode => -856789310; public override bool StaticDependenciesAreComputed => true; @@ -35,12 +40,16 @@ public WasmTypeNode(WasmFuncType type) protected override string GetName(NodeFactory factory) => $"Wasm Type Signature: {Type.ToString()}"; + private byte[] _data; + public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) - => new ObjectData( - Array.Empty(), - Array.Empty(), - 1, - Array.Empty()); + { + ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); + builder.AddSymbol(this); + builder.EmitBytes(_data); + + return builder.ToObjectData(); + } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { @@ -55,8 +64,6 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer public void AppendMangledName(NameMangler nameMangler, Internal.Text.Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); - sb.Append("__wasmtype_"u8); - _type.AppendMangledName(sb); } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs index 716fefe1e40a45..b27aacea0a13c7 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -1,3 +1,6 @@ +// 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; @@ -44,8 +47,8 @@ public static string ToTypeString(this WasmValueType valueType) public static WasmValueType FromCorInfoType(CorInfoWasmType ty) { - ArgumentOutOfRangeException.ThrowIfGreaterThan(byte.MaxValue, (int)ty); - if (Enum.IsDefined(typeof(WasmValueType), (int)ty)) + ArgumentOutOfRangeException.ThrowIfGreaterThan((int)ty, byte.MaxValue); + if (Enum.IsDefined(typeof(WasmValueType), (byte)ty)) { return (WasmValueType)ty; } @@ -136,9 +139,9 @@ public void AppendMangledName(Internal.Text.Utf8StringBuilder sb, bool isReturn public static class WasmResultTypeExtensions { - public static string ToTypeListString(this WasmResultType result, string sep = " ") + public static string ToTypeListString(this WasmResultType result) { - return string.Join(sep, result.Types.ToArray().Select(t => t.ToTypeString())); + return string.Join(" ", result.Types.ToArray().Select(t => t.ToTypeString())); } } @@ -157,6 +160,7 @@ public WasmFuncType(WasmResultType paramTypes, WasmResultType returnTypes) public static WasmFuncType FromCorInfoSignature(CorInfoWasmType[] types) { + Console.WriteLine($"types: {types}"); WasmResultType rs; if (types.Length == 0) { @@ -176,9 +180,10 @@ public static WasmFuncType FromCorInfoSignature(CorInfoWasmType[] types) if (types.Length > 1) { WasmValueType[] paramTypes = new WasmValueType[types.Length - 1]; - for (int i = 1; i < paramTypes.Length; i++) + int idx = 0; + foreach (CorInfoWasmType paramType in types.AsSpan().Slice(1)) { - paramTypes[i] = WasmValueTypeExtensions.FromCorInfoType(types[i]); + paramTypes[idx++] = WasmValueTypeExtensions.FromCorInfoType(paramType); } ps = new WasmResultType(paramTypes); } @@ -227,12 +232,22 @@ public override string ToString() string paramList = _params.ToTypeListString(); string returnList = _returns.ToTypeListString(); - if (string.IsNullOrEmpty(returnList)) + 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); @@ -243,10 +258,16 @@ public int CompareTo(WasmFuncType other) public void AppendMangledName(Internal.Text.Utf8StringBuilder sb) { + sb.Append("__wasmtype_"u8); _returns.AppendMangledName(sb, isReturn: true); _params.AppendMangledName(sb); } + + public Internal.Text.Utf8String GetMangledName() + { + Internal.Text.Utf8StringBuilder sb = new(); + AppendMangledName(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 a82fe2cf094886..85978a3fee2c89 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 && @@ -443,12 +438,18 @@ 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/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index a84e2b2a1b2321..759343c7731e57 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -51,39 +51,25 @@ 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; + Utf8String mangledName = new Utf8String(signature.GetMangledName(_nodeFactory.NameMangler)); + _uniqueSignatures[mangledName] = signatureIndex; + _signatureCount++; } - private void MaybeWriteType(MethodDesc desc) + private protected override void RecordMethodDeclaration(ISymbolDefinitionNode symbol, MethodDesc desc) { - WasmFuncType signature = WasmAbiContext.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) @@ -91,7 +77,8 @@ private void WriteSignatureIndexForFunction(MethodDesc desc) SectionWriter writer = GetOrCreateSection(WasmObjectNodeSection.FunctionSection); WasmFuncType signature = WasmAbiContext.GetSignature(desc); - if (!_uniqueSignatures.TryGetValue(signature, out int signatureIndex)) + Utf8String key = signature.GetMangledName(); + if (!_uniqueSignatures.TryGetValue(key, out int signatureIndex)) { throw new InvalidOperationException($"Signature index not found for function: {desc.GetName()}"); } @@ -99,7 +86,6 @@ private void WriteSignatureIndexForFunction(MethodDesc desc) writer.WriteULEB128((ulong)signatureIndex); } - private int _numImports; /// /// Writes the given import entry, including its prefix (module/name/kind) and body (external ref). @@ -270,6 +256,8 @@ private protected override void EmitSectionsAndLayout() { GetOrCreateSection(WasmObjectNodeSection.CombinedDataSection); WriteTableSection(); + + PrependCount(SectionByName(ObjectNodeSection.WasmCodeSection.Name), _methodCount); } private void WriteTableSection() @@ -293,31 +281,109 @@ 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 = Array.Empty(); + private int[] SectionEmitOrder + { + get + { + if (_sectionEmitOrder.Length == 0) + { + _sectionEmitOrder = SectionOrder.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]; + if (_resolvableRelocations.TryGetValue(index, out List relocations) && + section.Type is not WasmSectionType.Data) + { + // TODO-WASM: handle data section relocations (this is dependent on the WebCIL structure being in place) + MemoryStream stream = new MemoryStream((int)section.Stream.Length); + section.Stream.Position = 0; + section.Stream.CopyTo(stream); + ResolveRelocations(stream, relocations); + section.Stream = 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); + } + } + + private unsafe void ResolveRelocations(MemoryStream sectionStream, List relocs) + { + foreach (SymbolicRelocation reloc in relocs) + { + fixed (byte* pData = GetRelocDataSpan(reloc)) + { + switch (reloc.Type) + { + case RelocType.WASM_TYPE_INDEX_LEB: + { + if (_uniqueSignatures.TryGetValue(reloc.SymbolName, out int index)) + { + Relocation.WriteValue(reloc.Type, pData, index); + WriteRelocDataSpan(reloc, pData); + } + else + throw new InvalidDataException($"Type signature symbol definition '{reloc.SymbolName}' not found"); + + break; + } + default: + // TODO-WASM: add other cases as needed; + // ignore other reloc types for now + break; + } + } + } + + Span GetRelocDataSpan(SymbolicRelocation reloc) + { + sectionStream.Position = reloc.Offset; + Span data = new byte[Relocation.GetSize(reloc.Type)]; + sectionStream.ReadExactly(data); + return data; + } + + void WriteRelocDataSpan(SymbolicRelocation reloc, byte* data) + { + sectionStream.Position = reloc.Offset; + sectionStream.Write(new Span(data, Relocation.GetSize(reloc.Type))); + } } const int StackPointerGlobalIndex = 0; @@ -439,7 +505,7 @@ private static WasmValueType LowerType(TypeDesc type) /// /// Gets the Wasm-level signature for a given MethodDesc. /// - /// Parameters for managed Wasm calls have the following layout: + /// i32 (SP), loweredParam0, ..., loweredParamN, i32 (PE entrypoint) /// /// For unmanaged callers only (reverse P/Invoke), the layout is simply the native signature @@ -505,9 +571,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; @@ -556,7 +628,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/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/JitInterface/CorInfoImpl.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs index 42fb1148659daf..5e79bb332d334a 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -3433,7 +3433,10 @@ 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(); + ReadOnlySpan typeSpan = new ReadOnlySpan(types, (int)typesSize).ToArray(); + CorInfoWasmType[] typeArray = new CorInfoWasmType[typesSize]; + typeSpan.CopyTo(typeArray); + WasmTypeNode typeNode = _compilation.NodeFactory.WasmTypeNode(typeArray); return (CORINFO_WASM_TYPE_SYMBOL_STRUCT_*)ObjectToHandle(typeNode); } From 3a679b89ae221ac871a9480e0c77dcfe763c6c2b Mon Sep 17 00:00:00 2001 From: adamperlin Date: Fri, 20 Feb 2026 17:40:20 -0800 Subject: [PATCH 03/23] Replace WasmLowering.GetSignature implementation with patched version, remove unnecessary array copy when creating WasmTypeNode --- .../Compiler/ObjectWriter/WasmObjectWriter.cs | 2 +- .../tools/Common/JitInterface/WasmLowering.cs | 45 +++++++------------ .../JitInterface/CorInfoImpl.ReadyToRun.cs | 4 +- 3 files changed, 17 insertions(+), 34 deletions(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index 64abf89bbcbedf..e12a1ce307aeeb 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -80,7 +80,7 @@ private void WriteSignatureIndexForFunction(MethodDesc desc) Utf8String key = signature.GetMangledName(); 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); diff --git a/src/coreclr/tools/Common/JitInterface/WasmLowering.cs b/src/coreclr/tools/Common/JitInterface/WasmLowering.cs index bae704083d2fbf..2a1e6812429d35 100644 --- a/src/coreclr/tools/Common/JitInterface/WasmLowering.cs +++ b/src/coreclr/tools/Common/JitInterface/WasmLowering.cs @@ -2,9 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Collections.Generic; using System.Diagnostics; -using Internal.TypeSystem; using ILCompiler.DependencyAnalysis.Wasm; +using Internal.TypeSystem; namespace Internal.JitInterface { @@ -148,17 +149,8 @@ public static WasmFuncType GetSignature(MethodDesc method) returnIsVoid = true; } - int parameterCount = signature.Length; - - if (hasReturnBuffer) - { - parameterCount++; // return buffer - } - - if (!method.IsUnmanagedCallersOnly) - { - parameterCount += 2; // sp and pe - } + // Reserve space for potential implicit this, stack pointer parameter, portable entrypoint parameter, and return buffer + ArrayBuilder result = new(signature.Length + 4); if (!signature.IsStatic) { @@ -168,48 +160,41 @@ public static WasmFuncType GetSignature(MethodDesc method) { explicitThis = true; } - else - { - parameterCount += 1; // implicit this - } } - Span wasmParameters = new WasmValueType[parameterCount]; - - int index = 0; - if (method.IsUnmanagedCallersOnly) // reverse P/Invoke { if (hasReturnBuffer) { - wasmParameters[index++] = pointerType; + result.Add(pointerType); } } else // managed call { - wasmParameters[0] = pointerType; // Stack pointer parameter - - // Return buffer is first after this. + result.Add(pointerType); // Stack pointer parameter if (hasThis) { - wasmParameters[index++] = pointerType; + result.Add(pointerType); } if (hasReturnBuffer) { - wasmParameters[index++] = pointerType; + result.Add(pointerType); } - - wasmParameters[wasmParameters.Length - 1] = pointerType; // PE entrypoint parameter } for (int i = explicitThis ? 1 : 0; i < signature.Length; i++) { - wasmParameters[index++] = LowerType(signature[i]); + result.Add(LowerType(signature[i])); + } + + if (!method.IsUnmanagedCallersOnly) + { + result.Add(pointerType); // PE entrypoint parameter } - WasmResultType ps = new(wasmParameters.ToArray()); + WasmResultType ps = new(result.ToArray()); WasmResultType ret = returnIsVoid ? new(Array.Empty()) : new([LowerType(loweredReturnType)]); 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 51519057052111..5b15835aa85964 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -3433,9 +3433,7 @@ private bool notifyMethodInfoUsage(CORINFO_METHOD_STRUCT_* ftn) private CORINFO_WASM_TYPE_SYMBOL_STRUCT_* getWasmTypeSymbol(CorInfoWasmType* types, nuint typesSize) { - ReadOnlySpan typeSpan = new ReadOnlySpan(types, (int)typesSize).ToArray(); - CorInfoWasmType[] typeArray = new CorInfoWasmType[typesSize]; - typeSpan.CopyTo(typeArray); + CorInfoWasmType[] typeArray = new ReadOnlySpan(types, (int)typesSize).ToArray(); WasmTypeNode typeNode = _compilation.NodeFactory.WasmTypeNode(typeArray); return (CORINFO_WASM_TYPE_SYMBOL_STRUCT_*)ObjectToHandle(typeNode); From d95867e834b11481888b0cf40c2eb22835351e13 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Feb 2026 17:56:52 -0800 Subject: [PATCH 04/23] Update src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs index a87a80c3592f59..875fc4df4c7913 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmNative.cs @@ -5,10 +5,6 @@ using System.Diagnostics; using System.Linq; using System.Collections.Generic; -using Internal.JitInterface; -using System.Runtime.CompilerServices; -using Internal.TypeSystem; -using System.IO; using ILCompiler.DependencyAnalysis.Wasm; namespace ILCompiler.ObjectWriter From 7fa18f7cf15b192be8c5844722192e31a5c3f445 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Feb 2026 17:58:02 -0800 Subject: [PATCH 05/23] Update src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 fda1da18afdf76..928ce63121eccb 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs @@ -1092,7 +1092,7 @@ public WasmTypeNodeKey(WasmFuncType type) public bool Equals(WasmTypeNodeKey other) => Type.Equals(other.Type); public override bool Equals(object obj) => obj is WasmTypeNodeKey wtnk && Equals(wtnk); public override int GetHashCode() - => Type.GetHashCode(); // TODO-WASM: Hash all the types + => Type.GetHashCode(); } private NodeCache _wasmTypeNodes; From b4d651e8fc17ffbd4c69ac4862feb53c0bde94f6 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Feb 2026 17:58:18 -0800 Subject: [PATCH 06/23] Update src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index e12a1ce307aeeb..ca0f956164bc77 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -359,7 +359,9 @@ private unsafe void ResolveRelocations(MemoryStream sectionStream, List Date: Fri, 20 Feb 2026 17:58:58 -0800 Subject: [PATCH 07/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs index b27aacea0a13c7..b904febd417829 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -160,7 +160,6 @@ public WasmFuncType(WasmResultType paramTypes, WasmResultType returnTypes) public static WasmFuncType FromCorInfoSignature(CorInfoWasmType[] types) { - Console.WriteLine($"types: {types}"); WasmResultType rs; if (types.Length == 0) { From 4f9f0c86138d96c7338c988626c5ce53b811b119 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Feb 2026 17:59:18 -0800 Subject: [PATCH 08/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs index b904febd417829..baa5a36d8b7baf 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -241,7 +241,7 @@ public override string ToString() } else if (string.IsNullOrEmpty(paramList)) { - return $"(func (result {returnList})"; + return $"(func (result {returnList}))"; } return $"(func (param {paramList}) (result {returnList}))"; From fa953d03bd31e8a907cf41aa5ae06a98111e2212 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Feb 2026 17:59:34 -0800 Subject: [PATCH 09/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs index baa5a36d8b7baf..5590bcbcf99710 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -41,6 +41,7 @@ public static string ToTypeString(this WasmValueType valueType) WasmValueType.I64 => "i64", WasmValueType.F32 => "f32", WasmValueType.F64 => "f64", + WasmValueType.V128 => "v128", _ => "unknown", }; } From 74a4ae54bec5a4d41840c25a5e622e0999c8443c Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Feb 2026 18:05:09 -0800 Subject: [PATCH 10/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 8caf4cc364e9a7..883673a508589f 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -56,7 +56,7 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer // Put shorter signatures earlier in the sort order, on the assumption that they are more likely to be used. int result = _type.SignatureLength.CompareTo(wtn.Type.SignatureLength); if (result == 0) - return wtn.Type.CompareTo(_type); + return _type.CompareTo(wtn.Type); return result; } From 5bb1458f32c9e6a349f03de259a56a3e3cde1405 Mon Sep 17 00:00:00 2001 From: adamperlin Date: Mon, 23 Feb 2026 11:52:26 -0800 Subject: [PATCH 11/23] Resolve additional copilot feedback: dispose of original data stream after lifetime ends, and make lifetime of reloc resolution buffer more explicit (also avoid re-use reloc buffer for each reloc) --- .../Compiler/ObjectWriter/WasmObjectWriter.cs | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index ca0f956164bc77..c315f57810600f 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -18,6 +18,7 @@ using System.Collections.Immutable; using ILCompiler.ObjectWriter.WasmInstructions; using ILCompiler.DependencyAnalysis.Wasm; +using System.Runtime.CompilerServices; namespace ILCompiler.ObjectWriter { @@ -312,15 +313,19 @@ private protected override void EmitObjectFile(Stream 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) { - // TODO-WASM: handle data section relocations (this is dependent on the WebCIL structure being in place) - MemoryStream stream = new MemoryStream((int)section.Stream.Length); - section.Stream.Position = 0; - section.Stream.CopyTo(stream); - ResolveRelocations(stream, relocations); - section.Stream = stream; + 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 + } } section.Emit(outputFileStream); @@ -345,9 +350,11 @@ private protected override void EmitRelocations(int sectionIndex, List relocs) { + byte[] buffer = new byte[8]; foreach (SymbolicRelocation reloc in relocs) { - fixed (byte* pData = GetRelocDataSpan(reloc)) + // We need a pinned raw pointer here for manipulation with Relocation.WriteValue + fixed (byte* pData = ReadRelocToDataSpan(reloc, buffer)) { switch (reloc.Type) { @@ -356,7 +363,7 @@ private unsafe void ResolveRelocations(MemoryStream sectionStream, List GetRelocDataSpan(SymbolicRelocation reloc) + Span ReadRelocToDataSpan(SymbolicRelocation reloc, byte[] buffer) { + Span relocContents = buffer.AsSpan(0, Relocation.GetSize(reloc.Type)); sectionStream.Position = reloc.Offset; - Span data = new byte[Relocation.GetSize(reloc.Type)]; - sectionStream.ReadExactly(data); - return data; + sectionStream.ReadExactly(buffer); + return relocContents; } - void WriteRelocDataSpan(SymbolicRelocation reloc, byte* data) + void WriteRelocFromDataSpan(SymbolicRelocation reloc, byte *pData) { sectionStream.Position = reloc.Offset; - sectionStream.Write(new Span(data, Relocation.GetSize(reloc.Type))); + sectionStream.Write(new Span(pData, Relocation.GetSize(reloc.Type))); } } From 33e9aaa508bf10e5f3b74e740ea25f2340f979ca Mon Sep 17 00:00:00 2001 From: adamperlin Date: Mon, 23 Feb 2026 12:06:36 -0800 Subject: [PATCH 12/23] Add Relocation.MaxSize field, and check against relocation buffer length explicitly; jit-format --- src/coreclr/jit/emitwasm.cpp | 2 +- .../Common/Compiler/DependencyAnalysis/Relocation.cs | 3 +++ .../Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 8 +++++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/coreclr/jit/emitwasm.cpp b/src/coreclr/jit/emitwasm.cpp index 5386f747b4b16f..3b0df4a836fc5d 100644 --- a/src/coreclr/jit/emitwasm.cpp +++ b/src/coreclr/jit/emitwasm.cpp @@ -167,7 +167,7 @@ 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, CORINFO_WASM_TYPE_I32, CORINFO_WASM_TYPE_I32}; + 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, 3); diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs index 87d2ac11eabe5e..fa68031839b1d4 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Relocation.cs @@ -655,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 diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index c315f57810600f..b7107275b8ee9f 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -350,9 +350,15 @@ private protected override void EmitRelocations(int sectionIndex, List relocs) { - byte[] buffer = new byte[8]; + byte[] buffer = new byte[Relocation.MaxSize]; foreach (SymbolicRelocation reloc in relocs) { + int size = Relocation.GetSize(reloc.Type); + if (size >= buffer.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, buffer)) { From 977b80e94642d97b98893c0f6eb5e5dfa30197a4 Mon Sep 17 00:00:00 2001 From: adamperlin Date: Mon, 23 Feb 2026 12:15:40 -0800 Subject: [PATCH 13/23] Fix ReadExactly in relocation resolution --- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index b7107275b8ee9f..16477391851b6a 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -390,7 +390,7 @@ Span ReadRelocToDataSpan(SymbolicRelocation reloc, byte[] buffer) { Span relocContents = buffer.AsSpan(0, Relocation.GetSize(reloc.Type)); sectionStream.Position = reloc.Offset; - sectionStream.ReadExactly(buffer); + sectionStream.ReadExactly(relocContents); return relocContents; } From f42cf5012cf1b6788a83aa9e1b324b5333eaa3f0 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Mon, 23 Feb 2026 12:16:18 -0800 Subject: [PATCH 14/23] Update src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index 16477391851b6a..26b7b005537f0a 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -354,7 +354,7 @@ private unsafe void ResolveRelocations(MemoryStream sectionStream, List= buffer.Length) + if (size > buffer.Length) { throw new InvalidOperationException($"Unsupported relocation size for relocation: {reloc.Type}"); } From 4095ea100b62e42b504469f4742265eeeaa28b6a Mon Sep 17 00:00:00 2001 From: adamperlin Date: Mon, 23 Feb 2026 14:04:57 -0800 Subject: [PATCH 15/23] Address review feedback --- .../Compiler/ObjectWriter/WasmObjectWriter.cs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index 16477391851b6a..23d65209ea5457 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -61,7 +61,9 @@ private protected override void RecordMethodSignature(WasmTypeNode signature) { int signatureIndex = _signatureCount; Utf8String mangledName = new Utf8String(signature.GetMangledName(_nodeFactory.NameMangler)); - _uniqueSignatures[mangledName] = signatureIndex; + // 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++; } @@ -293,12 +295,12 @@ private WasmSection SectionByName(string name) WasmObjectNodeSection.CombinedDataSection.Name, ]; - private int[] _sectionEmitOrder = Array.Empty(); + private int[] _sectionEmitOrder = null; private int[] SectionEmitOrder { get { - if (_sectionEmitOrder.Length == 0) + if (_sectionEmitOrder == null) { _sectionEmitOrder = SectionOrder.Select(name => _sectionNameToIndex[name]).ToArray(); } @@ -348,19 +350,21 @@ private protected override void EmitRelocations(int sectionIndex, List relocs) { - byte[] buffer = new byte[Relocation.MaxSize]; + byte[] relocScratchBuffer = new byte[Relocation.MaxSize]; foreach (SymbolicRelocation reloc in relocs) { int size = Relocation.GetSize(reloc.Type); - if (size >= buffer.Length) + 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, buffer)) + fixed (byte* pData = ReadRelocToDataSpan(reloc, relocScratchBuffer)) { switch (reloc.Type) { From 2aafc74111c8d6b697b79d231ceb7e8906993fbc Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Mon, 23 Feb 2026 15:47:43 -0800 Subject: [PATCH 16/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs | 3 --- 1 file changed, 3 deletions(-) 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 883673a508589f..8654b94863198c 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -2,11 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Linq; using ILCompiler.DependencyAnalysis; using ILCompiler.ObjectWriter; -using Internal.JitInterface; -using Internal.Text; namespace ILCompiler.DependencyAnalysis.Wasm { From 056aab4e084467ad31561f5e808cd8c07f66315a Mon Sep 17 00:00:00 2001 From: adamperlin Date: Mon, 23 Feb 2026 17:01:22 -0800 Subject: [PATCH 17/23] Address additional review feedback --- .../DependencyAnalysis/Target_Wasm/WasmTypeNode.cs | 3 +-- .../Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs | 7 ++++--- .../tools/Common/Compiler/ObjectWriter/ObjectWriter.cs | 4 ++-- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) 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 883673a508589f..88f00c10b09785 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -62,8 +62,7 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer public void AppendMangledName(NameMangler nameMangler, Internal.Text.Utf8StringBuilder sb) { - sb.Append(nameMangler.CompilationUnitPrefix); - _type.AppendMangledName(sb); + _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 index 5590bcbcf99710..3f78462b163ca0 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -256,17 +256,18 @@ public int CompareTo(WasmFuncType other) return _returns.CompareTo(other._returns); } - public void AppendMangledName(Internal.Text.Utf8StringBuilder sb) + 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() + public Internal.Text.Utf8String GetMangledName(NameMangler mangler) { Internal.Text.Utf8StringBuilder sb = new(); - AppendMangledName(sb); + 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 c3d35ae5f1411e..7aedc405623940 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs @@ -505,8 +505,8 @@ public virtual void EmitObject(Stream outputFileStream, IReadOnlyCollection Date: Mon, 23 Feb 2026 17:05:14 -0800 Subject: [PATCH 18/23] Remove unused usings --- .../Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs | 2 -- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 1 - .../Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs | 1 - 3 files changed, 4 deletions(-) diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs index 3f78462b163ca0..103e23b943b71b 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -4,8 +4,6 @@ using System; using System.Diagnostics; using System.Linq; -using System.Runtime.CompilerServices; -using ILCompiler.DependencyAnalysis; using ILCompiler.ObjectWriter; using Internal.JitInterface; diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index a614896be7e8bc..0b7a92f8721bb0 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -18,7 +18,6 @@ using System.Collections.Immutable; using ILCompiler.ObjectWriter.WasmInstructions; using ILCompiler.DependencyAnalysis.Wasm; -using System.Runtime.CompilerServices; namespace ILCompiler.ObjectWriter { 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 928ce63121eccb..2a0fff9f0135b1 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs @@ -20,7 +20,6 @@ using Internal.CorConstants; using Internal.ReadyToRunConstants; using ILCompiler.ReadyToRun.TypeSystem; -using ILCompiler.ObjectWriter; namespace ILCompiler.DependencyAnalysis { From 7478bbf2c833cf271257942dcc784c99d40a5ebf Mon Sep 17 00:00:00 2001 From: adamperlin Date: Wed, 25 Feb 2026 11:59:07 -0800 Subject: [PATCH 19/23] Address review feedback --- .../SortableDependencyNode.cs | 5 +++++ .../Target_Wasm/WasmTypeNode.cs | 21 ++++++++++++------- .../Compiler/ObjectWriter/ObjectWriter.cs | 11 ++-------- .../ReadyToRunCodegenNodeFactory.cs | 21 +++---------------- 4 files changed, 24 insertions(+), 34 deletions(-) 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 433ca1713d3fd3..d98e838b68cc63 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -19,15 +19,13 @@ public class WasmTypeNode : ObjectNode, ISymbolNode, ISymbolDefinitionNode public WasmTypeNode(WasmFuncType type) { _type = type; - _data = new byte[_type.EncodeSize()]; - _type.Encode(_data); } public override bool IsShareable => true; protected internal override int Phase => (int)ObjectNodePhase.Ordered; - public override int ClassCode => -856789310; + public override int ClassCode => (int)ObjectNodeOrder.WasmTypeNode; public override bool StaticDependenciesAreComputed => true; @@ -36,14 +34,23 @@ public WasmTypeNode(WasmFuncType type) protected override string GetName(NodeFactory factory) => $"Wasm Type Signature: {Type.ToString()}"; - private byte[] _data; - public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { + 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); + ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.AddSymbol(this); - builder.EmitBytes(_data); - + builder.EmitBytes(data); return builder.ToObjectData(); } diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs index 7aedc405623940..9f0f397a364a07 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/ObjectWriter.cs @@ -438,7 +438,6 @@ public virtual void EmitObject(Stream outputFileStream, IReadOnlyCollection { - return new WasmTypeNode(key.Type); + return new WasmTypeNode(key); }); } @@ -1079,27 +1079,12 @@ public Utf8String GetSymbolAlternateName(ISymbolNode node, out bool isHidden) return default; } - private struct WasmTypeNodeKey : IEquatable - { - public readonly WasmFuncType Type; - - public WasmTypeNodeKey(WasmFuncType type) - { - Type = type; - } - - public bool Equals(WasmTypeNodeKey other) => Type.Equals(other.Type); - public override bool Equals(object obj) => obj is WasmTypeNodeKey wtnk && Equals(wtnk); - public override int GetHashCode() - => Type.GetHashCode(); - } - - private NodeCache _wasmTypeNodes; + private NodeCache _wasmTypeNodes; public WasmTypeNode WasmTypeNode(CorInfoWasmType[] types) { WasmFuncType funcType = WasmFuncType.FromCorInfoSignature(types); - return _wasmTypeNodes.GetOrAdd(new WasmTypeNodeKey(funcType)); + return _wasmTypeNodes.GetOrAdd(funcType); } } } From 97c37412c1bf6ab5f3cde9a820fb533a3652eb75 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Wed, 25 Feb 2026 14:21:37 -0800 Subject: [PATCH 20/23] Update src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index 0b7a92f8721bb0..ff5b8196e99b25 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -59,7 +59,9 @@ private void EmitWasmHeader(Stream outputFileStream) private protected override void RecordMethodSignature(WasmTypeNode signature) { int signatureIndex = _signatureCount; - Utf8String mangledName = new Utf8String(signature.GetMangledName(_nodeFactory.NameMangler)); + 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); From 6f902e65128ea09959e98f523932bc550ab08bf9 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Thu, 26 Feb 2026 11:46:01 -0800 Subject: [PATCH 21/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Avoids unnecessary copy of `data` when constructing the `ObjectData` in WasmTypeNode.GetData` Co-authored-by: Michal Strehovský --- .../DependencyAnalysis/Target_Wasm/WasmTypeNode.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) 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 d98e838b68cc63..4ef0659e166c1a 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypeNode.cs @@ -48,10 +48,11 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) byte[] data = new byte[_type.EncodeSize()]; _type.Encode(data); - ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); - builder.AddSymbol(this); - builder.EmitBytes(data); - return builder.ToObjectData(); + return new ObjectData( + data: data, + relocs: Array.Empty(), + alignment: 1, + definedSymbols: new ISymbolDefinitionNode[] { this }); } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) From 40814725ddcaf9ed8d2eb893f33d86ceffd57d07 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Thu, 26 Feb 2026 12:58:30 -0800 Subject: [PATCH 22/23] Update src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs index 103e23b943b71b..da37129e4b501e 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_Wasm/WasmTypes.cs @@ -82,7 +82,7 @@ public override bool Equals(object? obj) public override int GetHashCode() { - if (_types == null || _types.Length == 0) + if (_types.Length == 0) return 0; int code = _types[0].GetHashCode(); From 9f2448df5c3bc02a3696aaf25d0a99e3ed06237a Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Thu, 26 Feb 2026 13:01:11 -0800 Subject: [PATCH 23/23] Update src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs index ff5b8196e99b25..61ca39fac17022 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmObjectWriter.cs @@ -303,7 +303,10 @@ private int[] SectionEmitOrder { if (_sectionEmitOrder == null) { - _sectionEmitOrder = SectionOrder.Select(name => _sectionNameToIndex[name]).ToArray(); + _sectionEmitOrder = SectionOrder + .Where(name => _sectionNameToIndex.ContainsKey(name)) + .Select(name => _sectionNameToIndex[name]) + .ToArray(); } return _sectionEmitOrder;