From b42188a8143f3c7971a7ab1c735e31d8349e7991 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Sun, 2 Jan 2022 03:33:38 +0900 Subject: [PATCH 01/97] Update issue suppressions (#63248) The test got renamed in #63178. Should fix the Mono AOT CI failures seen in #63232. --- src/tests/issues.targets | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/tests/issues.targets b/src/tests/issues.targets index 5097f3e87e5dda..22eb44b80f59f1 100644 --- a/src/tests/issues.targets +++ b/src/tests/issues.targets @@ -2145,7 +2145,7 @@ needs triage - + needs triage @@ -2154,7 +2154,7 @@ needs triage - + needs triage @@ -2512,10 +2512,10 @@ needs triage - + needs triage - + needs triage @@ -2604,10 +2604,10 @@ https://github.com/dotnet/runtime/issues/57361 - + https://github.com/dotnet/runtime/issues/57369 - + https://github.com/dotnet/runtime/issues/57369 From e571c3b1348febce60153004760504b9c330f98c Mon Sep 17 00:00:00 2001 From: Zoltan Varga Date: Sun, 2 Jan 2022 13:26:27 -0500 Subject: [PATCH 02/97] [mono][wasm] Remove unused targets from wasm/Makefile. (#63263) The real build now happens in runtime/CMakeLists.txt, the Makefile contains only helper targets now. --- src/mono/wasm/Makefile | 82 ++++-------------------------------------- 1 file changed, 7 insertions(+), 75 deletions(-) diff --git a/src/mono/wasm/Makefile b/src/mono/wasm/Makefile index d171b9395a716a..6dabb5c5d28a1b 100644 --- a/src/mono/wasm/Makefile +++ b/src/mono/wasm/Makefile @@ -12,24 +12,15 @@ JSVU=$(HOME)/.jsvu CHROMEDRIVER?=$(HOME)/.chromedriver GECKODRIVER?=$(HOME)/.geckodriver -# -# These variables are set by wasm.proj -# EMSDK_PATH?=$(TOP)/src/mono/wasm/emsdk CONFIG?=Release BINDIR?=$(TOP)/artifacts/bin OBJDIR?=$(TOP)/artifacts/obj -PINVOKE_TABLE?=$(TOP)/artifacts/obj/wasm/pinvoke-table.h -MONO_BIN_DIR?=$(BINDIR)/mono/Browser.wasm.$(CONFIG) -NATIVE_BIN_DIR?=$(BINDIR)/native/net7.0-Browser-$(CONFIG)-wasm -ICU_LIBDIR?= -SYSTEM_NATIVE_LIBDIR?=$(TOP)/src/native/libs/System.Native _MSBUILD_WASM_BUILD_ARGS=/p:TargetOS=Browser /p:TargetArchitecture=wasm /p:Configuration=$(CONFIG) XHARNESS_BROWSER?=chrome -EMCC_DEFAULT_RSP=$(NATIVE_BIN_DIR)/src/emcc-default.rsp HELIX_TARGET_QUEUE?=Ubuntu.1804.Amd64.Open -all: build-native icu-files source-files header-files +all: build-all # # EMSCRIPTEN SETUP @@ -53,78 +44,16 @@ provision-wasm: .stamp-wasm-install-and-select-$(EMSCRIPTEN_VERSION) @echo "----------------------------------------------------------" @echo "Installed emsdk into EMSDK_PATH=$(TOP)/src/mono/wasm/emsdk" -# FIXME: When https://github.com/dotnet/runtime/issues/54565 is fixed, and the WasmApp targets are updated to use mono runtime components, remove this -MONO_COMPONENT_LIBS= \ - $(MONO_BIN_DIR)/libmono-component-hot_reload-static.a \ - $(MONO_BIN_DIR)/libmono-component-debugger-static.a \ - $(MONO_BIN_DIR)/libmono-component-diagnostics_tracing-stub-static.a - MONO_OBJ_DIR=$(OBJDIR)/mono/Browser.wasm.$(CONFIG) -MONO_INCLUDE_DIR=$(MONO_BIN_DIR)/include/mono-2.0 BUILDS_OBJ_DIR=$(MONO_OBJ_DIR)/wasm -# libmonosgen-2.0 is in MONO_LIBS twice because the components and the runtime are depend on each other -MONO_LIBS = \ - $(MONO_BIN_DIR)/libmono-ee-interp.a \ - $(MONO_BIN_DIR)/libmonosgen-2.0.a \ - $(MONO_COMPONENT_LIBS) \ - $(MONO_BIN_DIR)/libmonosgen-2.0.a \ - $(MONO_BIN_DIR)/libmono-ilgen.a \ - $(MONO_BIN_DIR)/libmono-icall-table.a \ - $(MONO_BIN_DIR)/libmono-profiler-aot.a \ - ${NATIVE_BIN_DIR}/libSystem.Native.a \ - ${NATIVE_BIN_DIR}/libSystem.IO.Compression.Native.a \ - $(ICU_LIBDIR)/libicuuc.a \ - $(ICU_LIBDIR)/libicui18n.a - -ifeq ($(NOSTRIP),) -STRIP_CMD=&& $(EMSDK_PATH)/upstream/bin/wasm-opt --strip-dwarf $(NATIVE_BIN_DIR)/dotnet.wasm -o $(NATIVE_BIN_DIR)/dotnet.wasm -else -STRIP_CMD= -endif - -# -# Wasm builds -# - -$(NATIVE_BIN_DIR): - mkdir -p $$@ - -$(NATIVE_BIN_DIR)/src: - mkdir -p $$@ - -$(NATIVE_BIN_DIR)/include/wasm: - mkdir -p $$@ - -$(BUILDS_OBJ_DIR): - mkdir -p $$@ - -$(NATIVE_BIN_DIR)/dotnet.js: runtime/driver.c runtime/pinvoke.c runtime/pinvoke.h runtime/corebindings.c $(NATIVE_BIN_DIR)/src/cjs/runtime.cjs.iffe.js runtime/cjs/dotnet.cjs.lib.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.lib.js $(MONO_LIBS) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) - $(DOTNET) build $(CURDIR)/wasm.proj $(_MSBUILD_WASM_BUILD_ARGS) /t:BuildWasmRuntimes $(MSBUILD_ARGS) - -$(EMCC_DEFAULT_RSP): $(CURDIR)/wasm.proj | $(NATIVE_BIN_DIR)/src Makefile - $(DOTNET) build $(CURDIR)/wasm.proj /p:Configuration=$(CONFIG) /t:GenerateEmccPropsAndRspFiles - -$(NATIVE_BIN_DIR)/src/emcc-props.json: $(EMSDK_PATH)/upstream/.emsdk_version | $(NATIVE_BIN_DIR)/src - $(DOTNET) build $(CURDIR)/wasm.proj /p:Configuration=$(CONFIG) /t:GenerateEmccPropsAndRspFiles - -build-native: $(NATIVE_BIN_DIR)/dotnet.js $(NATIVE_BIN_DIR)/src/emcc-default.rsp $(NATIVE_BIN_DIR)/src/emcc-props.json clean-emsdk: $(RM) -rf $(EMSDK_LOCAL_PATH) -clean: - $(RM) -rf $(BUILDS_OBJ_DIR) - -icu-files: $(wildcard $(ICU_LIBDIR)/*.dat) $(ICU_LIBDIR)/libicuuc.a $(ICU_LIBDIR)/libicui18n.a | $(NATIVE_BIN_DIR) - cp $^ $(NATIVE_BIN_DIR) - -source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/cjs/dotnet.cjs.lib.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.lib.js | $(NATIVE_BIN_DIR)/src - cp $^ $(NATIVE_BIN_DIR)/src - -header-files: runtime/pinvoke.h | $(NATIVE_BIN_DIR)/include/wasm - cp $^ $(NATIVE_BIN_DIR)/include/wasm - +# # Helper targets +# + .PHONY: runtime .PHONY: build @@ -153,6 +82,9 @@ app-builder: build-tasks: $(DOTNET) build $(TOP)/src/tasks/WasmBuildTasks $(MSBUILD_ARGS) +clean: + $(RM) -rf $(BUILDS_OBJ_DIR) + run-tests-v8-%: EMSDK_PATH=$(EMSDK_PATH) PATH="$(JSVU):$(PATH)" $(DOTNET) build $(TOP)/src/libraries/$*/tests/ /t:Test $(_MSBUILD_WASM_BUILD_ARGS) /p:JSEngine=V8 $(MSBUILD_ARGS) run-tests-sm-%: From c8f3b36d6d5da74333c6755ccd5687127bcd9905 Mon Sep 17 00:00:00 2001 From: Dan Moseley Date: Sun, 2 Jan 2022 21:56:39 -0700 Subject: [PATCH 03/97] Fix strings typo (#63269) --- .../System.Private.CoreLib/src/Resources/Strings.resx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx index 57a9c28c693960..4f48d0181a4c79 100644 --- a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx @@ -1824,7 +1824,7 @@ Pointer startIndex and length do not refer to a valid string. - Period must be less than 2^32-2. + Period must be less than 2^32-1. The position may not be greater or equal to the capacity of the accessor. @@ -1854,7 +1854,7 @@ Stream length must be non-negative and less than 2^31 - 1 - origin. - Time-out interval must be less than 2^32-2. + Time-out interval must be less than 2^32-1. The length of the buffer must be less than the maximum UIntPtr value for your platform. From 699b0ae0593e524e1f231e60bf03dd735ecb5d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Mon, 3 Jan 2022 15:03:03 +0900 Subject: [PATCH 04/97] Implement DiagnosticName in NativeAOT code (#63271) When `DiagnosticName` was introduced into the type system, I didn't want to deal with it and compiled it out of the NativeAOT version of the type system. In order to have a single ILCompiler.TypeSystem assembly that can be used with both crossgen2 and ILC, this needs to be implemented. I've also reduced the number of diffs between ILCompiler.TypeSystem.csproj and ILCompiler.TypeSystem.ReadyToRun.csproj. --- .../Common/GenericParameterDesc.Diagnostic.cs | 8 +- ...AssemblyGetExecutingAssemblyMethodThunk.cs | 8 ++ .../IL/Stubs/CalliMarshallingMethodThunk.cs | 8 ++ .../Stubs/DelegateMarshallingMethodThunk.cs | 8 ++ .../TypeSystem/IL/Stubs/DelegateThunks.cs | 16 +++ .../IL/Stubs/DynamicInvokeMethodThunk.cs | 8 ++ .../Common/TypeSystem/IL/Stubs/EnumThunks.cs | 16 +++ .../IL/Stubs/ForwardDelegateCreationThunk.cs | 8 ++ .../Stubs/MethodBaseGetCurrentMethodThunk.cs | 8 ++ .../IL/Stubs/StructMarshallingThunk.cs | 8 ++ .../IL/Stubs/TypeGetTypeMethodThunk.cs | 8 ++ .../ValueTypeGetFieldHelperMethodOverride.cs | 8 ++ .../IL/TypeSystemContext.GeneratedAssembly.cs | 16 +++ .../TypeSystem/Interop/IL/InlineArrayType.cs | 24 ++++ .../TypeSystem/Interop/IL/NativeStructType.cs | 16 +++ .../Interop/IL/PInvokeDelegateWrapper.cs | 16 +++ .../IL/PInvokeDelegateWrapperConstructor.cs | 8 ++ .../CompilerTypeSystemContext.BoxedTypes.cs | 20 +++- ...ompilerTypeSystemContext.IntefaceThunks.cs | 9 ++ .../AppContextInitializerMethod.cs | 8 ++ .../StartupCode/NativeLibraryStartupMethod.cs | 8 ++ .../StartupCode/StartupCodeMainMethod.cs | 16 +++ .../ILCompiler.TypeSystem.csproj | 107 ++++++++++++------ 23 files changed, 323 insertions(+), 37 deletions(-) diff --git a/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs index 8af9193966818b..7e8df4304dfd5c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs @@ -11,6 +11,12 @@ public abstract partial class GenericParameterDesc /// /// Gets the name of the generic parameter as defined in the metadata. This must not throw /// - public abstract string DiagnosticName { get; } + public virtual string DiagnosticName + { + get + { + return string.Concat("T", Index.ToStringInvariant()); + } + } } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs index ab0e8eee978581..ce1d69716a7b97 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs @@ -44,6 +44,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return $"GetExecutingAssembly_{ExecutingAssembly.GetName().Name}"; + } + } + public override TypeDesc OwningType { get; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs index 73b8645e855947..bdbd7b67998f48 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs @@ -79,6 +79,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "CalliMarshallingMethodThunk"; + } + } + public override PInvokeMetadata GetPInvokeMethodMetadata() { // Return PInvokeAttributes.PreserveSig to circumvent marshalling required checks diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs index a81809c4193030..276f7dc4a42fcb 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs @@ -237,6 +237,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return NamePrefix + "__" + DelegateType.DiagnosticName; + } + } + public override MethodIL EmitIL() { return PInvokeILEmitter.EmitIL(this, default(PInvokeILEmitterConfiguration), _interopStateManager); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs index 5725a062a086e2..2d76523052ecd0 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs @@ -90,6 +90,14 @@ protected FieldDesc FunctionPointerField return SystemDelegateType.GetKnownField("m_functionPointer"); } } + + public sealed override string DiagnosticName + { + get + { + return Name; + } + } } /// @@ -779,5 +787,13 @@ public override string Name return "GetThunk"; } } + + public override string DiagnosticName + { + get + { + return "GetThunk"; + } + } } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs index 90ce50f8425ca4..de076f3b8cbff8 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs @@ -308,6 +308,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return Name; + } + } + public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs index a44161e6fa354b..dc8fba49876afc 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs @@ -64,6 +64,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "GetHashCode"; + } + } + public override bool IsVirtual { get @@ -147,6 +155,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "Equals"; + } + } + public override bool IsVirtual { get diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs index e93d385a0ffcf6..fd1e907f844031 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs @@ -75,6 +75,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "ForwardDelegateCreationStub__" + DelegateType.DiagnosticName; + } + } + /// /// This thunk creates a delegate from a native function pointer /// by first creating a PInvokeDelegateWrapper from the function pointer diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs index d75feac0fe9bdc..82a729dc3eb2db 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs @@ -44,6 +44,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return Method.DiagnosticName; + } + } + public override TypeDesc OwningType { get diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs index cf346c06852173..2751290f0c91ef 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs @@ -126,6 +126,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return NamePrefix + "__" + ManagedType.DiagnosticName; + } + } + private Marshaller[] InitializeMarshallers() { Debug.Assert(_interopStateManager != null); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs index be09098c5dab6a..b1a32586bef3f5 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs @@ -41,6 +41,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return $"{_helperMethod.DiagnosticName}_{Signature.Length}_{DefaultAssemblyName}"; + } + } + public override TypeDesc OwningType { get; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs index a324de7bb222be..a5cfa2db42e5ec 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs @@ -149,5 +149,13 @@ public override string Name return "__GetFieldHelper"; } } + + public override string DiagnosticName + { + get + { + return "__GetFieldHelper"; + } + } } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs b/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs index a01beba3cea869..1a289f651f107e 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs @@ -89,6 +89,14 @@ public override string Name get; } + public override string DiagnosticName + { + get + { + return Name; + } + } + public override string Namespace { get @@ -97,6 +105,14 @@ public override string Namespace } } + public override string DiagnosticNamespace + { + get + { + return "Internal.CompilerGenerated"; + } + } + public override int GetHashCode() { if (_hashcode != 0) diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs index 6462c6ee2c59c7..4cf06e8b6bfb4f 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs @@ -35,6 +35,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "_InlineArray__" + ElementType.DiagnosticName + "__" + Length; + } + } + public override string Namespace { get @@ -43,6 +51,14 @@ public override string Namespace } } + public override string DiagnosticNamespace + { + get + { + return Namespace; + } + } + public override Instantiation Instantiation { get @@ -320,6 +336,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return Name; + } + } + public override MethodSignature Signature { get diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs index d20d6fafcc0dc9..bf5e0c6ef3d7ba 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs @@ -28,6 +28,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "__NativeType__" + ManagedStructType.DiagnosticName; + } + } + public override string Namespace { get @@ -36,6 +44,14 @@ public override string Namespace } } + public override string DiagnosticNamespace + { + get + { + return "Internal.CompilerGenerated"; + } + } + public override PInvokeStringFormat PInvokeStringFormat { get diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs index 78cbe796e397f1..dcc2fbff41c065 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs @@ -35,6 +35,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "PInvokeDelegateWrapper__" + DelegateType.DiagnosticName; + } + } + public override string Namespace { get @@ -43,6 +51,14 @@ public override string Namespace } } + public override string DiagnosticNamespace + { + get + { + return "Internal.CompilerGenerated"; + } + } + public override bool IsExplicitLayout { get diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs index 6917c71f656e42..2e138f6098c7ff 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs @@ -33,6 +33,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return ".ctor"; + } + } + private MethodSignature _signature; public override MethodSignature Signature { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs index 8be62c3d9950db..39a6bf3490beb0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs @@ -259,7 +259,8 @@ private partial class BoxedValueType : MetadataType, INonEmittableType public override string Name => "Boxed_" + ValueTypeRepresented.Name; public override string Namespace => ValueTypeRepresented.Namespace; - + public override string DiagnosticName => "Boxed_" + ValueTypeRepresented.DiagnosticName; + public override string DiagnosticNamespace => ValueTypeRepresented.DiagnosticNamespace; public override Instantiation Instantiation => ValueTypeRepresented.Instantiation; public override PInvokeStringFormat PInvokeStringFormat => PInvokeStringFormat.AutoClass; public override bool IsExplicitLayout => false; @@ -411,6 +412,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return _targetMethod.DiagnosticName + "_Unbox"; + } + } + public override MethodIL EmitIL() { if (_owningType.ValueTypeRepresented.IsByRefLike) @@ -487,6 +496,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return _targetMethod.DiagnosticName + "_Unbox"; + } + } + public override MethodIL EmitIL() { if (_owningType.ValueTypeRepresented.IsByRefLike) @@ -574,6 +591,7 @@ public ValueTypeInstanceMethodWithHiddenParameter(MethodDesc methodRepresented) public override TypeDesc OwningType => _methodRepresented.OwningType; public override string Name => _methodRepresented.Name; + public override string DiagnosticName => _methodRepresented.DiagnosticName; public override MethodSignature Signature { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs index ad558ae43bf51b..06c13c51e6d8d1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs @@ -194,6 +194,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return _targetMethod.DiagnosticName; + } + } + public MethodDesc BaseMethod => _targetMethod; public string Prefix => $"__InstantiatingStub_{_interfaceIndex}_"; @@ -274,6 +282,7 @@ public DefaultInterfaceMethodImplementationWithHiddenParameter(MethodDesc method public override TypeDesc OwningType => _owningType; public override string Name => _methodRepresented.Name; + public override string DiagnosticName => _methodRepresented.DiagnosticName; public override MethodSignature Signature { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs index d4b53340b55301..ed40a5f6fcc75c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs @@ -54,6 +54,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "SetAppContextSwitches"; + } + } + public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs index 7138804bb23138..4240af2427d154 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs @@ -48,6 +48,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "NativeLibraryStartup"; + } + } + public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs index b18b9435491343..2c91f888c4dc05 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs @@ -53,6 +53,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "StartupCodeMain"; + } + } + public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); @@ -229,6 +237,14 @@ public override string Name } } + public override string DiagnosticName + { + get + { + return "MainMethodWrapper"; + } + } + public override MethodSignature Signature { get diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj index 4aa53fd19c5e11..a638f7310d0523 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj @@ -9,6 +9,8 @@ x64;x86 AnyCPU false + true + $(DefineConstants);DISABLE_UNMANAGED_PDB_SYMBOLS 6.0.0-preview-20211019.1 - 7.0.100-1.21620.1 + 7.0.100-1.21628.1 $(MicrosoftNETILLinkTasksVersion) 7.0.0-alpha.1.21620.1 From c7ec82ae6e1e8a2fc929df77965cfe659ac9c036 Mon Sep 17 00:00:00 2001 From: Zoltan Varga Date: Mon, 3 Jan 2022 06:44:48 -0500 Subject: [PATCH 08/97] [mono][wasm] Allow methods with finally clauses to be AOTed. (#63065) * [mono][wasm] Allow methods with finally clauses to be AOTed. This is implemented by running the finally clause with the interpreter. Methods with clauses have additional code generated, which: * Saves the IL state (pc+arguments+locals) into a MonoMethodILState structure. * Pushes an LMF frame on the LMF stack of type MONO_LMFEXT_IL_STATE. The LMF frame points to the il state. During EH, if such an LMF frame is found, and the IL pc in the il state points inside a clause, then an interpreted version of the method is created, and the finally clause is ran using the interpreter using the il state as the starting state. * Disable a few test suites which now cause emscripten to OOM when building with AOT. --- src/libraries/tests.proj | 5 + src/mono/mono/metadata/object-offsets.h | 7 + src/mono/mono/mini/ee.h | 4 +- src/mono/mono/mini/exceptions.cs | 70 +++++++ src/mono/mono/mini/interp-stubs.c | 13 ++ src/mono/mono/mini/interp/interp.c | 182 ++++++++++++++++++ src/mono/mono/mini/method-to-ir.c | 77 +++++++- src/mono/mono/mini/mini-exceptions.c | 81 ++++++-- src/mono/mono/mini/mini-llvm.c | 90 ++++++++- src/mono/mono/mini/mini-ops.h | 3 + src/mono/mono/mini/mini-runtime.h | 10 + src/mono/mono/mini/mini.c | 34 +++- src/mono/mono/mini/mini.h | 9 +- .../mono/tools/offsets-tool/offsets-tool.py | 2 + src/mono/mono/utils/mono-stack-unwinding.h | 7 +- 15 files changed, 558 insertions(+), 36 deletions(-) diff --git a/src/libraries/tests.proj b/src/libraries/tests.proj index 326cbde18d7d70..3bb6154ad93d0e 100644 --- a/src/libraries/tests.proj +++ b/src/libraries/tests.proj @@ -17,6 +17,11 @@ + + + + diff --git a/src/mono/mono/metadata/object-offsets.h b/src/mono/mono/metadata/object-offsets.h index dd19b9c395cc31..3c4e158b8deefb 100644 --- a/src/mono/mono/metadata/object-offsets.h +++ b/src/mono/mono/metadata/object-offsets.h @@ -149,11 +149,18 @@ DECL_OFFSET(SgenThreadInfo, tlab_temp_end) #ifndef DISABLE_JIT_OFFSETS DECL_SIZE(MonoMethodRuntimeGenericContext) DECL_SIZE(MonoLMF) +DECL_SIZE(MonoLMFExt) DECL_SIZE(MonoTypedRef) DECL_SIZE(CallContext) DECL_SIZE(MonoContext) DECL_OFFSET(MonoLMF, previous_lmf) +DECL_OFFSET(MonoLMFExt, kind) +DECL_OFFSET(MonoLMFExt, il_state) + +DECL_OFFSET(MonoMethodILState, method) +DECL_OFFSET(MonoMethodILState, il_offset) +DECL_OFFSET(MonoMethodILState, data) DECL_OFFSET(MonoMethodRuntimeGenericContext, class_vtable) diff --git a/src/mono/mono/mini/ee.h b/src/mono/mono/mini/ee.h index 33a06a3820b07e..8eb73fd459fc07 100644 --- a/src/mono/mono/mini/ee.h +++ b/src/mono/mono/mini/ee.h @@ -14,7 +14,7 @@ #ifndef __MONO_EE_H__ #define __MONO_EE_H__ -#define MONO_EE_API_VERSION 0x14 +#define MONO_EE_API_VERSION 0x15 typedef struct _MonoInterpStackIter MonoInterpStackIter; @@ -38,6 +38,7 @@ typedef gpointer MonoInterpFrameHandle; MONO_EE_CALLBACK (void, get_resume_state, (const MonoJitTlsData *jit_tls, gboolean *has_resume_state, MonoInterpFrameHandle *interp_frame, gpointer *handler_ip)) \ MONO_EE_CALLBACK (gboolean, run_finally, (StackFrameInfo *frame, int clause_index, gpointer handler_ip, gpointer handler_ip_end)) \ MONO_EE_CALLBACK (gboolean, run_filter, (StackFrameInfo *frame, MonoException *ex, int clause_index, gpointer handler_ip, gpointer handler_ip_end)) \ + MONO_EE_CALLBACK (gboolean, run_finally_with_il_state, (gpointer il_state, int clause_index, gpointer handler_ip, gpointer handler_ip_end)) \ MONO_EE_CALLBACK (void, frame_iter_init, (MonoInterpStackIter *iter, gpointer interp_exit_data)) \ MONO_EE_CALLBACK (gboolean, frame_iter_next, (MonoInterpStackIter *iter, StackFrameInfo *frame)) \ MONO_EE_CALLBACK (MonoJitInfo*, find_jit_info, (MonoMethod *method)) \ @@ -63,6 +64,7 @@ typedef gpointer MonoInterpFrameHandle; MONO_EE_CALLBACK (gboolean, sufficient_stack, (gsize size)) \ MONO_EE_CALLBACK (void, entry_llvmonly, (gpointer res, gpointer *args, gpointer imethod)) \ MONO_EE_CALLBACK (gpointer, get_interp_method, (MonoMethod *method, MonoError *error)) \ + MONO_EE_CALLBACK (MonoJitInfo*, compile_interp_method, (MonoMethod *method, MonoError *error)) \ typedef struct _MonoEECallbacks { diff --git a/src/mono/mono/mini/exceptions.cs b/src/mono/mono/mini/exceptions.cs index fe5bc32817096b..79903d21bcf6c2 100644 --- a/src/mono/mono/mini/exceptions.cs +++ b/src/mono/mono/mini/exceptions.cs @@ -3029,6 +3029,76 @@ public static int test_0_unsigned_ct_div () { return 0; } + + struct AStruct { + public int i1, i2, i3, i4; + } + + // Running finally clauses with the interpreter in llvmonly-interp mode + public static int test_0_finally_deopt () { + int arg_i = 2; + var o = new ExceptionTests (); + try { + o.finally_deopt (1, 0, ref arg_i, new AStruct () { i1 = 1, i2 = 2, i3 = 3, i4 = 4 }); + } catch (Exception) { + } + return finally_deopt_res; + } + + static int dummy_static = 5; + + [MethodImplAttribute (MethodImplOptions.NoInlining)] + static void throw_inner () { + // Avoid warnings/errors + if (dummy_static == 5) + throw new Exception (); + // Run with the interpreter + try { + throw new Exception (); + } catch (Exception) { + } + } + + static int finally_deopt_res; + + void finally_deopt (int arg_i, int unused_arg_i, ref int ref_arg_i, AStruct s) { + int i = 3; + + try { + try { + i = 5; + throw_inner (); + } finally { + // Check that arguments/locals are copied correctly to the interpreter + object o = this; + if (!(o is ExceptionTests)) + finally_deopt_res = 1; + if (arg_i != 1) + finally_deopt_res = 2; + arg_i ++; + if (i != 5) + finally_deopt_res = 3; + i ++; + if (ref_arg_i != 2) + finally_deopt_res = 4; + ref_arg_i ++; + if (s.i1 != 1 || s.i2 != 2) + finally_deopt_res = 5; + s.i1 ++; + s.i2 ++; + } + } finally { + // Check that arguments/locals were copied back after the first call to the interpreter + if (arg_i != 2) + finally_deopt_res = 10; + if (ref_arg_i != 3) + finally_deopt_res = 11; + if (i != 6) + finally_deopt_res = 12; + if (s.i1 != 2 || s.i2 != 3) + finally_deopt_res = 13; + } + } } #if !__MOBILE__ diff --git a/src/mono/mono/mini/interp-stubs.c b/src/mono/mono/mini/interp-stubs.c index 5d4e3b5c14ed61..63ef7de7a69325 100644 --- a/src/mono/mono/mini/interp-stubs.c +++ b/src/mono/mono/mini/interp-stubs.c @@ -114,6 +114,12 @@ stub_run_filter (StackFrameInfo *frame, MonoException *ex, int clause_index, gpo return FALSE; } +static gboolean +stub_run_finally_with_il_state (gpointer il_state, int clause_index, gpointer handler_ip, gpointer handler_ip_end) +{ + g_assert_not_reached (); +} + static void stub_frame_iter_init (MonoInterpStackIter *iter, gpointer interp_exit_data) { @@ -239,6 +245,13 @@ stub_get_interp_method (MonoMethod *method, MonoError *error) return NULL; } +static MonoJitInfo* +stub_compile_interp_method (MonoMethod *method, MonoError *error) +{ + g_assert_not_reached (); + return NULL; +} + #undef MONO_EE_CALLBACK #define MONO_EE_CALLBACK(ret, name, sig) stub_ ## name, diff --git a/src/mono/mono/mini/interp/interp.c b/src/mono/mono/mini/interp/interp.c index 040e1169c77f43..2cd43b6fffd6a9 100644 --- a/src/mono/mono/mini/interp/interp.c +++ b/src/mono/mono/mini/interp/interp.c @@ -756,6 +756,70 @@ get_virtual_method_fast (InterpMethod *imethod, MonoVTable *vtable, int offset) } } +// Returns the size it uses on the interpreter stack +static int +stackval_size (MonoType *type, gboolean pinvoke) +{ + type = mini_native_type_replace_type (type); + if (m_type_is_byref (type)) + return MINT_STACK_SLOT_SIZE; + switch (type->type) { + case MONO_TYPE_VOID: + return 0; + case MONO_TYPE_I1: + case MONO_TYPE_U1: + case MONO_TYPE_BOOLEAN: + case MONO_TYPE_I2: + case MONO_TYPE_U2: + case MONO_TYPE_CHAR: + case MONO_TYPE_I4: + case MONO_TYPE_U: + case MONO_TYPE_I: + case MONO_TYPE_PTR: + case MONO_TYPE_FNPTR: + case MONO_TYPE_U4: + return MINT_STACK_SLOT_SIZE; + case MONO_TYPE_R4: + return MINT_STACK_SLOT_SIZE; + case MONO_TYPE_I8: + case MONO_TYPE_U8: + return MINT_STACK_SLOT_SIZE; + case MONO_TYPE_R8: + return MINT_STACK_SLOT_SIZE; + case MONO_TYPE_STRING: + case MONO_TYPE_SZARRAY: + case MONO_TYPE_CLASS: + case MONO_TYPE_OBJECT: + case MONO_TYPE_ARRAY: + return MINT_STACK_SLOT_SIZE; + case MONO_TYPE_VALUETYPE: + if (m_class_is_enumtype (type->data.klass)) { + return stackval_size (mono_class_enum_basetype_internal (type->data.klass), pinvoke); + } else { + int size; + if (pinvoke) + size = mono_class_native_size (type->data.klass, NULL); + else + size = mono_class_value_size (type->data.klass, NULL); + return ALIGN_TO (size, MINT_STACK_SLOT_SIZE); + } + case MONO_TYPE_GENERICINST: { + if (mono_type_generic_inst_is_valuetype (type)) { + MonoClass *klass = mono_class_from_mono_type_internal (type); + int size; + if (pinvoke) + size = mono_class_native_size (klass, NULL); + else + size = mono_class_value_size (klass, NULL); + return ALIGN_TO (size, MINT_STACK_SLOT_SIZE); + } + return stackval_size (m_class_get_byval_arg (type->data.generic_class->container_class), pinvoke); + } + default: + g_error ("got type 0x%02x", type->type); + } +} + // Returns the size it uses on the interpreter stack static int stackval_from_data (MonoType *type, stackval *result, const void *data, gboolean pinvoke) @@ -2859,6 +2923,18 @@ interp_get_interp_method (MonoMethod *method, MonoError *error) return mono_interp_get_imethod (method, error); } +static MonoJitInfo* +interp_compile_interp_method (MonoMethod *method, MonoError *error) +{ + InterpMethod *imethod = mono_interp_get_imethod (method, error); + return_val_if_nok (error, NULL); + + mono_interp_transform_method (imethod, get_context (), error); + return_val_if_nok (error, NULL); + + return imethod->jinfo; +} + static InterpMethod* lookup_method_pointer (gpointer addr) { @@ -7187,6 +7263,112 @@ interp_run_filter (StackFrameInfo *frame, MonoException *ex, int clause_index, g return retval.data.i ? TRUE : FALSE; } +static gboolean +interp_run_finally_with_il_state (gpointer il_state_ptr, int clause_index, gpointer handler_ip, gpointer handler_ip_end) +{ + MonoMethodILState *il_state = (MonoMethodILState*)il_state_ptr; + MonoMethodSignature *sig; + ThreadContext *context = get_context (); + stackval *sp, *sp_args; + InterpMethod *imethod; + FrameClauseArgs clause_args; + ERROR_DECL (error); + + // FIXME: Optimize this ? Its only used during EH + + sig = mono_method_signature_internal (il_state->method); + g_assert (sig); + + imethod = mono_interp_get_imethod (il_state->method, error); + mono_error_assert_ok (error); + + sp_args = sp = (stackval*)context->stack_pointer; + + int findex = 0; + if (sig->hasthis) { + if (il_state->data [findex]) + sp_args->data.p = *(gpointer*)il_state->data [findex]; + sp_args++; + findex ++; + } + + for (int i = 0; i < sig->param_count; ++i) { + if (il_state->data [findex]) { + int size = stackval_from_data (sig->params [i], sp_args, il_state->data [findex], FALSE); + sp_args = STACK_ADD_BYTES (sp_args, size); + } else { + int size = stackval_size (sig->params [i], FALSE); + sp_args = STACK_ADD_BYTES (sp_args, size); + } + findex ++; + } + + /* Allocate frame */ + InterpFrame frame = {0}; + frame.imethod = imethod; + frame.stack = sp; + frame.retval = sp; + + context->stack_pointer = (guchar*)sp_args; + context->stack_pointer += imethod->alloca_size; + + MonoMethodHeader *header = mono_method_get_header_internal (il_state->method, error); + mono_error_assert_ok (error); + + /* Init locals */ + if (header->num_locals) + memset (frame_locals (&frame) + imethod->local_offsets [0], 0, imethod->locals_size); + /* Copy locals from il_state */ + int locals_start = sig->hasthis + sig->param_count; + for (int i = 0; i < header->num_locals; ++i) { + if (il_state->data [locals_start + i]) + stackval_from_data (header->locals [i], (stackval*)(frame_locals (&frame) + imethod->local_offsets [i]), il_state->data [locals_start + i], FALSE); + } + + memset (&clause_args, 0, sizeof (FrameClauseArgs)); + clause_args.start_with_ip = (const guint16*)handler_ip; + clause_args.end_at_ip = (const guint16*)handler_ip_end; + clause_args.exit_clause = clause_index; + clause_args.exec_frame = &frame; + + // this informs MINT_ENDFINALLY to return to EH + *(guint16**)(frame_locals (&frame) + imethod->clause_data_offsets [clause_index]) = NULL; + + interp_exec_method (&frame, context, &clause_args); + + /* Write back args */ + sp_args = sp; + findex = 0; + if (sig->hasthis) { + // FIXME: This + sp_args++; + findex ++; + } + findex = sig->hasthis ? 1 : 0; + for (int i = 0; i < sig->param_count; ++i) { + if (il_state->data [findex]) { + int size = stackval_to_data (sig->params [i], sp_args, il_state->data [findex], FALSE); + sp_args = STACK_ADD_BYTES (sp_args, size); + } else { + int size = stackval_size (sig->params [i], FALSE); + sp_args = STACK_ADD_BYTES (sp_args, size); + } + findex ++; + } + /* Write back locals */ + for (int i = 0; i < header->num_locals; ++i) { + if (il_state->data [locals_start + i]) + stackval_to_data (header->locals [i], (stackval*)(frame_locals (&frame) + imethod->local_offsets [i]), il_state->data [locals_start + i], FALSE); + } + mono_metadata_free_mh (header); + + // FIXME: Restore stack ? + if (context->has_resume_state) + return TRUE; + else + return FALSE; +} + typedef struct { InterpFrame *current; } StackIter; diff --git a/src/mono/mono/mini/method-to-ir.c b/src/mono/mono/mini/method-to-ir.c index 29948b1d0a2719..db3be9c80bd401 100644 --- a/src/mono/mono/mini/method-to-ir.c +++ b/src/mono/mono/mini/method-to-ir.c @@ -1774,6 +1774,9 @@ emit_push_lmf (MonoCompile *cfg) prev_lmf_reg = alloc_preg (cfg); /* Save previous_lmf */ EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0); + if (cfg->deopt) + /* Mark this as an LMFExt */ + EMIT_NEW_BIALU_IMM (cfg, ins, OP_POR_IMM, prev_lmf_reg, prev_lmf_reg, 2); EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg); /* Set new lmf */ EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg); @@ -1808,6 +1811,9 @@ emit_pop_lmf (MonoCompile *cfg) prev_lmf_reg = alloc_preg (cfg); EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf)); + if (cfg->deopt) + /* Clear out the bit set by push_lmf () to mark this as LMFExt */ + EMIT_NEW_BIALU_IMM (cfg, ins, OP_PXOR_IMM, prev_lmf_reg, prev_lmf_reg, 2); EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg); } @@ -3449,8 +3455,11 @@ method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod) const char *cname = m_class_get_name (cmethod->klass); if (!strcmp (cname, "Assembly") || !strcmp (cname, "AssemblyLoadContext") || - (!strcmp (cname, "Activator"))) + (!strcmp (cname, "Activator"))) { + if (!strcmp (cmethod->name, "op_Equality")) + return FALSE; return TRUE; + } } return FALSE; @@ -3506,6 +3515,18 @@ mini_handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_th } } +static void +emit_set_deopt_il_offset (MonoCompile *cfg, int offset) +{ + MonoInst *ins; + + if (!(cfg->deopt && cfg->method == cfg->current_method)) + return; + + EMIT_NEW_VARLOADA (cfg, ins, cfg->il_state_var, NULL); + MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, ins->dreg, MONO_STRUCT_OFFSET (MonoMethodILState, il_offset), offset); +} + static MonoInst* emit_get_rgctx_dele_tramp (MonoCompile *cfg, int context_used, MonoClass *klass, MonoMethod *virt_method, gboolean _virtual, MonoRgctxInfoType rgctx_type) @@ -5238,9 +5259,8 @@ emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n) } } - guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]); - if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0] && + if (!cfg->deopt && (opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0] && ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) { /* Optimize reg-reg moves away */ /* @@ -6140,7 +6160,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b gboolean detached_before_ret = FALSE; gboolean ins_has_side_effect; - cfg->disable_inline = (method->iflags & METHOD_IMPL_ATTRIBUTE_NOOPTIMIZATION) || is_jit_optimizer_disabled (method); + if (!cfg->disable_inline) + cfg->disable_inline = (method->iflags & METHOD_IMPL_ATTRIBUTE_NOOPTIMIZATION) || is_jit_optimizer_disabled (method); cfg->current_method = method; image = m_class_get_image (method->klass); @@ -6468,8 +6489,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b } } - if (cfg->llvm_only && cfg->interp && cfg->method == method) { - if (!cfg->method->wrapper_type && header->num_clauses) { + if (cfg->llvm_only && cfg->interp && cfg->method == method && !cfg->deopt) { + if (header->num_clauses) { for (int i = 0; i < header->num_clauses; ++i) { MonoExceptionClause *clause = &header->clauses [i]; /* Finally clauses are checked after the remove_finally pass */ @@ -6534,6 +6555,40 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b } } + if (cfg->deopt) { + /* + * Push an LMFExt frame which points to a MonoMethodILState structure. + */ + emit_push_lmf (cfg); + + /* The type doesn't matter, the llvm backend will use the correct type */ + MonoInst *il_state_var = mono_compile_create_var (cfg, mono_get_int_type (), OP_LOCAL); + il_state_var->flags |= MONO_INST_VOLATILE; + cfg->il_state_var = il_state_var; + + EMIT_NEW_VARLOADA (cfg, ins, cfg->il_state_var, NULL); + int il_state_addr_reg = ins->dreg; + + /* il_state->method = method */ + MonoInst *method_ins = emit_get_rgctx_method (cfg, -1, cfg->method, MONO_RGCTX_INFO_METHOD); + MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, il_state_addr_reg, MONO_STRUCT_OFFSET (MonoMethodILState, method), method_ins->dreg); + + EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL); + int lmf_reg = ins->dreg; + + /* lmf->kind = MONO_LMFEXT_IL_STATE */ + MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, lmf_reg, MONO_STRUCT_OFFSET (MonoLMFExt, kind), MONO_LMFEXT_IL_STATE); + + /* lmf->il_state = il_state */ + MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMFExt, il_state), il_state_addr_reg); + + /* emit_get_rgctx_method () might create new bblocks */ + if (cfg->llvm_only) { + init_localsbb = cfg->cbb; + init_localsbb2 = cfg->cbb; + } + } + if (cfg->llvm_only && cfg->interp && cfg->method == method) { if (cfg->interp_entry_only) emit_llvmonly_interp_entry (cfg, header); @@ -6649,6 +6704,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b if (class_inits) g_slist_free (class_inits); class_inits = NULL; + emit_set_deopt_il_offset (cfg, ip - cfg->cil_start); } else { if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) { link_bblock (cfg, cfg->cbb, tblock); @@ -6667,6 +6723,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b } g_slist_free (class_inits); class_inits = NULL; + emit_set_deopt_il_offset (cfg, ip - cfg->cil_start); } } @@ -8023,7 +8080,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b #ifdef TARGET_WASM /* Push an LMF so these frames can be enumerated during stack walks by mono_arch_unwind_frame () */ - if (needs_stack_walk) { + if (needs_stack_walk && !cfg->deopt) { MonoInst *method_ins; int lmf_reg; @@ -8060,7 +8117,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b ins = handle_call_res_devirt (cfg, cmethod, ins); #ifdef TARGET_WASM - if (common_call && needs_stack_walk) + if (common_call && needs_stack_walk && !cfg->deopt) /* If an exception is thrown, the LMF is popped by a call to mini_llvmonly_pop_lmf () */ emit_pop_lmf (cfg); #endif @@ -8187,7 +8244,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b cfg->ret_var_set = TRUE; } } else { - if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only) + if (cfg->lmf_var && cfg->cbb->in_count && (!cfg->llvm_only || cfg->deopt)) emit_pop_lmf (cfg); if (cfg->ret) { @@ -11605,7 +11662,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b #endif #ifdef TARGET_WASM - if (cfg->lmf_var) { + if (cfg->lmf_var && !cfg->deopt) { // mini_llvmonly_pop_lmf () might be called before emit_push_lmf () so initialize the LMF cfg->cbb = init_localsbb; EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL); diff --git a/src/mono/mono/mini/mini-exceptions.c b/src/mono/mono/mini/mini-exceptions.c index 40f804499d0f24..c350d4307bd628 100644 --- a/src/mono/mono/mini/mini-exceptions.c +++ b/src/mono/mono/mini/mini-exceptions.c @@ -437,6 +437,40 @@ arch_unwind_frame (MonoJitTlsData *jit_tls, } } else if (ext->kind == MONO_LMFEXT_JIT_ENTRY) { frame->type = FRAME_TYPE_JIT_ENTRY; + } else if (ext->kind == MONO_LMFEXT_IL_STATE) { + frame->type = FRAME_TYPE_IL_STATE; + frame->method = ext->il_state->method; + frame->actual_method = ext->il_state->method; + frame->il_state = ext->il_state; + + // FIXME: Do this somewhere else ? + ERROR_DECL (error); + frame->ji = mini_get_interp_callbacks ()->compile_interp_method (frame->method, error); + mono_error_assert_ok (error); + g_assert (frame->ji); + + MonoMethodHeader *header = mono_method_get_header_checked (frame->method, error); + mono_error_assert_ok (error); + + /* Find try clause containing IL offset */ + int il_offset = ((MonoMethodILState*)frame->il_state)->il_offset; + int clause_index = -1; + for (int i = 0; i < header->num_clauses; ++i) { + if (il_offset >= header->clauses [i].try_offset && il_offset < header->clauses [i].try_offset + header->clauses [i].try_len) { + clause_index = i; + break; + } + } + + mono_metadata_free_mh (header); + + if (clause_index == -1) { + frame->native_offset = 0xffffff; + } else { + /* Set ctx->ip to the beginning of the corresponding interpreter try clause */ + g_assert (clause_index < frame->ji->num_clauses); + frame->native_offset = (guint8*)frame->ji->clauses [clause_index].try_start - (guint8*)frame->ji->code_start; + } } else { g_assert_not_reached (); } @@ -663,7 +697,8 @@ mono_find_jit_info_ext (MonoJitTlsData *jit_tls, frame->method = NULL; } - frame->native_offset = -1; + if (frame->type != FRAME_TYPE_IL_STATE) + frame->native_offset = -1; frame->async_context = async; frame->frame_addr = MONO_CONTEXT_GET_SP (ctx); @@ -682,10 +717,12 @@ mono_find_jit_info_ext (MonoJitTlsData *jit_tls, /* ctx->ip points into native code */ real_ip = (const char*)MONO_CONTEXT_GET_IP (new_ctx); - if ((real_ip >= start) && (real_ip <= start + ji->code_size)) - frame->native_offset = real_ip - start; - else { - frame->native_offset = -1; + if (frame->type != FRAME_TYPE_IL_STATE) { + if ((real_ip >= start) && (real_ip <= start + ji->code_size)) + frame->native_offset = real_ip - start; + else { + frame->native_offset = -1; + } } if (trace) @@ -1855,12 +1892,14 @@ handle_exception_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filt case FRAME_TYPE_INTERP: case FRAME_TYPE_MANAGED: break; + case FRAME_TYPE_IL_STATE: + break; default: g_assert_not_reached (); break; } - in_interp = frame.type == FRAME_TYPE_INTERP; + in_interp = (frame.type == FRAME_TYPE_INTERP) || (frame.type == FRAME_TYPE_IL_STATE); ji = frame.ji; gpointer ip; @@ -1900,8 +1939,7 @@ handle_exception_first_pass (MonoContext *ctx, MonoObject *obj, gint32 *out_filt if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED && ftnptr_eh_callback) { result = MONO_FIRST_PASS_CALLBACK_TO_NATIVE; } - - + for (i = clause_index_start; i < ji->num_clauses; i++) { MonoJitExceptionInfo *ei = &ji->clauses [i]; gboolean filtered = FALSE; @@ -2285,6 +2323,7 @@ mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resu jit_tls->abort_func (obj); g_assert_not_reached (); } + in_interp = FALSE; switch (frame.type) { case FRAME_TYPE_DEBUGGER_INVOKE: case FRAME_TYPE_MANAGED_TO_NATIVE: @@ -2296,14 +2335,16 @@ mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resu continue; case FRAME_TYPE_INTERP_TO_MANAGED: continue; - case FRAME_TYPE_INTERP: case FRAME_TYPE_MANAGED: break; + case FRAME_TYPE_INTERP: + case FRAME_TYPE_IL_STATE: + in_interp = TRUE; + break; default: g_assert_not_reached (); break; } - in_interp = frame.type == FRAME_TYPE_INTERP; ji = frame.ji; } @@ -2514,7 +2555,11 @@ mono_handle_exception_internal (MonoContext *ctx, MonoObject *obj, gboolean resu return 0; } else { mini_set_abort_threshold (&frame); - if (in_interp) { + if (frame.type == FRAME_TYPE_IL_STATE) { + if (mono_trace_is_enabled () && mono_trace_eval (method)) + g_print ("EXCEPTION: clause found in AOTed code, running clause with interpreter.\n"); + mini_get_interp_callbacks ()->run_finally_with_il_state (frame.il_state, i, ei->handler_start, ei->data.handler_end); + } else if (in_interp) { gboolean has_ex = mini_get_interp_callbacks ()->run_finally (&frame, i, ei->handler_start, ei->data.handler_end); if (has_ex) { /* @@ -3398,6 +3443,20 @@ throw_exception (MonoObject *ex, gboolean rethrow) void mono_llvm_throw_exception (MonoObject *ex) { + g_assert (mono_llvm_only); + + /* + * There are native frames above us, possibly followed by + * interpreter frames. Handle the exception here to + * allow the finally clauses in the native frames to be ran. + * Then throw the c++ exception to unwind back to the interpreter. + */ + MonoContext ctx; + memset (&ctx, 0, sizeof (MonoContext)); + MONO_CONTEXT_SET_SP (&ctx, &ctx); + + mono_handle_exception (&ctx, (MonoObject*)ex); + throw_exception (ex, FALSE); } diff --git a/src/mono/mono/mini/mini-llvm.c b/src/mono/mono/mini/mini-llvm.c index 75c45652b06a5a..cd6a279c223d80 100644 --- a/src/mono/mono/mini/mini-llvm.c +++ b/src/mono/mono/mini/mini-llvm.c @@ -195,6 +195,7 @@ typedef struct { LLVMValueRef long_bb_break_var; int *gc_var_indexes; LLVMValueRef gc_pin_area; + LLVMValueRef il_state; } EmitContext; typedef struct { @@ -2371,7 +2372,7 @@ emit_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref, LL if (ctx->llvm_only) { clause = get_most_deep_clause (cfg, ctx, bb); - if (clause) { + if (!ctx->cfg->deopt && clause) { g_assert (clause->flags == MONO_EXCEPTION_CLAUSE_NONE || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT); /* @@ -3816,11 +3817,15 @@ emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder) return; /* Could be already created by an OP_VPHI */ if (!ctx->addresses [var->dreg]) { - if (var->flags & MONO_INST_LMF) - ctx->addresses [var->dreg] = build_alloca_llvm_type_name (ctx, LLVMArrayType (LLVMInt8Type (), MONO_ABI_SIZEOF (MonoLMF)), sizeof (target_mgreg_t), "entry_lmf"); - else - ctx->addresses [var->dreg] = build_named_alloca (ctx, var->inst_vtype, "entry"); - //LLVMSetValueName (ctx->addresses [var->dreg], g_strdup_printf ("vreg_loc_%d", var->dreg)); + if (var->flags & MONO_INST_LMF) { + // FIXME: Allocate a smaller struct in the deopt case + int size = cfg->deopt ? MONO_ABI_SIZEOF (MonoLMFExt) : MONO_ABI_SIZEOF (MonoLMF); + ctx->addresses [var->dreg] = build_alloca_llvm_type_name (ctx, LLVMArrayType (LLVMInt8Type (), size), sizeof (target_mgreg_t), "lmf"); + } else { + char *name = g_strdup_printf ("vreg_loc_%d", var->dreg); + ctx->addresses [var->dreg] = build_named_alloca (ctx, var->inst_vtype, name); + g_free (name); + } } ctx->vreg_cli_types [var->dreg] = var->inst_vtype; } @@ -4030,6 +4035,72 @@ emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder) } #endif + if (cfg->deopt) { + LLVMValueRef addr, index [2]; + MonoMethodHeader *header = cfg->header; + int nfields = sig->hasthis + sig->param_count + header->num_locals + 2; + LLVMTypeRef *types = g_alloca (nfields * sizeof (LLVMTypeRef)); + int findex = 0; + /* method */ + types [findex ++] = IntPtrType (); + /* il_offset */ + types [findex ++] = LLVMInt32Type (); + int data_start = findex; + /* data */ + if (sig->hasthis) + types [findex ++] = IntPtrType (); + for (int i = 0; i < sig->param_count; ++i) + types [findex ++] = LLVMPointerType (type_to_llvm_type (ctx, sig->params [i]), 0); + for (int i = 0; i < header->num_locals; ++i) + types [findex ++] = LLVMPointerType (type_to_llvm_type (ctx, header->locals [i]), 0); + g_assert (findex == nfields); + char *name = g_strdup_printf ("%s_il_state", ctx->method_name); + LLVMTypeRef il_state_type = LLVMStructCreateNamed (ctx->module->context, name); + LLVMStructSetBody (il_state_type, types, nfields, FALSE); + g_free (name); + + ctx->il_state = build_alloca_llvm_type_name (ctx, il_state_type, 0, "il_state"); + g_assert (cfg->il_state_var); + ctx->addresses [cfg->il_state_var->dreg] = ctx->il_state; + + /* Set il_state->il_offset = -1 */ + index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE); + index [1] = LLVMConstInt (LLVMInt32Type (), 1, FALSE); + addr = LLVMBuildGEP (builder, ctx->il_state, index, 2, ""); + LLVMBuildStore (ctx->builder, LLVMConstInt (types [1], -1, FALSE), addr); + + /* + * Set il_state->data [i] to either the address of the arg/local, or NULL. + * Because of mono_liveness_handle_exception_clauses (), all locals used/reachable from + * clauses are supposed to be volatile, so they have an address. + */ + findex = data_start; + for (int i = 0; i < sig->hasthis + sig->param_count; ++i) { + LLVMValueRef var_addr = ctx->addresses [cfg->args [i]->dreg]; + + index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE); + index [1] = LLVMConstInt (LLVMInt32Type (), findex, FALSE); + addr = LLVMBuildGEP (builder, ctx->il_state, index, 2, ""); + if (var_addr) + LLVMBuildStore (ctx->builder, var_addr, convert (ctx, addr, LLVMPointerType (LLVMTypeOf (var_addr), 0))); + else + LLVMBuildStore (ctx->builder, LLVMConstNull (types [findex]), addr); + findex ++; + } + for (int i = 0; i < header->num_locals; ++i) { + LLVMValueRef var_addr = ctx->addresses [cfg->locals [i]->dreg]; + + index [0] = LLVMConstInt (LLVMInt32Type (), 0, FALSE); + index [1] = LLVMConstInt (LLVMInt32Type (), findex, FALSE); + addr = LLVMBuildGEP (builder, ctx->il_state, index, 2, ""); + if (var_addr) + LLVMBuildStore (ctx->builder, LLVMBuildBitCast (builder, var_addr, types [findex], ""), addr); + else + LLVMBuildStore (ctx->builder, LLVMConstNull (types [findex]), addr); + findex ++; + } + } + /* Initialize the method if needed */ if (cfg->compile_aot) { /* Emit a location for the initialization code */ @@ -11005,7 +11076,12 @@ process_bb (EmitContext *ctx, MonoBasicBlock *bb) } if (ctx->llvm_only) { - emit_resume_eh (ctx, bb); + if (!cfg->deopt) { + emit_resume_eh (ctx, bb); + } else { + /* Not needed */ + LLVMBuildUnreachable (builder); + } } else { LLVMTypeRef icall_sig = LLVMFunctionType (LLVMVoidType (), NULL, 0, FALSE); if (ctx->cfg->compile_aot) { diff --git a/src/mono/mono/mini/mini-ops.h b/src/mono/mono/mini/mini-ops.h index 8857019c96ebf3..f41585485a9111 100644 --- a/src/mono/mono/mini/mini-ops.h +++ b/src/mono/mono/mini/mini-ops.h @@ -290,6 +290,7 @@ MINI_OP(OP_LCONV_TO_I, "long_conv_to_i", LREG, LREG, NONE) MINI_OP(OP_LCONV_TO_OVF_I,"long_conv_to_ovf_i", LREG, LREG, NONE) MINI_OP(OP_LCONV_TO_OVF_U,"long_conv_to_ovf_u", LREG, LREG, NONE) +/* inst_exc_name contains the exception name to throw */ MINI_OP(OP_LADD_OVF, "long_add_ovf", LREG, LREG, LREG) MINI_OP(OP_LADD_OVF_UN, "long_add_ovf_un", LREG, LREG, LREG) MINI_OP(OP_LMUL_OVF, "long_mul_ovf", LREG, LREG, LREG) @@ -395,6 +396,8 @@ MINI_OP(OP_ICONV_TO_U1, "int_conv_to_u1", IREG, IREG, NONE) MINI_OP(OP_ICONV_TO_I, "int_conv_to_i", IREG, IREG, NONE) MINI_OP(OP_ICONV_TO_OVF_I,"int_conv_to_ovf_i", IREG, IREG, NONE) MINI_OP(OP_ICONV_TO_OVF_U,"int_conv_to_ovf_u", IREG, IREG, NONE) + +/* inst_exc_name contains the exception name to throw */ MINI_OP(OP_IADD_OVF, "int_add_ovf", IREG, IREG, IREG) MINI_OP(OP_IADD_OVF_UN, "int_add_ovf_un", IREG, IREG, IREG) MINI_OP(OP_IMUL_OVF, "int_mul_ovf", IREG, IREG, IREG) diff --git a/src/mono/mono/mini/mini-runtime.h b/src/mono/mono/mini/mini-runtime.h index 3a2a2382247b75..d1e822a35e7a22 100644 --- a/src/mono/mono/mini/mini-runtime.h +++ b/src/mono/mono/mini/mini-runtime.h @@ -201,10 +201,19 @@ struct MonoJitTlsData { #endif }; +typedef struct { + MonoMethod *method; + /* Either the IL offset of the currently executing code, or -1 */ + int il_offset; + /* For every arg+local, either its address on the stack, or NULL */ + gpointer data [1]; +} MonoMethodILState; + #define MONO_LMFEXT_DEBUGGER_INVOKE 1 #define MONO_LMFEXT_INTERP_EXIT 2 #define MONO_LMFEXT_INTERP_EXIT_WITH_CTX 3 #define MONO_LMFEXT_JIT_ENTRY 4 +#define MONO_LMFEXT_IL_STATE 5 /* * The MonoLMF structure is arch specific, it includes at least these fields. @@ -232,6 +241,7 @@ typedef struct { int kind; MonoContext ctx; /* valid if kind == DEBUGGER_INVOKE || kind == INTERP_EXIT_WITH_CTX */ gpointer interp_exit_data; /* valid if kind == INTERP_EXIT || kind == INTERP_EXIT_WITH_CTX */ + MonoMethodILState *il_state; /* valid if kind == IL_STATE */ #if defined (_MSC_VER) gboolean interp_exit_label_set; #endif diff --git a/src/mono/mono/mini/mini.c b/src/mono/mono/mini/mini.c index c9486dce45c48d..2d6e3a22930f79 100644 --- a/src/mono/mono/mini/mini.c +++ b/src/mono/mono/mini/mini.c @@ -3071,6 +3071,32 @@ mini_get_rgctx_access_for_method (MonoMethod *method) return MONO_RGCTX_ACCESS_THIS; } +static gboolean +can_deopt (MonoCompile *cfg) +{ + MonoMethodHeader *header = cfg->header; + + if (!header->num_clauses) + return FALSE; + + /* + * Currently, only finally/fault clauses are supported. + * Catch clauses are hard to support, since even if the + * rest of the method is executed by the interpreter, execution needs to + * return to the caller which is an AOTed method. + * Filter clauses could be supported, but every filter clause has an + * associated catch clause. + */ + for (int i = 0; i < header->num_clauses; ++i) { + MonoExceptionClause *clause = &header->clauses [i]; + + if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT) + return FALSE; + } + + return TRUE; +} + /* * mini_method_compile: * @method: the method to compile @@ -3305,6 +3331,12 @@ mini_method_compile (MonoMethod *method, guint32 opts, JitFlags flags, int parts return cfg; } + if (cfg->llvm_only && cfg->interp && !cfg->interp_entry_only && header->num_clauses && can_deopt (cfg)) { + cfg->deopt = TRUE; + /* Can't reconstruct inlined state */ + cfg->disable_inline = TRUE; + } + #ifdef ENABLE_LLVM { static gboolean inited; @@ -3600,7 +3632,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, JitFlags flags, int parts remove_empty_finally_pass (cfg); - if (cfg->llvm_only && cfg->interp && !cfg->method->wrapper_type && !interp_entry_only) { + if (cfg->llvm_only && cfg->interp && !cfg->method->wrapper_type && !interp_entry_only && !cfg->deopt) { /* Disable llvm if there are still finally clauses left */ for (int i = 0; i < cfg->header->num_clauses; ++i) { MonoExceptionClause *clause = &header->clauses [i]; diff --git a/src/mono/mono/mini/mini.h b/src/mono/mono/mini/mini.h index e671ca86b11ae6..85f64cd67cc777 100644 --- a/src/mono/mono/mini/mini.h +++ b/src/mono/mono/mini/mini.h @@ -1399,6 +1399,7 @@ typedef struct { MonoInst *lmf_var; MonoInst *lmf_addr_var; + MonoInst *il_state_var; MonoInst *stack_inbalance_var; @@ -1452,10 +1453,6 @@ typedef struct { * instead of being generated in emit_prolog ()/emit_epilog (). */ guint lmf_ir : 1; - /* - * Whenever to use the mono_lmf TLS variable instead of indirection through the - * mono_lmf_addr TLS variable. - */ guint gen_write_barriers : 1; guint init_ref_vars : 1; guint extend_live_ranges : 1; @@ -1493,6 +1490,7 @@ typedef struct { guint interp_entry_only : 1; guint after_method_to_ir : 1; guint disable_inline_rgctx_fetch : 1; + guint deopt : 1; guint8 uses_simd_intrinsics; int r4_stack_type; gpointer debug_info; @@ -1802,6 +1800,7 @@ enum { #define OP_PSUB OP_LSUB #define OP_PMUL OP_LMUL #define OP_PMUL_IMM OP_LMUL_IMM +#define OP_POR_IMM OP_LOR_IMM #define OP_PNEG OP_LNEG #define OP_PCONV_TO_I1 OP_LCONV_TO_I1 #define OP_PCONV_TO_U1 OP_LCONV_TO_U1 @@ -1832,6 +1831,7 @@ enum { #define OP_PSUB OP_ISUB #define OP_PMUL OP_IMUL #define OP_PMUL_IMM OP_IMUL_IMM +#define OP_POR_IMM OP_IOR_IMM #define OP_PNEG OP_INEG #define OP_PCONV_TO_I1 OP_ICONV_TO_I1 #define OP_PCONV_TO_U1 OP_ICONV_TO_U1 @@ -2856,7 +2856,6 @@ typedef enum { MONO_CPU_X86_BMI1 = 1 << 14, MONO_CPU_X86_BMI2 = 1 << 15, - // // Dependencies (based on System.Runtime.Intrinsics.X86 class hierarchy): // diff --git a/src/mono/mono/tools/offsets-tool/offsets-tool.py b/src/mono/mono/tools/offsets-tool/offsets-tool.py index 11de36fda20b11..4a2c68920d2bd7 100644 --- a/src/mono/mono/tools/offsets-tool/offsets-tool.py +++ b/src/mono/mono/tools/offsets-tool/offsets-tool.py @@ -252,6 +252,8 @@ def run_clang(self): ] self.jit_type_names = [ "MonoLMF", + "MonoLMFExt", + "MonoMethodILState", "MonoMethodRuntimeGenericContext", "MonoJitTlsData", "MonoGSharedVtMethodRuntimeInfo", diff --git a/src/mono/mono/utils/mono-stack-unwinding.h b/src/mono/mono/utils/mono-stack-unwinding.h index f27b2cbb00a6a8..b3109a9b0e61f3 100644 --- a/src/mono/mono/utils/mono-stack-unwinding.h +++ b/src/mono/mono/utils/mono-stack-unwinding.h @@ -32,7 +32,9 @@ typedef enum { FRAME_TYPE_INTERP_ENTRY = 7, /* Frame marking transition to native JIT compiler */ FRAME_TYPE_JIT_ENTRY = 8, - FRAME_TYPE_NUM = 9 + /* Compiled method with IL state */ + FRAME_TYPE_IL_STATE = 9, + FRAME_TYPE_NUM = 10 } MonoStackFrameType; typedef enum { @@ -103,6 +105,9 @@ typedef struct { guint8 *unwind_info; host_mgreg_t **reg_locations; + + /* For FRAME_TYPE_IL_STATE */ + gpointer il_state; /* MonoMethodILState */ } MonoStackFrameInfo; /*Index into MonoThreadState::unwind_data. */ From 2a11aab0cc220545b072cd13ee7479cfa7cbd0f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Mon, 3 Jan 2022 20:52:46 +0900 Subject: [PATCH 09/97] Move things from ILCompiler.TypeSystem to ILCompiler.Compiler (#63280) IL generation (stubs/thunks) is not part of the core type system and these files are not included in ILCompiler.TypeSystem.ReadyToRun. Somehow we accumulated them in ILCompiler.TypeSystem but they can be pretty cleanly moved to ILCompiler.Compiler (left one TODO for a subsequent cleanup since some of what's in Common\TypeSystem should actually be in ILCompiler.Compiler proper). --- .../CalliMarshallingMethodThunk.Sorting.cs | 4 +- .../DelegateMarshallingMethodThunk.Sorting.cs | 4 +- .../IL/Stubs/DelegateThunks.Sorting.cs | 18 +- .../TypeSystem/IL/Stubs/DelegateThunks.cs | 3 +- .../Stubs/DynamicInvokeMethodThunk.Sorting.cs | 8 +- .../TypeSystem/IL/Stubs/EnumThunks.Sorting.cs | 8 +- .../ForwardDelegateCreationThunk.Sorting.cs | 4 +- .../IL/Stubs/PInvokeLazyFixupField.Sorting.cs | 4 +- .../Stubs/StructMarshallingThunk.Sorting.cs | 4 +- ...ypeGetFieldHelperMethodOverride.Sorting.cs | 4 +- .../Interop/IL/InlineArrayType.Sorting.cs | 16 +- .../Interop/IL/NativeStructType.Sorting.cs | 8 +- .../IL/PInvokeDelegateWrapper.Sorting.cs | 4 +- ...nvokeDelegateWrapperConstructor.Sorting.cs | 4 +- .../Compiler/CompilerTypeSystemContext.Aot.cs | 8 +- ...CompilerTypeSystemContext.DelegateInfo.cs} | 23 ++- ...ompilerTypeSystemContext.DynamicInvoke.cs} | 7 +- .../CompilerTypeSystemContext.EnumMethods.cs} | 5 +- ...ystemContext.GeneratedAssembly.Sorting.cs} | 10 +- ...lerTypeSystemContext.GeneratedAssembly.cs} | 6 +- ...ompilerTypeSystemContext.IntefaceThunks.cs | 2 +- ...ilerTypeSystemContext.ValueTypeMethods.cs} | 7 +- .../Compiler/DelegateCreationInfo.cs | 2 +- .../MultiFileCompilationModuleGroup.cs | 4 +- .../ILCompiler.Compiler.csproj | 144 ++++++++++++++++ .../ILCompiler.TypeSystem.csproj | 159 ------------------ src/coreclr/tools/aot/ILCompiler/Program.cs | 4 +- 27 files changed, 229 insertions(+), 245 deletions(-) rename src/coreclr/tools/{Common/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs => aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs} (67%) rename src/coreclr/tools/{Common/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs => aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs} (85%) rename src/coreclr/tools/{Common/TypeSystem/IL/TypeSystemContext.EnumMethods.cs => aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs} (97%) rename src/coreclr/tools/{Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs => aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs} (64%) rename src/coreclr/tools/{Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs => aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs} (98%) rename src/coreclr/tools/{Common/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs => aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs} (97%) diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs index 1c48c00b406078..89be9fa3a7d881 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs @@ -8,9 +8,9 @@ namespace Internal.IL.Stubs // Functionality related to deterministic ordering of methods partial class CalliMarshallingMethodThunk { - protected internal override int ClassCode => 1594107963; + protected override int ClassCode => 1594107963; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (CalliMarshallingMethodThunk)other; return comparer.Compare(_targetSignature, otherMethod._targetSignature); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs index c0a4887211c179..b38cd1fda8e540 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs @@ -8,9 +8,9 @@ namespace Internal.IL.Stubs // Functionality related to deterministic ordering of methods partial class DelegateMarshallingMethodThunk { - protected internal override int ClassCode => 1018037605; + protected override int ClassCode => 1018037605; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (DelegateMarshallingMethodThunk)other; int result = (int)Kind - (int)otherMethod.Kind; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs index a5aece70b22371..1126e01d4020ba 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs @@ -8,7 +8,7 @@ namespace Internal.IL.Stubs // Functionality related to deterministic ordering of types partial class DelegateThunk { - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (DelegateThunk)other; return comparer.Compare(_delegateInfo.Type, otherMethod._delegateInfo.Type); @@ -17,39 +17,39 @@ protected internal override int CompareToImpl(MethodDesc other, TypeSystemCompar partial class DelegateInvokeOpenStaticThunk { - protected internal override int ClassCode => 386356101; + protected override int ClassCode => 386356101; } public sealed partial class DelegateInvokeOpenInstanceThunk { - protected internal override int ClassCode => -1787190244; + protected override int ClassCode => -1787190244; } partial class DelegateInvokeClosedStaticThunk { - protected internal override int ClassCode => 28195375; + protected override int ClassCode => 28195375; } partial class DelegateInvokeMulticastThunk { - protected internal override int ClassCode => 639863471; + protected override int ClassCode => 639863471; } partial class DelegateInvokeInstanceClosedOverGenericMethodThunk { - protected internal override int ClassCode => -354480633; + protected override int ClassCode => -354480633; } partial class DelegateInvokeObjectArrayThunk { - protected internal override int ClassCode => 1993292344; + protected override int ClassCode => 1993292344; } partial class DelegateGetThunkMethodOverride { - protected internal override int ClassCode => -321263379; + protected override int ClassCode => -321263379; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (DelegateGetThunkMethodOverride)other; return comparer.Compare(_delegateInfo.Type, otherMethod._delegateInfo.Type); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs index 2d76523052ecd0..5e9ed17fbc478b 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs @@ -726,7 +726,8 @@ public override MethodIL EmitIL() Debug.Assert(_delegateInfo.Thunks[i] == null); var sig = new DynamicInvokeMethodSignature(_delegateInfo.Signature); - MethodDesc thunk = Context.GetDynamicInvokeThunk(sig); + // TODO: layering violation. Should move delegate thunk stuff to ILCompiler.Compiler. + MethodDesc thunk = ((ILCompiler.CompilerTypeSystemContext)Context).GetDynamicInvokeThunk(sig); if (thunk.HasInstantiation) { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs index 43da587d086346..29976d1a659c4e 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs @@ -11,9 +11,9 @@ namespace Internal.IL.Stubs // Functionality related to determinstic ordering of types partial class DynamicInvokeMethodThunk { - protected internal override int ClassCode => -1980933220; + protected override int ClassCode => -1980933220; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { return CompareTo((DynamicInvokeMethodThunk)other); } @@ -51,9 +51,9 @@ private int CompareTo(DynamicInvokeMethodThunk otherMethod) partial class DynamicInvokeThunkGenericParameter { - protected internal override int ClassCode => -234393261; + protected override int ClassCode => -234393261; - protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { var otherType = (DynamicInvokeThunkGenericParameter)other; int result = Index - otherType.Index; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs index d6ae00c139863f..33b07a8e86f109 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs @@ -8,9 +8,9 @@ namespace Internal.IL.Stubs // Functionality related to deterministic ordering of types partial class EnumGetHashCodeThunk { - protected internal override int ClassCode => 261739662; + protected override int ClassCode => 261739662; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (EnumGetHashCodeThunk)other; return comparer.Compare(_owningType, otherMethod._owningType); @@ -19,9 +19,9 @@ protected internal override int CompareToImpl(MethodDesc other, TypeSystemCompar partial class EnumEqualsThunk { - protected internal override int ClassCode => -1774524780; + protected override int ClassCode => -1774524780; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (EnumEqualsThunk)other; return comparer.Compare(_owningType, otherMethod._owningType); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs index 7bdbbadd0d00fc..66d5142caa2878 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs @@ -8,9 +8,9 @@ namespace Internal.IL.Stubs // Functionality related to deterministic ordering of types partial class ForwardDelegateCreationThunk { - protected internal override int ClassCode => 1026039617; + protected override int ClassCode => 1026039617; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (ForwardDelegateCreationThunk)other; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs index edfccf89890e67..d3156fbefb2cf4 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs @@ -7,9 +7,9 @@ namespace Internal.IL.Stubs { partial class PInvokeLazyFixupField { - protected internal override int ClassCode => -1784477702; + protected override int ClassCode => -1784477702; - protected internal override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer) { return comparer.Compare(_targetMethod, ((PInvokeLazyFixupField)other)._targetMethod); } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs index f2eee55f961086..0cbb4f7e7c6c38 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs @@ -8,9 +8,9 @@ namespace Internal.IL.Stubs // Functionality related to deterministic ordering of types partial class StructMarshallingThunk { - protected internal override int ClassCode => 340834018; + protected override int ClassCode => 340834018; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (StructMarshallingThunk)other; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs index 882a4419e2e242..e12b3bc41567f9 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs @@ -7,9 +7,9 @@ namespace Internal.IL.Stubs { partial class ValueTypeGetFieldHelperMethodOverride { - protected internal override int ClassCode => 2036839816; + protected override int ClassCode => 2036839816; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (ValueTypeGetFieldHelperMethodOverride)other; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs index 2bcee373962bea..c8655241711389 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs @@ -6,9 +6,9 @@ namespace Internal.TypeSystem.Interop // Functionality related to determinstic ordering of types partial class InlineArrayType { - protected internal override int ClassCode => 226817075; + protected override int ClassCode => 226817075; - protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { var otherType = (InlineArrayType)other; int result = (int)Length - (int)otherType.Length; @@ -20,9 +20,9 @@ protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer partial class InlineArrayMethod { - protected internal override int ClassCode => -1303220581; + protected override int ClassCode => -1303220581; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var otherMethod = (InlineArrayMethod)other; @@ -30,19 +30,19 @@ protected internal override int CompareToImpl(MethodDesc other, TypeSystemCompar if (result != 0) return result; - return comparer.CompareWithinClass(OwningType, otherMethod.OwningType); + return comparer.Compare(OwningType, otherMethod.OwningType); } } partial class InlineArrayField { - protected internal override int ClassCode => 1542668652; + protected override int ClassCode => 1542668652; - protected internal override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer) { var otherField = (InlineArrayField)other; - return comparer.CompareWithinClass(OwningType, otherField.OwningType); + return comparer.Compare(OwningType, otherField.OwningType); } } } diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs index 0da2d42007d56b..bcd97084e56718 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs @@ -6,18 +6,18 @@ namespace Internal.TypeSystem.Interop // Functionality related to determinstic ordering of types partial class NativeStructType { - protected internal override int ClassCode => -377751537; + protected override int ClassCode => -377751537; - protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { return comparer.Compare(ManagedStructType, ((NativeStructType)other).ManagedStructType); } partial class NativeStructField { - protected internal override int ClassCode => 1580219745; + protected override int ClassCode => 1580219745; - protected internal override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(FieldDesc other, TypeSystemComparer comparer) { return comparer.Compare(_managedField, ((NativeStructField)other)._managedField); } diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs index 6b4f6b9ca06206..72948268466607 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs @@ -6,9 +6,9 @@ namespace Internal.TypeSystem.Interop // Functionality related to determinstic ordering of types partial class PInvokeDelegateWrapper { - protected internal override int ClassCode => -262930217; + protected override int ClassCode => -262930217; - protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { return comparer.Compare(DelegateType, ((PInvokeDelegateWrapper)other).DelegateType); } diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs index 2509b265ea71e8..5fe9290213b2f6 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs @@ -6,9 +6,9 @@ namespace Internal.TypeSystem.Interop // Functionality related to deterministic ordering of methods partial class PInvokeDelegateWrapperConstructor { - protected internal override int ClassCode => 1000342011; + protected override int ClassCode => 1000342011; - protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { var owningType = (PInvokeDelegateWrapper)OwningType; var otherOwningType = (PInvokeDelegateWrapper)other.OwningType; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs index 33305d2011c876..91446e51641879 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs @@ -19,7 +19,6 @@ public SharedGenericsConfiguration GenericsConfig get; } - private readonly DelegateFeature _delegateFeatures; private readonly MetadataFieldLayoutAlgorithm _metadataFieldLayoutAlgorithm = new CompilerMetadataFieldLayoutAlgorithm(); private readonly RuntimeDeterminedFieldLayoutAlgorithm _runtimeDeterminedFieldLayoutAlgorithm = new RuntimeDeterminedFieldLayoutAlgorithm(); private readonly VectorOfTFieldLayoutAlgorithm _vectorOfTFieldLayoutAlgorithm; @@ -37,7 +36,7 @@ public CompilerTypeSystemContext(TargetDetails details, SharedGenericsMode gener _vectorOfTFieldLayoutAlgorithm = new VectorOfTFieldLayoutAlgorithm(_metadataFieldLayoutAlgorithm); _vectorFieldLayoutAlgorithm = new VectorFieldLayoutAlgorithm(_metadataFieldLayoutAlgorithm); - _delegateFeatures = delegateFeatures; + _delegateInfoHashtable = new DelegateInfoHashtable(delegateFeatures); GenericsConfig = new SharedGenericsConfiguration(); } @@ -165,11 +164,6 @@ protected virtual IEnumerable GetAllMethodsForDelegate(TypeDesc type yield return m; } - protected override DelegateInfo CreateDelegateInfo(TypeDesc delegateType) - { - return new DelegateInfo(delegateType, _delegateFeatures); - } - internal DefType GetClosestDefType(TypeDesc type) { if (type.IsArray) diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs similarity index 67% rename from src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs index b9a3a3e1fdbbb2..a021e39691d226 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.DelegateInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs @@ -4,13 +4,19 @@ using System; using Internal.IL; +using Internal.TypeSystem; -namespace Internal.TypeSystem +namespace ILCompiler { - public abstract partial class TypeSystemContext + partial class CompilerTypeSystemContext { private class DelegateInfoHashtable : LockFreeReaderHashtable { + private readonly DelegateFeature _delegateFeatures; + + public DelegateInfoHashtable(DelegateFeature features) + => _delegateFeatures = features; + protected override int GetKeyHashCode(TypeDesc key) { return key.GetHashCode(); @@ -29,24 +35,15 @@ protected override bool CompareValueToValue(DelegateInfo value1, DelegateInfo va } protected override DelegateInfo CreateValueFromKey(TypeDesc key) { - return key.Context.CreateDelegateInfo(key); + return new DelegateInfo(key, _delegateFeatures); } } - private DelegateInfoHashtable _delegateInfoHashtable = new DelegateInfoHashtable(); + private readonly DelegateInfoHashtable _delegateInfoHashtable; public DelegateInfo GetDelegateInfo(TypeDesc delegateType) { return _delegateInfoHashtable.GetOrCreateValue(delegateType); } - - /// - /// Creates a for a given delegate type. - /// - protected virtual DelegateInfo CreateDelegateInfo(TypeDesc key) - { - // Type system contexts that support creating delegate infos need to override. - throw new NotSupportedException(); - } } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs similarity index 85% rename from src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs index 290f11dd90a508..0ed3d107b3a396 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.DynamicInvoke.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using Internal.IL.Stubs; +using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; -namespace Internal.TypeSystem +namespace ILCompiler { - partial class TypeSystemContext + partial class CompilerTypeSystemContext { private class DynamicInvokeThunkHashtable : LockFreeReaderHashtable { @@ -17,7 +18,7 @@ private class DynamicInvokeThunkHashtable : LockFreeReaderHashtable value.TargetSignature.GetHashCode(); protected override DynamicInvokeMethodThunk CreateValueFromKey(DynamicInvokeMethodSignature key) { - return new DynamicInvokeMethodThunk(key.Context.GeneratedAssembly.GetGlobalModuleType(), key); + return new DynamicInvokeMethodThunk(((CompilerTypeSystemContext)key.Context).GeneratedAssembly.GetGlobalModuleType(), key); } } DynamicInvokeThunkHashtable _dynamicInvokeThunks = new DynamicInvokeThunkHashtable(); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.EnumMethods.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs similarity index 97% rename from src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.EnumMethods.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs index 0be009f53c7bb3..b777e28a2d144e 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.EnumMethods.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs @@ -3,13 +3,14 @@ using System.Collections.Generic; +using Internal.TypeSystem; using Internal.IL.Stubs; using Debug = System.Diagnostics.Debug; -namespace Internal.TypeSystem +namespace ILCompiler { - public abstract partial class TypeSystemContext + partial class CompilerTypeSystemContext { private class EnumInfo { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs similarity index 64% rename from src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs index a2490a4cb196e7..41254150763cf9 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs @@ -3,16 +3,18 @@ using System; -namespace Internal.TypeSystem +using Internal.TypeSystem; + +namespace ILCompiler { - partial class TypeSystemContext + partial class CompilerTypeSystemContext { // Functionality related to determinstic ordering of types and members partial class CompilerGeneratedType : MetadataType { - protected internal override int ClassCode => -1036681447; + protected override int ClassCode => -1036681447; - protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) + protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { // Should be a singleton throw new NotSupportedException(); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs similarity index 98% rename from src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs index 1a289f651f107e..280f2d85684a3b 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.GeneratedAssembly.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs @@ -4,14 +4,16 @@ using System; using System.Collections.Generic; +using Internal.TypeSystem; + using TypeHashingAlgorithms = Internal.NativeFormat.TypeHashingAlgorithms; using Interlocked = System.Threading.Interlocked; using AssemblyName = System.Reflection.AssemblyName; using Debug = System.Diagnostics.Debug; -namespace Internal.TypeSystem +namespace ILCompiler { - partial class TypeSystemContext + partial class CompilerTypeSystemContext { private ModuleDesc _generatedAssembly; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs index 06c13c51e6d8d1..adc509298c0bbc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.IntefaceThunks.cs @@ -149,7 +149,7 @@ protected override bool CompareValueToValue(DefaultInterfaceMethodImplementation } protected override DefaultInterfaceMethodImplementationInstantiationThunk CreateValueFromKey(DefaultInterfaceMethodImplementationInstantiationThunkHashtableKey key) { - TypeDesc owningTypeOfThunks = key.TargetMethod.Context.GeneratedAssembly.GetGlobalModuleType(); + TypeDesc owningTypeOfThunks = ((CompilerTypeSystemContext)key.TargetMethod.Context).GeneratedAssembly.GetGlobalModuleType(); return new DefaultInterfaceMethodImplementationInstantiationThunk(owningTypeOfThunks, key.TargetMethod, key.InterfaceIndex); } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs similarity index 97% rename from src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs index f44bf4b11cf8e2..738b43554182c8 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/TypeSystemContext.ValueTypeMethods.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs @@ -3,13 +3,14 @@ using System.Collections.Generic; +using Internal.TypeSystem; using Internal.IL.Stubs; using Debug = System.Diagnostics.Debug; -namespace Internal.TypeSystem +namespace ILCompiler { - public abstract partial class TypeSystemContext + partial class CompilerTypeSystemContext { private MethodDesc _objectEqualsMethod; @@ -154,7 +155,7 @@ private bool ComputeCanCompareValueTypeBits(MetadataType type) // Would be a suprise if this wasn't a valuetype. We checked ContainsGCPointers above. Debug.Assert(fieldType.IsValueType); - MethodDesc objectEqualsMethod = fieldType.Context._objectEqualsMethod; + MethodDesc objectEqualsMethod = ((CompilerTypeSystemContext)fieldType.Context)._objectEqualsMethod; // If the field overrides Equals, we can't use the fast helper because we need to call the method. if (fieldType.FindVirtualFunctionTargetMethodOnObjectType(objectEqualsMethod).OwningType == fieldType) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DelegateCreationInfo.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DelegateCreationInfo.cs index 0195f82d6c3692..dc6cd81fcccf5d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DelegateCreationInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DelegateCreationInfo.cs @@ -161,7 +161,7 @@ private DelegateCreationInfo(IMethodNode constructor, MethodDesc targetMethod, T /// public static DelegateCreationInfo Create(TypeDesc delegateType, MethodDesc targetMethod, NodeFactory factory, bool followVirtualDispatch) { - TypeSystemContext context = delegateType.Context; + CompilerTypeSystemContext context = factory.TypeSystemContext; DefType systemDelegate = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; int paramCountTargetMethod = targetMethod.Signature.Length; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs index 9f93ae3ea87a13..a7c4b27afd274f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs @@ -15,7 +15,7 @@ public abstract class MultiFileCompilationModuleGroup : CompilationModuleGroup { private HashSet _compilationModuleSet; - public MultiFileCompilationModuleGroup(TypeSystemContext context, IEnumerable compilationModuleSet) + public MultiFileCompilationModuleGroup(CompilerTypeSystemContext context, IEnumerable compilationModuleSet) { _compilationModuleSet = new HashSet(compilationModuleSet); @@ -94,7 +94,7 @@ public override bool CanHaveReferenceThroughImportTable /// public class MultiFileSharedCompilationModuleGroup : MultiFileCompilationModuleGroup { - public MultiFileSharedCompilationModuleGroup(TypeSystemContext context, IEnumerable compilationModuleSet) + public MultiFileSharedCompilationModuleGroup(CompilerTypeSystemContext context, IEnumerable compilationModuleSet) : base(context, compilationModuleSet) { } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index 3273d2cc58f567..33cefd92b42620 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -23,6 +23,144 @@ + + IL\DelegateInfo.cs + + + IL\Stubs\DelegateThunks.Sorting.cs + + + IL\Stubs\DynamicInvokeMethodThunk.cs + + + IL\Stubs\DynamicInvokeMethodThunk.Sorting.cs + + + IL\Stubs\EnumThunks.cs + + + IL\Stubs\EnumThunks.Sorting.cs + + + IL\Stubs\PInvokeLazyFixupField.cs + + + IL\Stubs\PInvokeLazyFixupField.Sorting.cs + + + IL\Stubs\StructMarshallingThunk.Sorting.cs + + + IL\Stubs\ValueTypeGetFieldHelperMethodOverride.cs + + + IL\Stubs\ValueTypeGetFieldHelperMethodOverride.Sorting.cs + + + TypeSystem\Interop\IL\InlineArrayType.Sorting.cs + + + Interop\IL\MarshalHelpers.cs + + + Interop\IL\MarshalHelpers.Aot.cs + + + Interop\IL\MarshalUtils.cs + + + Interop\IL\Marshaller.cs + + + Interop\IL\Marshaller.Aot.cs + + + TypeSystem\Interop\IL\NativeStructType.Sorting.cs + + + Interop\IL\PInvokeILEmitterConfiguration.cs + + + IL\Stubs\PInvokeILEmitter.cs + + + IL\Stubs\PInvokeILCodeStreams.cs + + + IL\Stubs\DebuggerSteppingHelpers.cs + + + IL\Stubs\CalliMarshallingMethodThunk.cs + + + IL\Stubs\CalliMarshallingMethodThunk.Mangling.cs + + + IL\Stubs\CalliMarshallingMethodThunk.Sorting.cs + + + IL\Stubs\DelegateMarshallingMethodThunk.cs + + + IL\Stubs\DelegateMarshallingMethodThunk.Mangling.cs + + + IL\Stubs\DelegateMarshallingMethodThunk.Sorting.cs + + + IL\Stubs\ForwardDelegateCreationThunk.cs + + + IL\Stubs\ForwardDelegateCreationThunk.Mangling.cs + + + IL\Stubs\ForwardDelegateCreationThunk.Sorting.cs + + + IL\Stubs\DelegateThunks.cs + + + IL\Stubs\StructMarshallingThunk.cs + + + IL\Stubs\StructMarshallingThunk.Mangling.cs + + + TypeSystem\Interop\IL\NativeStructType.cs + + + TypeSystem\Interop\IL\NativeStructType.Mangling.cs + + + TypeSystem\Interop\IL\PInvokeDelegateWrapper.cs + + + TypeSystem\Interop\IL\PInvokeDelegateWrapper.Mangling.cs + + + TypeSystem\Interop\IL\PInvokeDelegateWrapper.Sorting.cs + + + TypeSystem\Interop\IL\PInvokeDelegateWrapperConstructor.cs + + + TypeSystem\Interop\IL\PInvokeDelegateWrapperConstructor.Sorting.cs + + + TypeSystem\Interop\IL\InlineArrayType.cs + + + TypeSystem\Interop\InteropTypes.cs + + + TypeSystem\Interop\InteropStateManager.cs + + + TypeSystem\CodeGen\INonEmittableType.cs + + + TypeSystem\CodeGen\NativeStructType.CodeGen.cs + Compiler\Logging\CompilerGeneratedState.cs @@ -179,6 +317,12 @@ + + + + + + diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj index a638f7310d0523..e2703506aae36b 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj @@ -457,60 +457,12 @@ Ecma\CachingMetadataStringDecoder.cs - - IL\DelegateInfo.cs - - - IL\Stubs\DelegateThunks.Sorting.cs - - - IL\Stubs\DynamicInvokeMethodThunk.cs - - - IL\Stubs\DynamicInvokeMethodThunk.Sorting.cs - - - IL\Stubs\EnumThunks.cs - - - IL\Stubs\EnumThunks.Sorting.cs - - - IL\Stubs\PInvokeLazyFixupField.cs - - - IL\Stubs\PInvokeLazyFixupField.Sorting.cs - - - IL\Stubs\StructMarshallingThunk.Sorting.cs - - - IL\Stubs\ValueTypeGetFieldHelperMethodOverride.cs - - - IL\Stubs\ValueTypeGetFieldHelperMethodOverride.Sorting.cs - - - IL\TypeSystemContext.DelegateInfo.cs - - - IL\TypeSystemContext.DynamicInvoke.cs - - - IL\TypeSystemContext.GeneratedAssembly.cs - - - IL\TypeSystemContext.GeneratedAssembly.Sorting.cs - IL\EcmaMethodIL.cs IL\EcmaMethodIL.Symbols.cs - - IL\HelperExtensions.cs - IL\MethodIL.cs @@ -535,42 +487,6 @@ IL\ILOpcodeHelper.cs - - IL\TypeSystemContext.EnumMethods.cs - - - IL\TypeSystemContext.ValueTypeMethods.cs - - - TypeSystem\Interop\IL\InlineArrayType.Sorting.cs - - - Interop\IL\MarshalHelpers.cs - - - Interop\IL\MarshalHelpers.Aot.cs - - - Interop\IL\MarshalUtils.cs - - - Interop\IL\Marshaller.cs - - - Interop\IL\Marshaller.Aot.cs - - - TypeSystem\Interop\IL\NativeStructType.Sorting.cs - - - Interop\IL\PInvokeILEmitterConfiguration.cs - - - IL\Stubs\PInvokeILEmitter.cs - - - IL\Stubs\PInvokeILCodeStreams.cs - IL\Stubs\ILEmitter.cs @@ -586,48 +502,6 @@ IL\Stubs\PInvokeTargetNativeMethod.Sorting.cs - - IL\Stubs\DebuggerSteppingHelpers.cs - - - IL\Stubs\CalliMarshallingMethodThunk.cs - - - IL\Stubs\CalliMarshallingMethodThunk.Mangling.cs - - - IL\Stubs\CalliMarshallingMethodThunk.Sorting.cs - - - IL\Stubs\DelegateMarshallingMethodThunk.cs - - - IL\Stubs\DelegateMarshallingMethodThunk.Mangling.cs - - - IL\Stubs\DelegateMarshallingMethodThunk.Sorting.cs - - - IL\Stubs\ForwardDelegateCreationThunk.cs - - - IL\Stubs\ForwardDelegateCreationThunk.Mangling.cs - - - IL\Stubs\ForwardDelegateCreationThunk.Sorting.cs - - - IL\Stubs\DelegateThunks.cs - - - IL\Stubs\StructMarshallingThunk.cs - - - IL\Stubs\StructMarshallingThunk.Mangling.cs - - - TypeSystem\Interop\IL\NativeStructType.cs - TypeSystem\CodeGen\FieldDesc.Serialization.cs @@ -649,33 +523,6 @@ TypeSystem\Sorting\MethodForInstantiatedType.Sorting.cs - - TypeSystem\Interop\IL\NativeStructType.Mangling.cs - - - TypeSystem\Interop\IL\PInvokeDelegateWrapper.cs - - - TypeSystem\Interop\IL\PInvokeDelegateWrapper.Mangling.cs - - - TypeSystem\Interop\IL\PInvokeDelegateWrapper.Sorting.cs - - - TypeSystem\Interop\IL\PInvokeDelegateWrapperConstructor.cs - - - TypeSystem\Interop\IL\PInvokeDelegateWrapperConstructor.Sorting.cs - - - TypeSystem\Interop\IL\InlineArrayType.cs - - - TypeSystem\Interop\InteropTypes.cs - - - TypeSystem\Interop\InteropStateManager.cs - TypeSystem\Interop\FieldDesc.Interop.cs @@ -709,12 +556,6 @@ TypeSystem\Common\LocalVariableDefinition.cs - - TypeSystem\CodeGen\INonEmittableType.cs - - - TypeSystem\CodeGen\NativeStructType.CodeGen.cs - TypeSystem\RuntimeDetermined\ArrayType.RuntimeDetermined.cs diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index 007c3787df15f5..d9b7d79b012d3b 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -270,7 +270,7 @@ private ArgumentSyntax ParseCommandLine(string[] args) return argSyntax; } - private IReadOnlyCollection CreateInitializerList(TypeSystemContext context) + private IReadOnlyCollection CreateInitializerList(CompilerTypeSystemContext context) { List assembliesWithInitalizers = new List(); @@ -278,7 +278,7 @@ private IReadOnlyCollection CreateInitializerList(TypeSystemContext // any user code runs. foreach (string initAssemblyName in _initAssemblies) { - ModuleDesc assembly = context.ResolveAssembly(new AssemblyName(initAssemblyName)); + ModuleDesc assembly = context.ResolveAssembly(new AssemblyName(initAssemblyName), throwIfNotFound: true); assembliesWithInitalizers.Add(assembly); } From 7574e03e71d35827bfc08ece73492bd3df21c61d Mon Sep 17 00:00:00 2001 From: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> Date: Mon, 3 Jan 2022 13:43:26 +0100 Subject: [PATCH 10/97] [wasm][debugger] Add Browsable Attribute support. (#62045) * Description of DebuggerBrowsable behavior. * Added test for browse attributes. * Corrected typos in the doc. * Added Browse Never feature. Corrected Collapse test. ToDo: RootHidden. * Draft of RootHidden solution. * Added Array to test cases as it behaves differently than Collection. * Added name concatenation to make array/list elemetns in debug window unique. * Update docs/design/mono/debugger.md Co-authored-by: Ankit Jain * Applied PR review suggestions. * Added a reference to regular Browsable attribute behavior in .net. * Applied most of review suggestions. * Stopping GetFieldsValue early. * Remove unintentional change to the original code. * Do not skip fields that don't have browsable attributes. * Changing the expected behavior to match Console Application. EventHandlers are Browsable.Never by default. * Changed the place of checking if objetc is an array. * Update src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs Co-authored-by: Ankit Jain * Removed unused variables. * Removing space and unused import. * Partially addressed @radical comments. * Addressed the comment about extension instead of Union. * Removed string cultural vunerability. * Added Properties dictionary, the same as for fields. * Fixed the bug I made by using dynamc. * Applying @radical comments about refactoring. * Corrected typo. * Added tests for properties. * Draft of changes for properties handling - never and root hidden failing. * Fix for RootHidden properties. * Added tests for static fields decorated with Browsable. * Correct a typo. * Undo merge unintentional changes. * Changing expected behavior for MulticastDelegateTest - in Console Application EventHandler is Browsable.Never by default so we should not expect it to be visible in the debug window. * Removing not relevant changes created after merge with main. * Remove file added in merge with main. * Revert "Removing not relevant changes created after merge with main." This reverts commit b1acf8b546d1b95bea101290c25ec7f15cb78799. * Revert. * Revert revert. * One broken test for custom getter. * Ugly fix to make all the tests work. * Refactored JArray aggregation to Dictionary. * Better naming. * Remove not connected to PR file. * Applied @thaystg suggestions. * Removed comments. Co-authored-by: Ankit Jain --- docs/design/mono/debugger.md | 9 +- .../debugger/BrowserDebugProxy/DebugStore.cs | 70 +++- .../BrowserDebugProxy/MonoSDBHelper.cs | 304 ++++++++++++----- .../DebuggerTestSuite/DebuggerTestBase.cs | 2 - .../EvaluateOnCallFrameTests.cs | 121 +++++++ .../debugger/DebuggerTestSuite/MiscTests.cs | 1 - .../debugger-test/debugger-evaluate-test.cs | 313 ++++++++++++++++++ 7 files changed, 730 insertions(+), 90 deletions(-) diff --git a/docs/design/mono/debugger.md b/docs/design/mono/debugger.md index 3a3a2936b79eb4..2268d81bf1047b 100644 --- a/docs/design/mono/debugger.md +++ b/docs/design/mono/debugger.md @@ -18,4 +18,11 @@ Web Assembly Debugger supports usage of following attributes: - Stepping In/Over: results in an additional stepping need to proceed to the next line.

- __System.Diagnostics.DebuggerDisplay__ - __System.Diagnostics.DebuggerTypeProxy__ -- ... \ No newline at end of file +- __System.Diagnostics.DebuggerBrowsable__ ([doc](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerbrowsableattribute?view=net-6.0)) + - Collapsed - displayed normally. + - RootHidden: + - Simple type - not displayed in the debugger window. + - Collection / Array - the values of a collection are displayed in a flat view, using the naming convention: *rootName[idx]*. + + - Never - not displayed in the debugger window. + diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs index 6fb9b309d88e28..a50f486e052f6c 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs @@ -21,6 +21,8 @@ using System.IO.Compression; using System.Reflection; using System.Collections.Immutable; +using System.Diagnostics; +using Microsoft.VisualBasic; namespace Microsoft.WebAssembly.Diagnostics { @@ -475,14 +477,19 @@ public VarInfo[] GetLiveVarsAt(int offset) internal class TypeInfo { + private readonly ILogger logger; internal AssemblyInfo assembly; private TypeDefinition type; private List methods; internal int Token { get; } internal string Namespace { get; } - public TypeInfo(AssemblyInfo assembly, TypeDefinitionHandle typeHandle, TypeDefinition type) + public Dictionary DebuggerBrowsableFields = new(); + public Dictionary DebuggerBrowsableProperties = new(); + + public TypeInfo(AssemblyInfo assembly, TypeDefinitionHandle typeHandle, TypeDefinition type, ILogger logger) { + this.logger = logger; this.assembly = assembly; var metadataReader = assembly.asmMetadataReader; Token = MetadataTokens.GetToken(metadataReader, typeHandle); @@ -500,6 +507,63 @@ public TypeInfo(AssemblyInfo assembly, TypeDefinitionHandle typeHandle, TypeDefi FullName = Namespace + "." + Name; else FullName = Name; + + foreach (var field in type.GetFields()) + { + try + { + var fieldDefinition = metadataReader.GetFieldDefinition(field); + var fieldName = metadataReader.GetString(fieldDefinition.Name); + AppendToBrowsable(DebuggerBrowsableFields, fieldDefinition.GetCustomAttributes(), fieldName); + } + catch (Exception ex) + { + logger.LogDebug($"Failed to read browsable attributes of a field. ({ex.Message})"); + continue; + } + } + + foreach (var prop in type.GetProperties()) + { + try + { + var propDefinition = metadataReader.GetPropertyDefinition(prop); + var propName = metadataReader.GetString(propDefinition.Name); + AppendToBrowsable(DebuggerBrowsableProperties, propDefinition.GetCustomAttributes(), propName); + } + catch (Exception ex) + { + logger.LogDebug($"Failed to read browsable attributes of a property. ({ex.Message})"); + continue; + } + } + + void AppendToBrowsable(Dictionary dict, CustomAttributeHandleCollection customAttrs, string fieldName) + { + foreach (var cattr in customAttrs) + { + try + { + var ctorHandle = metadataReader.GetCustomAttribute(cattr).Constructor; + if (ctorHandle.Kind != HandleKind.MemberReference) + continue; + var container = metadataReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent; + var valueBytes = metadataReader.GetBlobBytes(metadataReader.GetCustomAttribute(cattr).Value); + var attributeName = metadataReader.GetString(metadataReader.GetTypeReference((TypeReferenceHandle)container).Name); + if (attributeName != "DebuggerBrowsableAttribute") + continue; + var state = (DebuggerBrowsableState)valueBytes[2]; + if (!Enum.IsDefined(typeof(DebuggerBrowsableState), state)) + continue; + dict.Add(fieldName, state); + break; + } + catch + { + continue; + } + } + } } public TypeInfo(AssemblyInfo assembly, string name) @@ -515,7 +579,6 @@ public TypeInfo(AssemblyInfo assembly, string name) public override string ToString() => "TypeInfo('" + FullName + "')"; } - internal class AssemblyInfo { private static int next_id; @@ -652,7 +715,7 @@ SourceFile FindSource(DocumentHandle doc, int rowid, string documentName) { var typeDefinition = asmMetadataReader.GetTypeDefinition(type); - var typeInfo = new TypeInfo(this, type, typeDefinition); + var typeInfo = new TypeInfo(this, type, typeDefinition, logger); TypesByName[typeInfo.FullName] = typeInfo; TypesByToken[typeInfo.Token] = typeInfo; if (pdbMetadataReader != null) @@ -680,7 +743,6 @@ SourceFile FindSource(DocumentHandle doc, int rowid, string documentName) } } } - } private void ProcessSourceLink() diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs index 35d1ef4fceba12..80eaed9daf6948 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs @@ -16,6 +16,7 @@ using System.Reflection; using System.Text; using System.Runtime.CompilerServices; +using System.Diagnostics; namespace Microsoft.WebAssembly.Diagnostics { @@ -2316,128 +2317,247 @@ public async Task GetValuesFromDebuggerProxyAttribute(int objectId, int public async Task GetObjectValues(int objectId, GetObjectCommandOptions getCommandType, CancellationToken token) { - var typeId = await GetTypeIdFromObject(objectId, true, token); + var typeIdsIncludingParents = await GetTypeIdFromObject(objectId, true, token); if (!getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerDisplayAttribute)) { - var debuggerProxy = await GetValuesFromDebuggerProxyAttribute(objectId, typeId[0], token); + var debuggerProxy = await GetValuesFromDebuggerProxyAttribute(objectId, typeIdsIncludingParents[0], token); if (debuggerProxy != null) return debuggerProxy; } - var className = await GetTypeName(typeId[0], token); - JArray ret = new JArray(); if (await IsDelegate(objectId, token)) { var description = await GetDelegateMethodDescription(objectId, token); - - var obj = JObject.FromObject(new { - value = new - { - type = "symbol", - value = description, - description - }, - name = "Target" - }); - ret.Add(obj); - return ret; + return new JArray( + JObject.FromObject(new + { + value = new + { + type = "symbol", + value = description, + description + }, + name = "Target" + })); } - for (int i = 0; i < typeId.Count; i++) + + var objects = new Dictionary(); + for (int i = 0; i < typeIdsIncludingParents.Count; i++) { + int typeId = typeIdsIncludingParents[i]; + // 0th id is for the object itself, and then its parents + bool isOwn = i == 0; + if (!getCommandType.HasFlag(GetObjectCommandOptions.AccessorPropertiesOnly)) { - className = await GetTypeName(typeId[i], token); - var fields = await GetTypeFields(typeId[i], token); - if (getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerProxyAttribute)) - fields = fields.Where(field => field.IsPublic).ToList(); - JArray objectFields = new JArray(); - - using var commandParamsWriter = new MonoBinaryWriter(); - commandParamsWriter.Write(objectId); - commandParamsWriter.Write(fields.Count); - foreach (var field in fields) - { - commandParamsWriter.Write(field.Id); - } + var fields = await GetTypeFields(typeId, token); + var (collapsedFields, rootHiddenFields) = await FilterFieldsByDebuggerBrowsable(fields, typeId, token); - using var retDebuggerCmdReader = await SendDebuggerAgentCommand(CmdObject.RefGetValues, commandParamsWriter, token); + var collapsedFieldsValues = await GetFieldsValues(collapsedFields, isOwn); + var hiddenFieldsValues = await GetFieldsValues(rootHiddenFields, isOwn, isRootHidden: true); - foreach (var field in fields) - { - long initialPos = retDebuggerCmdReader.BaseStream.Position; - int valtype = retDebuggerCmdReader.ReadByte(); - retDebuggerCmdReader.BaseStream.Position = initialPos; - var fieldValue = await CreateJObjectForVariableValue(retDebuggerCmdReader, field.Name, i == 0, field.TypeId, getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerDisplayAttribute), token); - if (ret.Where(attribute => attribute["name"].Value().Equals(fieldValue["name"].Value())).Any()) { - continue; - } - if (getCommandType.HasFlag(GetObjectCommandOptions.WithSetter)) - { - var command_params_writer_to_set = new MonoBinaryWriter(); - command_params_writer_to_set.Write(objectId); - command_params_writer_to_set.Write(1); - command_params_writer_to_set.Write(field.Id); - var (data, length) = command_params_writer_to_set.ToBase64(); - - fieldValue.Add("set", JObject.FromObject(new { - commandSet = CommandSet.ObjectRef, - command = CmdObject.RefSetValues, - buffer = data, - valtype, - length = length - })); - } - objectFields.Add(fieldValue); - } - ret = new JArray(ret.Union(objectFields)); + objects.TryAddRange(collapsedFieldsValues); + objects.TryAddRange(hiddenFieldsValues); } if (!getCommandType.HasFlag(GetObjectCommandOptions.WithProperties)) - return ret; + return new JArray(objects.Values); using var commandParamsObjWriter = new MonoBinaryWriter(); commandParamsObjWriter.WriteObj(new DotnetObjectId("object", objectId), this); - var props = await CreateJArrayForProperties(typeId[i], commandParamsObjWriter.GetParameterBuffer(), ret, getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerProxyAttribute), $"dotnet:object:{objectId}", i == 0, token); - ret = new JArray(ret.Union(props)); + var props = await CreateJArrayForProperties( + typeId, + commandParamsObjWriter.GetParameterBuffer(), + new JArray(objects.Values), + getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerProxyAttribute), + $"dotnet:object:{objectId}", + i == 0, + token); + var properties = await GetProperties(props, typeId, token); + objects.TryAddRange(properties); // ownProperties // Note: ownProperties should mean that we return members of the klass itself, // but we are going to ignore that here, because otherwise vscode/chrome don't // seem to ask for inherited fields at all. //if (ownProperties) - //break; + //break; /*if (accessorPropertiesOnly) break;*/ } if (getCommandType.HasFlag(GetObjectCommandOptions.AccessorPropertiesOnly)) { - var retAfterRemove = new JArray(); - List> allFields = new List>(); - for (int i = 0; i < typeId.Count; i++) + var ownId = typeIdsIncludingParents[0]; + var ownFields = await GetTypeFields(ownId, token); + + var parentFields = new List(); + for (int i = 1; i < typeIdsIncludingParents.Count; i++) + parentFields.AddRange(await GetTypeFields(typeIdsIncludingParents[i], token)); + + var ownDuplicatedFields = ownFields.Where(field => objects.Any(obj => + field.Name.Equals(obj.Key))); + + var parentDuplicatedFields = parentFields.Where(field => objects.Any(obj => + field.Name.Equals(obj.Key) && + (obj.Value["isOwn"] == null || + !obj.Value["isOwn"].Value()))); + + foreach (var duplicate in ownDuplicatedFields) + objects.Remove(duplicate.Name); + foreach (var duplicate in parentDuplicatedFields) + objects.Remove(duplicate.Name); + } + return new JArray(objects.Values); + + async Task AppendRootHiddenChildren(JObject root, JArray expandedCollection) + { + if (!DotnetObjectId.TryParse(root?["value"]?["objectId"]?.Value(), out DotnetObjectId rootHiddenObjectId)) + return; + + var resultValue = new JArray(); + // collections require extracting items to get inner values; items are of array type + // arrays have "subtype": "array" field, collections don't + var subtype = root?["value"]?["subtype"]; + var rootHiddenObjectIdInt = rootHiddenObjectId.Value; + if (subtype == null || subtype?.Value() != "array") { - var fields = await GetTypeFields(typeId[i], token); - allFields.Add(fields); + resultValue = await GetObjectValues(rootHiddenObjectIdInt, getCommandType, token); + DotnetObjectId.TryParse(resultValue[0]?["value"]?["objectId"]?.Value(), out DotnetObjectId objectId2); + rootHiddenObjectIdInt = objectId2.Value; + } + resultValue = await GetArrayValues(rootHiddenObjectIdInt, token); + + // root hidden item name has to be unique, so we concatenate the root's name to it + foreach (var item in resultValue) + { + item["name"] = string.Concat(root["name"], "[", item["name"], "]"); + expandedCollection.Add(item); + } + } + + async Task GetFieldsValues(List fields, bool isOwn, bool isRootHidden = false) + { + JArray objFields = new JArray(); + if (fields.Count == 0) + return objFields; + + if (getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerProxyAttribute)) + fields = fields.Where(field => field.IsPublic).ToList(); + + using var commandParamsWriter = new MonoBinaryWriter(); + commandParamsWriter.Write(objectId); + commandParamsWriter.Write(fields.Count); + foreach (var field in fields) + commandParamsWriter.Write(field.Id); + var retDebuggerCmdReader = await SendDebuggerAgentCommand(CmdObject.RefGetValues, commandParamsWriter, token); + + foreach (var field in fields) + { + long initialPos = retDebuggerCmdReader.BaseStream.Position; + int valtype = retDebuggerCmdReader.ReadByte(); + retDebuggerCmdReader.BaseStream.Position = initialPos; + var fieldValue = await CreateJObjectForVariableValue(retDebuggerCmdReader, field.Name, isOwn: isOwn, field.TypeId, getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerDisplayAttribute), token); + if (objects.Where((k, v) => k.Equals(fieldValue["name"].Value())).Any()) + continue; + if (getCommandType.HasFlag(GetObjectCommandOptions.WithSetter)) + { + var command_params_writer_to_set = new MonoBinaryWriter(); + command_params_writer_to_set.Write(objectId); + command_params_writer_to_set.Write(1); + command_params_writer_to_set.Write(field.Id); + var (data, length) = command_params_writer_to_set.ToBase64(); + + fieldValue.Add("set", JObject.FromObject(new + { + commandSet = CommandSet.ObjectRef, + command = CmdObject.RefSetValues, + buffer = data, + valtype, + length = length + })); + } + if (!isRootHidden) + { + objFields.Add(fieldValue); + continue; + } + await AppendRootHiddenChildren(fieldValue, objFields); } - foreach (var item in ret) + return objFields; + } + + async Task<(List, List)> FilterFieldsByDebuggerBrowsable(List fields, int typeId, CancellationToken token) + { + if (fields.Count == 0) + return (fields, new List()); + + var typeInfo = await GetTypeInfo(typeId, token); + var typeFieldsBrowsableInfo = typeInfo?.Info?.DebuggerBrowsableFields; + var typeProperitesBrowsableInfo = typeInfo?.Info?.DebuggerBrowsableProperties; + if (typeFieldsBrowsableInfo == null || typeFieldsBrowsableInfo.Count == 0) + return (fields, new List()); + + var collapsedFields = new List(); + var rootHiddenFields = new List(); + foreach (var field in fields) { - bool foundField = false; - for (int j = 0 ; j < allFields.Count; j++) + if (!typeFieldsBrowsableInfo.TryGetValue(field.Name, out DebuggerBrowsableState? state)) { - foreach (var field in allFields[j]) + if (!typeProperitesBrowsableInfo.TryGetValue(field.Name, out DebuggerBrowsableState? propState)) { - if (field.Name.Equals(item["name"].Value())) { - if (item["isOwn"] == null || (item["isOwn"].Value() && j == 0) || !item["isOwn"].Value()) - foundField = true; - break; - } + collapsedFields.Add(field); + continue; } - if (foundField) + state = propState; + } + switch (state) + { + case DebuggerBrowsableState.Never: + break; + case DebuggerBrowsableState.RootHidden: + var typeName = await GetTypeName(field.TypeId, token); + if (typeName.StartsWith("System.Collections.Generic", StringComparison.Ordinal) || + typeName.EndsWith("[]", StringComparison.Ordinal)) + rootHiddenFields.Add(field); + break; + case DebuggerBrowsableState.Collapsed: + collapsedFields.Add(field); break; + default: + throw new NotImplementedException($"DebuggerBrowsableState: {state}"); } - if (!foundField) { - retAfterRemove.Add(item); + } + return (collapsedFields, rootHiddenFields); + } + + async Task GetProperties(JArray props, int typeId, CancellationToken token) + { + var typeInfo = await GetTypeInfo(typeId, token); + var typeProperitesBrowsableInfo = typeInfo?.Info?.DebuggerBrowsableProperties; + var regularProps = new JArray(); + foreach (var p in props) + { + if (!typeProperitesBrowsableInfo.TryGetValue(p["name"].Value(), out DebuggerBrowsableState? state)) + { + regularProps.Add(p); + continue; + } + switch (state) + { + case DebuggerBrowsableState.Never: + break; + case DebuggerBrowsableState.RootHidden: + DotnetObjectId rootObjId; + DotnetObjectId.TryParse(p["get"]["objectId"].Value(), out rootObjId); + var rootObject = await InvokeMethodInObject(rootObjId.Value, rootObjId.SubValue, p["name"].Value(), token); + await AppendRootHiddenChildren(rootObject, regularProps); + break; + case DebuggerBrowsableState.Collapsed: + regularProps.Add(p); + break; + default: + throw new NotImplementedException($"DebuggerBrowsableState: {state}"); } } - ret = retAfterRemove; + return regularProps; } - return ret; } public async Task GetObjectProxy(int objectId, CancellationToken token) @@ -2524,4 +2644,24 @@ public async Task SetVariableValue(int thread_id, int frame_id, int varId, return true; } } + + internal static class HelperExtensions + { + public static void AddRange(this JArray arr, JArray addedArr) + { + foreach (var item in addedArr) + arr.Add(item); + } + + public static void TryAddRange(this Dictionary dict, JArray addedArr) + { + foreach (var item in addedArr) + { + var key = item["name"]?.Value(); + if (key == null) + continue; + dict.TryAdd(key, item); + } + } + } } diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs index f22b4ae3196bef..f78f013e8a68e6 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs @@ -670,10 +670,8 @@ internal async Task CheckProps(JToken actual, object exp_o, string label, int nu if (exp_i != null) await CheckValue(act_i["value"], exp_i, $"{label}-{i}th value"); } - return; } - // Not an array var exp = exp_o as JObject; if (exp == null) diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs index 80bef3eb092578..14a786c040b4e3 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs @@ -854,6 +854,127 @@ await RuntimeEvaluateAndCheck( ("\"15\"\n//comment as vs does\n", TString("15")), ("\"15\"", TString("15"))); }); + + [Theory] + [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsNone", "testFieldsNone", 10)] + [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesNone", "testPropertiesNone", 10)] + [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesNone", "testPropertiesNone", 5, true)] + public async Task EvaluateBrowsableNone(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( + $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", + $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", + wait_for_event_fn: async (pause_location) => + { + var id = pause_location["callFrames"][0]["callFrameId"].Value(); + + var (testNone, _) = await EvaluateOnCallFrame(id, localVarName); + await CheckValue(testNone, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testNone)); + var testNoneProps = await GetProperties(testNone["objectId"]?.Value()); + + if (isCustomGetter) + await CheckProps(testNoneProps, new + { + list = TGetter("list", TObject("System.Collections.Generic.List", description: "Count = 2")), + array = TGetter("array", TObject("int[]", description: "int[2]")), + text = TGetter("text", TString("text")) + }, "testNoneProps#1"); + else + await CheckProps(testNoneProps, new + { + list = TObject("System.Collections.Generic.List", description: "Count = 2"), + array = TObject("int[]", description: "int[2]"), + text = TString("text") + }, "testNoneProps#1"); + }); + + [Theory] + [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsNever", "testFieldsNever", 10)] + [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 10)] + [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsNever", "testFieldsNever", 10)] + [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 10)] + [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesNever", "testPropertiesNever", 5)] + public async Task EvaluateBrowsableNever(string outerClassName, string className, string localVarName, int breakLine) => await CheckInspectLocalsAtBreakpointSite( + $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", + $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", + wait_for_event_fn: async (pause_location) => + { + var id = pause_location["callFrames"][0]["callFrameId"].Value(); + + var (testNever, _) = await EvaluateOnCallFrame(id, localVarName); + await CheckValue(testNever, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testNever)); + var testNeverProps = await GetProperties(testNever["objectId"]?.Value()); + await CheckProps(testNeverProps, new + { + }, "testNeverProps#1"); + }); + + [Theory] + [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsCollapsed", "testFieldsCollapsed", 10)] + [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 10)] + [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsCollapsed", "testFieldsCollapsed", 10)] + [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 10)] + [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesCollapsed", "testPropertiesCollapsed", 5, true)] + public async Task EvaluateBrowsableCollapsed(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( + $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", + $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", + wait_for_event_fn: async (pause_location) => + { + var id = pause_location["callFrames"][0]["callFrameId"].Value(); + + var (testCollapsed, _) = await EvaluateOnCallFrame(id, localVarName); + await CheckValue(testCollapsed, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testCollapsed)); + var testCollapsedProps = await GetProperties(testCollapsed["objectId"]?.Value()); + if (isCustomGetter) + await CheckProps(testCollapsedProps, new + { + listCollapsed = TGetter("listCollapsed", TObject("System.Collections.Generic.List", description: "Count = 2")), + arrayCollapsed = TGetter("arrayCollapsed", TObject("int[]", description: "int[2]")), + textCollapsed = TGetter("textCollapsed", TString("textCollapsed")) + }, "testCollapsedProps#1"); + else + await CheckProps(testCollapsedProps, new + { + listCollapsed = TObject("System.Collections.Generic.List", description: "Count = 2"), + arrayCollapsed = TObject("int[]", description: "int[2]"), + textCollapsed = TString("textCollapsed") + }, "testCollapsedProps#1"); + }); + + [Theory] + [InlineData("EvaluateBrowsableProperties", "TestEvaluateFieldsRootHidden", "testFieldsRootHidden", 10)] + [InlineData("EvaluateBrowsableProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 10)] + [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluateFieldsRootHidden", "testFieldsRootHidden", 10)] + [InlineData("EvaluateBrowsableStaticProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 10)] + [InlineData("EvaluateBrowsableCustomProperties", "TestEvaluatePropertiesRootHidden", "testPropertiesRootHidden", 5, true)] + public async Task EvaluateBrowsableRootHidden(string outerClassName, string className, string localVarName, int breakLine, bool isCustomGetter = false) => await CheckInspectLocalsAtBreakpointSite( + $"DebuggerTests.{outerClassName}", "Evaluate", breakLine, "Evaluate", + $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test] DebuggerTests.{outerClassName}:Evaluate'); 1 }})", + wait_for_event_fn: async (pause_location) => + { + var id = pause_location["callFrames"][0]["callFrameId"].Value(); + + var (testRootHidden, _) = await EvaluateOnCallFrame(id, localVarName); + await CheckValue(testRootHidden, TObject($"DebuggerTests.{outerClassName}.{className}"), nameof(testRootHidden)); + var testRootHiddenProps = await GetProperties(testRootHidden["objectId"]?.Value()); + var (refList, _) = await EvaluateOnCallFrame(id, "testPropertiesNone.list"); + var refListProp = await GetProperties(refList["objectId"]?.Value()); + var refListElementsProp = await GetProperties(refListProp[0]["value"]["objectId"]?.Value()); + var (refArray, _) = await EvaluateOnCallFrame(id, "testPropertiesNone.array"); + var refArrayProp = await GetProperties(refArray["objectId"]?.Value()); + + //in Console App names are in [] + //adding variable name to make elements unique + foreach (var item in refArrayProp) + { + item["name"] = string.Concat("arrayRootHidden[", item["name"], "]"); + } + foreach (var item in refListElementsProp) + { + item["name"] = string.Concat("listRootHidden[", item["name"], "]"); + } + // Console.WriteLine(testRootHiddenProps); + var mergedRefItems = new JArray(refListElementsProp.Union(refArrayProp)); + Assert.Equal(mergedRefItems, testRootHiddenProps); + }); [Fact] public async Task EvaluateStaticAttributeInAssemblyNotRelatedButLoaded() => await CheckInspectLocalsAtBreakpointSite( diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs index 398d640c0a01c8..22b8b165159885 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs @@ -654,7 +654,6 @@ public async Task MulticastDelegateTest() => await CheckInspectLocalsAtBreakpoin var this_props = await GetObjectOnLocals(frame_locals, "this"); await CheckProps(this_props, new { - TestEvent = TSymbol("System.EventHandler"), Delegate = TSymbol("System.MulticastDelegate") }, "this_props"); }); diff --git a/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs b/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs index f27888c17200cc..b0ff3f95ba3de3 100644 --- a/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs +++ b/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs @@ -504,6 +504,319 @@ public static void EvaluateLocals() } } + public static class EvaluateBrowsableProperties + { + public class TestEvaluateFieldsNone + { + public List list = new List() { 1, 2 }; + public int[] array = new int[] { 11, 22 }; + public string text = "text"; + } + + public class TestEvaluatePropertiesNone + { + public List list { get; set; } + public int[] array { get; set; } + public string text { get; set; } + + public TestEvaluatePropertiesNone() + { + list = new List() { 1, 2 }; + array = new int[] { 11, 22 }; + text = "text"; + } + } + + public class TestEvaluateFieldsNever + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public List listNever = new List() { 1, 2 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public int[] arrayNever = new int[] { 11, 22 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public string textNever = "textNever"; + } + + public class TestEvaluatePropertiesNever + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public List listNever { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public int[] arrayNever { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public string textNever { get; set; } + + public TestEvaluatePropertiesNever() + { + listNever = new List() { 1, 2 }; + arrayNever = new int[] { 11, 22 }; + textNever = "textNever"; + } + } + + public class TestEvaluateFieldsCollapsed + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public List listCollapsed = new List() { 1, 2 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public int[] arrayCollapsed = new int[] { 11, 22 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public string textCollapsed = "textCollapsed"; + } + + public class TestEvaluatePropertiesCollapsed + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public List listCollapsed { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public int[] arrayCollapsed { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public string textCollapsed { get; set; } + + public TestEvaluatePropertiesCollapsed() + { + listCollapsed = new List() { 1, 2 }; + arrayCollapsed = new int[] { 11, 22 }; + textCollapsed = "textCollapsed"; + } + } + + public class TestEvaluateFieldsRootHidden + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public List listRootHidden = new List() { 1, 2 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public int[] arrayRootHidden = new int[] { 11, 22 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public string textRootHidden = "textRootHidden"; + } + + public class TestEvaluatePropertiesRootHidden + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public List listRootHidden { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public int[] arrayRootHidden { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public string textRootHidden { get; set; } + + public TestEvaluatePropertiesRootHidden() + { + listRootHidden = new List() { 1, 2 }; + arrayRootHidden = new int[] { 11, 22 }; + textRootHidden = "textRootHidden"; + } + } + + public static void Evaluate() + { + var testFieldsNone = new TestEvaluateFieldsNone(); + var testFieldsNever = new TestEvaluateFieldsNever(); + var testFieldsCollapsed = new TestEvaluateFieldsCollapsed(); + var testFieldsRootHidden = new TestEvaluateFieldsRootHidden(); + + var testPropertiesNone = new TestEvaluatePropertiesNone(); + var testPropertiesNever = new TestEvaluatePropertiesNever(); + var testPropertiesCollapsed = new TestEvaluatePropertiesCollapsed(); + var testPropertiesRootHidden = new TestEvaluatePropertiesRootHidden(); + } + } + + public static class EvaluateBrowsableStaticProperties + { + public class TestEvaluateFieldsNone + { + public static List list = new List() { 1, 2 }; + public static int[] array = new int[] { 11, 22 }; + public static string text = "text"; + } + + public class TestEvaluatePropertiesNone + { + public static List list { get; set; } + public static int[] array { get; set; } + public static string text { get; set; } + + public TestEvaluatePropertiesNone() + { + list = new List() { 1, 2 }; + array = new int[] { 11, 22 }; + text = "text"; + } + } + + public class TestEvaluateFieldsNever + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public static List listNever = new List() { 1, 2 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public static int[] arrayNever = new int[] { 11, 22 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public static string textNever = "textNever"; + } + + public class TestEvaluatePropertiesNever + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public static List listNever { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public static int[] arrayNever { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public static string textNever { get; set; } + + public TestEvaluatePropertiesNever() + { + listNever = new List() { 1, 2 }; + arrayNever = new int[] { 11, 22 }; + textNever = "textNever"; + } + } + + public class TestEvaluateFieldsCollapsed + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public static List listCollapsed = new List() { 1, 2 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public static int[] arrayCollapsed = new int[] { 11, 22 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public static string textCollapsed = "textCollapsed"; + } + + public class TestEvaluatePropertiesCollapsed + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public static List listCollapsed { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public static int[] arrayCollapsed { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public static string textCollapsed { get; set; } + + public TestEvaluatePropertiesCollapsed() + { + listCollapsed = new List() { 1, 2 }; + arrayCollapsed = new int[] { 11, 22 }; + textCollapsed = "textCollapsed"; + } + } + + public class TestEvaluateFieldsRootHidden + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public static List listRootHidden = new List() { 1, 2 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public static int[] arrayRootHidden = new int[] { 11, 22 }; + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public static string textRootHidden = "textRootHidden"; + } + + public class TestEvaluatePropertiesRootHidden + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public static List listRootHidden { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public static int[] arrayRootHidden { get; set; } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public static string textRootHidden { get; set; } + + public TestEvaluatePropertiesRootHidden() + { + listRootHidden = new List() { 1, 2 }; + arrayRootHidden = new int[] { 11, 22 }; + textRootHidden = "textRootHidden"; + } + } + + public static void Evaluate() + { + var testFieldsNone = new TestEvaluateFieldsNone(); + var testFieldsNever = new TestEvaluateFieldsNever(); + var testFieldsCollapsed = new TestEvaluateFieldsCollapsed(); + var testFieldsRootHidden = new TestEvaluateFieldsRootHidden(); + + var testPropertiesNone = new TestEvaluatePropertiesNone(); + var testPropertiesNever = new TestEvaluatePropertiesNever(); + var testPropertiesCollapsed = new TestEvaluatePropertiesCollapsed(); + var testPropertiesRootHidden = new TestEvaluatePropertiesRootHidden(); + } + } + + public static class EvaluateBrowsableCustomProperties + { + public class TestEvaluatePropertiesNone + { + public List list { get { return new List() { 1, 2 }; } } + public int[] array { get { return new int[] { 11, 22 }; } } + public string text { get { return "text"; } } + } + + public class TestEvaluatePropertiesNever + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public List listNever { get { return new List() { 1, 2 }; } } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public int[] arrayNever { get { return new int[] { 11, 22 }; } } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] + public string textNever { get { return "textNever"; } } + } + + public class TestEvaluatePropertiesCollapsed + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public List listCollapsed { get { return new List() { 1, 2 }; } } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public int[] arrayCollapsed { get { return new int[] { 11, 22 }; } } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Collapsed)] + public string textCollapsed { get { return "textCollapsed"; } } + } + + public class TestEvaluatePropertiesRootHidden + { + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public List listRootHidden { get { return new List() { 1, 2 }; } } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public int[] arrayRootHidden { get { return new int[] { 11, 22 }; } } + + [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] + public string textRootHidden { get { return "textRootHidden"; } } + } + + public static void Evaluate() + { + var testPropertiesNone = new TestEvaluatePropertiesNone(); + var testPropertiesNever = new TestEvaluatePropertiesNever(); + var testPropertiesCollapsed = new TestEvaluatePropertiesCollapsed(); + var testPropertiesRootHidden = new TestEvaluatePropertiesRootHidden(); + } + } } namespace DebuggerTestsV2 From 55fecfbc201dc789d71c0903e04f2a779212c671 Mon Sep 17 00:00:00 2001 From: Andrii Kurdiumov Date: Mon, 3 Jan 2022 19:54:45 +0600 Subject: [PATCH 11/97] Fix issues in PAL (#62625) --- src/coreclr/pal/src/file/file.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/coreclr/pal/src/file/file.cpp b/src/coreclr/pal/src/file/file.cpp index 59cfd07fbdbdd8..71f35f810bcf19 100644 --- a/src/coreclr/pal/src/file/file.cpp +++ b/src/coreclr/pal/src/file/file.cpp @@ -1617,7 +1617,7 @@ GetFileAttributesExW( attr_data = (LPWIN32_FILE_ATTRIBUTE_DATA)lpFileInformation; attr_data->dwFileAttributes = GetFileAttributesW(lpFileName); - /* assume that GetFileAttributes will call SetLastError appropriately */ + /* assume that GetFileAttributesW will call SetLastError appropriately */ if ( attr_data->dwFileAttributes == (DWORD)-1 ) { goto done; @@ -1753,7 +1753,7 @@ SetFileAttributesA( new_mode = stat_data.st_mode; TRACE("st_mode is %#x\n", new_mode); - /* if we can't do GetFileAttributes on it, don't do SetFileAttributes */ + /* if we can't do GetFileAttributesA on it, don't do SetFileAttributesA */ if ( !(new_mode & S_IFREG) && !(new_mode & S_IFDIR) ) { ERROR("Not a regular file or directory, S_IFMT is %#x\n", @@ -3542,10 +3542,10 @@ CopyFileA( } /* Need to preserve the file attributes */ - dwSrcFileAttributes = GetFileAttributes(lpExistingFileName); + dwSrcFileAttributes = GetFileAttributesA(lpExistingFileName); if (dwSrcFileAttributes == 0xffffffff) { - ERROR("GetFileAttributes failed for %s\n", lpExistingFileName); + ERROR("GetFileAttributesA failed for %s\n", lpExistingFileName); goto done; } From 3cde4dc780b4a727bdaf8a6129d8f776649fcf06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 4 Jan 2022 01:28:03 +0900 Subject: [PATCH 12/97] Last ILCompiler.TypeSystem <-> ILCompiler.TypeSystem.ReadyToRun diff (#63281) After this and dotnet/runtime#63280 there will be no differences between ILCompiler.TypeSystem and ILCompiler.TypeSystem.ReadyToRun and we can unify them. --- .../TypeSystem/Aot/TargetDetails.Aot.cs | 16 -- .../Utilities/GCPointerMap.Algorithm.cs | 68 ++++++++ .../Common/Utilities/GCPointerMap.Aot.cs | 78 --------- .../CallingConventionConverterKey.cs | 152 ++++++++++++++++ .../FatFunctionPointerNode.cs | 2 +- .../ILCompiler.TypeSystem.csproj | 7 - .../Utilities/UniqueTypeNameFormatter.cs | 164 ------------------ 7 files changed, 221 insertions(+), 266 deletions(-) delete mode 100644 src/coreclr/tools/Common/TypeSystem/Aot/TargetDetails.Aot.cs delete mode 100644 src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Aot.cs delete mode 100644 src/coreclr/tools/aot/ILCompiler.TypeSystem/Utilities/UniqueTypeNameFormatter.cs diff --git a/src/coreclr/tools/Common/TypeSystem/Aot/TargetDetails.Aot.cs b/src/coreclr/tools/Common/TypeSystem/Aot/TargetDetails.Aot.cs deleted file mode 100644 index 9e9704555724d4..00000000000000 --- a/src/coreclr/tools/Common/TypeSystem/Aot/TargetDetails.Aot.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace Internal.TypeSystem -{ - // Extension to TargetDetails related to Aot - partial class TargetDetails - { - /// - /// Offset by which fat function pointers are shifted to distinguish them - /// from real function pointers. - /// WebAssembly uses index tables, not addresses for function pointers, so the lower bits are not free to use. - /// - public int FatFunctionPointerOffset => Architecture == TargetArchitecture.Wasm32 ? 1 << 31 : 2; - } -} diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs index af5938677a4b4d..b4fc577fb7bb6a 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs @@ -51,5 +51,73 @@ private static void FromInstanceLayoutHelper(ref GCPointerMapBuilder builder, De } } } + + /// + /// Computes the GC pointer map of the GC static region of the type. + /// + public static GCPointerMap FromStaticLayout(DefType type) + { + GCPointerMapBuilder builder = new GCPointerMapBuilder(type.GCStaticFieldSize.AsInt, type.Context.Target.PointerSize); + + foreach (FieldDesc field in type.GetFields()) + { + if (!field.IsStatic || field.HasRva || field.IsLiteral + || field.IsThreadStatic || !field.HasGCStaticBase) + continue; + + TypeDesc fieldType = field.FieldType; + if (fieldType.IsGCPointer) + { + builder.MarkGCPointer(field.Offset.AsInt); + } + else + { + Debug.Assert(fieldType.IsValueType); + var fieldDefType = (DefType)fieldType; + if (fieldDefType.ContainsGCPointers) + { + GCPointerMapBuilder innerBuilder = + builder.GetInnerBuilder(field.Offset.AsInt, fieldDefType.InstanceByteCount.AsInt); + FromInstanceLayoutHelper(ref innerBuilder, fieldDefType); + } + } + } + + Debug.Assert(builder.ToGCMap().Size * type.Context.Target.PointerSize >= type.GCStaticFieldSize.AsInt); + return builder.ToGCMap(); + } + + /// + /// Computes the GC pointer map of the thread static region of the type. + /// + public static GCPointerMap FromThreadStaticLayout(DefType type) + { + GCPointerMapBuilder builder = new GCPointerMapBuilder(type.ThreadGcStaticFieldSize.AsInt, type.Context.Target.PointerSize); + + foreach (FieldDesc field in type.GetFields()) + { + if (!field.IsStatic || field.HasRva || field.IsLiteral || !field.IsThreadStatic || !field.HasGCStaticBase) + continue; + + TypeDesc fieldType = field.FieldType; + if (fieldType.IsGCPointer) + { + builder.MarkGCPointer(field.Offset.AsInt); + } + else if (fieldType.IsValueType) + { + var fieldDefType = (DefType)fieldType; + if (fieldDefType.ContainsGCPointers) + { + GCPointerMapBuilder innerBuilder = + builder.GetInnerBuilder(field.Offset.AsInt, fieldDefType.InstanceByteCount.AsInt); + FromInstanceLayoutHelper(ref innerBuilder, fieldDefType); + } + } + } + + Debug.Assert(builder.ToGCMap().Size * type.Context.Target.PointerSize >= type.ThreadGcStaticFieldSize.AsInt); + return builder.ToGCMap(); + } } } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Aot.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Aot.cs deleted file mode 100644 index 4738cde90c6921..00000000000000 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Aot.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Debug = System.Diagnostics.Debug; - -namespace Internal.TypeSystem -{ - partial struct GCPointerMap - { - /// - /// Computes the GC pointer map of the GC static region of the type. - /// - public static GCPointerMap FromStaticLayout(DefType type) - { - GCPointerMapBuilder builder = new GCPointerMapBuilder(type.GCStaticFieldSize.AsInt, type.Context.Target.PointerSize); - - foreach (FieldDesc field in type.GetFields()) - { - if (!field.IsStatic || field.HasRva || field.IsLiteral - || field.IsThreadStatic || !field.HasGCStaticBase) - continue; - - TypeDesc fieldType = field.FieldType; - if (fieldType.IsGCPointer) - { - builder.MarkGCPointer(field.Offset.AsInt); - } - else - { - Debug.Assert(fieldType.IsValueType); - var fieldDefType = (DefType)fieldType; - if (fieldDefType.ContainsGCPointers) - { - GCPointerMapBuilder innerBuilder = - builder.GetInnerBuilder(field.Offset.AsInt, fieldDefType.InstanceByteCount.AsInt); - FromInstanceLayoutHelper(ref innerBuilder, fieldDefType); - } - } - } - - Debug.Assert(builder.ToGCMap().Size * type.Context.Target.PointerSize >= type.GCStaticFieldSize.AsInt); - return builder.ToGCMap(); - } - - /// - /// Computes the GC pointer map of the thread static region of the type. - /// - public static GCPointerMap FromThreadStaticLayout(DefType type) - { - GCPointerMapBuilder builder = new GCPointerMapBuilder(type.ThreadGcStaticFieldSize.AsInt, type.Context.Target.PointerSize); - - foreach (FieldDesc field in type.GetFields()) - { - if (!field.IsStatic || field.HasRva || field.IsLiteral || !field.IsThreadStatic || !field.HasGCStaticBase) - continue; - - TypeDesc fieldType = field.FieldType; - if (fieldType.IsGCPointer) - { - builder.MarkGCPointer(field.Offset.AsInt); - } - else if (fieldType.IsValueType) - { - var fieldDefType = (DefType)fieldType; - if (fieldDefType.ContainsGCPointers) - { - GCPointerMapBuilder innerBuilder = - builder.GetInnerBuilder(field.Offset.AsInt, fieldDefType.InstanceByteCount.AsInt); - FromInstanceLayoutHelper(ref innerBuilder, fieldDefType); - } - } - } - - Debug.Assert(builder.ToGCMap().Size * type.Context.Target.PointerSize >= type.ThreadGcStaticFieldSize.AsInt); - return builder.ToGCMap(); - } - } -} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs index 7c94539fb6bb42..40b7281dbba01b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs @@ -78,4 +78,156 @@ public static string GetName(this MethodSignature signature) return nameBuilder.ToString(); } } + + public class UniqueTypeNameFormatter : TypeNameFormatter + { + public static UniqueTypeNameFormatter Instance { get; } = new UniqueTypeNameFormatter(); + + public override void AppendName(StringBuilder sb, PointerType type) + { + AppendName(sb, type.ParameterType); + sb.Append('*'); + } + + public override void AppendName(StringBuilder sb, GenericParameterDesc type) + { + string prefix = type.Kind == GenericParameterKind.Type ? "!" : "!!"; + sb.Append(prefix); + sb.Append(type.Name); + } + + public override void AppendName(StringBuilder sb, SignatureTypeVariable type) + { + sb.Append("!"); + sb.Append(type.Index.ToStringInvariant()); + } + + public override void AppendName(StringBuilder sb, SignatureMethodVariable type) + { + sb.Append("!!"); + sb.Append(type.Index.ToStringInvariant()); + } + + public override void AppendName(StringBuilder sb, FunctionPointerType type) + { + MethodSignature signature = type.Signature; + + AppendName(sb, signature.ReturnType); + + sb.Append(" ("); + for (int i = 0; i < signature.Length; i++) + { + if (i > 0) + sb.Append(", "); + AppendName(sb, signature[i]); + } + + // TODO: Append '...' for vararg methods + + sb.Append(')'); + } + + public override void AppendName(StringBuilder sb, ByRefType type) + { + AppendName(sb, type.ParameterType); + sb.Append(" ByRef"); + } + + public override void AppendName(StringBuilder sb, ArrayType type) + { + AppendName(sb, type.ElementType); + sb.Append('['); + + if (type.Rank == 1 && type.IsMdArray) + sb.Append('*'); + sb.Append(',', type.Rank - 1); + + sb.Append(']'); + } + + protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type) + { + AppendName(sb, type.GetTypeDefinition()); + sb.Append('<'); + + for (int i = 0; i < type.Instantiation.Length; i++) + { + if (i > 0) + sb.Append(", "); + AppendName(sb, type.Instantiation[i]); + } + + sb.Append('>'); + } + + protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) + { + string ns = GetTypeNamespace(type); + if (ns.Length > 0) + { + AppendEscapedIdentifier(sb, ns); + sb.Append('.'); + } + AppendEscapedIdentifier(sb, GetTypeName(type)); + + if (type is MetadataType) + { + IAssemblyDesc homeAssembly = ((MetadataType)type).Module as IAssemblyDesc; + AppendAssemblyName(sb, homeAssembly); + } + } + + private void AppendAssemblyName(StringBuilder sb, IAssemblyDesc assembly) + { + if (assembly == null) + return; + + sb.Append(','); + AppendEscapedIdentifier(sb, assembly.GetName().Name); + } + + protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType) + { + AppendName(sb, containingType); + + sb.Append('+'); + + string ns = GetTypeNamespace(nestedType); + if (ns.Length > 0) + { + AppendEscapedIdentifier(sb, ns); + sb.Append('.'); + } + AppendEscapedIdentifier(sb, GetTypeName(nestedType)); + } + + private string GetTypeName(DefType type) + { + return type.Name; + } + + private string GetTypeNamespace(DefType type) + { + return type.Namespace; + } + + private static char[] s_escapedChars = new char[] { ',', '=', '"', ']', '[', '*', '&', '+', '\\' }; + private void AppendEscapedIdentifier(StringBuilder sb, string identifier) + { + if (identifier.IndexOfAny(s_escapedChars) < 0) + { + string escapedIdentifier = identifier; + foreach (char escapedChar in s_escapedChars) + { + string escapedCharString = new string(escapedChar, 1); + escapedIdentifier = escapedIdentifier.Replace(escapedCharString, "\\" + escapedCharString); + } + sb.Append(escapedIdentifier); + } + else + { + sb.Append(identifier); + } + } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs index 9873fb76c78370..2dd04047e594e0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs @@ -35,7 +35,7 @@ public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) } int ISymbolDefinitionNode.Offset => 0; - int ISymbolNode.Offset => Method.Context.Target.FatFunctionPointerOffset; + int ISymbolNode.Offset => Method.Context.Target.Architecture == TargetArchitecture.Wasm32 ? 1 << 31 : 2; public override bool IsShareable => true; diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj index e2703506aae36b..bf9a6275d972b7 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj @@ -100,9 +100,6 @@ TypeSystem\Canon\TypeSystemContext.Canon.cs - - TypeSystem\Aot\TargetDetails.Aot.cs - TypeSystem\CodeGen\FieldDesc.CodeGen.cs @@ -181,9 +178,6 @@ Utilities\GCPointerMap.Algorithm.cs - - Utilities\GCPointerMap.Aot.cs - Utilities\GCPointerMap.cs @@ -649,6 +643,5 @@ TypeSystem\Sorting\TypeSystemComparer.cs -
diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem/Utilities/UniqueTypeNameFormatter.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem/Utilities/UniqueTypeNameFormatter.cs deleted file mode 100644 index 980c0c8050aacb..00000000000000 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem/Utilities/UniqueTypeNameFormatter.cs +++ /dev/null @@ -1,164 +0,0 @@ -// 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.Text; - -namespace Internal.TypeSystem -{ - /// - /// Provides a name formatter attempts to produce unique names given a type. - /// The exact format of this type name provider is not considered stable or suited for parsing at this time. - /// - public class UniqueTypeNameFormatter : TypeNameFormatter - { - public static UniqueTypeNameFormatter Instance { get; } = new UniqueTypeNameFormatter(); - - public override void AppendName(StringBuilder sb, PointerType type) - { - AppendName(sb, type.ParameterType); - sb.Append('*'); - } - - public override void AppendName(StringBuilder sb, GenericParameterDesc type) - { - string prefix = type.Kind == GenericParameterKind.Type ? "!" : "!!"; - sb.Append(prefix); - sb.Append(type.Name); - } - - public override void AppendName(StringBuilder sb, SignatureTypeVariable type) - { - sb.Append("!"); - sb.Append(type.Index.ToStringInvariant()); - } - - public override void AppendName(StringBuilder sb, SignatureMethodVariable type) - { - sb.Append("!!"); - sb.Append(type.Index.ToStringInvariant()); - } - - public override void AppendName(StringBuilder sb, FunctionPointerType type) - { - MethodSignature signature = type.Signature; - - AppendName(sb, signature.ReturnType); - - sb.Append(" ("); - for (int i = 0; i < signature.Length; i++) - { - if (i > 0) - sb.Append(", "); - AppendName(sb, signature[i]); - } - - // TODO: Append '...' for vararg methods - - sb.Append(')'); - } - - public override void AppendName(StringBuilder sb, ByRefType type) - { - AppendName(sb, type.ParameterType); - sb.Append(" ByRef"); - } - - public override void AppendName(StringBuilder sb, ArrayType type) - { - AppendName(sb, type.ElementType); - sb.Append('['); - - if (type.Rank == 1 && type.IsMdArray) - sb.Append('*'); - sb.Append(',', type.Rank - 1); - - sb.Append(']'); - } - - protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type) - { - AppendName(sb, type.GetTypeDefinition()); - sb.Append('<'); - - for (int i = 0; i < type.Instantiation.Length; i++) - { - if (i > 0) - sb.Append(", "); - AppendName(sb, type.Instantiation[i]); - } - - sb.Append('>'); - } - - protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) - { - string ns = GetTypeNamespace(type); - if (ns.Length > 0) - { - AppendEscapedIdentifier(sb, ns); - sb.Append('.'); - } - AppendEscapedIdentifier(sb, GetTypeName(type)); - - if (type is MetadataType) - { - IAssemblyDesc homeAssembly = ((MetadataType)type).Module as IAssemblyDesc; - AppendAssemblyName(sb, homeAssembly); - } - } - - private void AppendAssemblyName(StringBuilder sb, IAssemblyDesc assembly) - { - if (assembly == null) - return; - - sb.Append(','); - AppendEscapedIdentifier(sb, assembly.GetName().Name); - } - - protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType) - { - AppendName(sb, containingType); - - sb.Append('+'); - - string ns = GetTypeNamespace(nestedType); - if (ns.Length > 0) - { - AppendEscapedIdentifier(sb, ns); - sb.Append('.'); - } - AppendEscapedIdentifier(sb, GetTypeName(nestedType)); - } - - private string GetTypeName(DefType type) - { - return type.Name; - } - - private string GetTypeNamespace(DefType type) - { - return type.Namespace; - } - - private static char[] s_escapedChars = new char[] { ',', '=', '"', ']', '[', '*', '&', '+', '\\' }; - private void AppendEscapedIdentifier(StringBuilder sb, string identifier) - { - if (identifier.IndexOfAny(s_escapedChars) < 0) - { - string escapedIdentifier = identifier; - foreach (char escapedChar in s_escapedChars) - { - string escapedCharString = new string(escapedChar, 1); - escapedIdentifier = escapedIdentifier.Replace(escapedCharString, "\\" + escapedCharString); - } - sb.Append(escapedIdentifier); - } - else - { - sb.Append(identifier); - } - } - } -} From 327bb3028ea87369066be954312ac0acd67bdb12 Mon Sep 17 00:00:00 2001 From: Clinton Ingram Date: Mon, 3 Jan 2022 10:17:32 -0800 Subject: [PATCH 13/97] add missing PTEST docs (#62122) --- .../X86/Sse41.PlatformNotSupported.cs | 84 +++++++++++++++++++ .../System/Runtime/Intrinsics/X86/Sse41.cs | 84 +++++++++++++++++++ 2 files changed, 168 insertions(+) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs index a207c6cfb1a911..a09030b4f3c7c3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.PlatformNotSupported.cs @@ -675,12 +675,40 @@ internal X64() { } /// PTEST xmm, xmm/m128 /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } /// @@ -688,12 +716,40 @@ internal X64() { } /// PTEST xmm, xmm/m128 /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } /// @@ -701,12 +757,40 @@ internal X64() { } /// PTEST xmm, xmm/m128 /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.cs index f0a7f00747c1ba..46352356b2d013 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse41.cs @@ -675,12 +675,40 @@ internal X64() { } /// PTEST xmm, xmm/m128 /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); + /// + /// int _mm_testc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestC(Vector128 left, Vector128 right) => TestC(left, right); /// @@ -688,12 +716,40 @@ internal X64() { } /// PTEST xmm, xmm/m128 /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); + /// + /// int _mm_testnzc_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestNotZAndNotC(Vector128 left, Vector128 right) => TestNotZAndNotC(left, right); /// @@ -701,12 +757,40 @@ internal X64() { } /// PTEST xmm, xmm/m128 /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); + /// + /// int _mm_testz_si128 (__m128i a, __m128i b) + /// PTEST xmm, xmm/m128 + /// public static bool TestZ(Vector128 left, Vector128 right) => TestZ(left, right); } } From 6c50d9fad7217b0eeed2b27ca6ab9ab34bc0dd1f Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 3 Jan 2022 13:32:34 -0500 Subject: [PATCH 14/97] Mark Go override as SkipLocalsInit if possible (#63277) It can have so many locals that zero-initing is measurable. --- .../gen/RegexGenerator.Emitter.cs | 12 +++++++++--- .../gen/RegexGenerator.cs | 2 +- .../RegexGeneratorParserTests.cs | 12 +++++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs index cbe77998186a2d..b95387ba4eceed 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs +++ b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs @@ -41,7 +41,7 @@ public partial class RegexGenerator }; /// Generates the code for one regular expression class. - private static (string, ImmutableArray) EmitRegexType(RegexType regexClass) + private static (string, ImmutableArray) EmitRegexType(RegexType regexClass, Compilation compilation) { var sb = new StringBuilder(1024); var writer = new IndentedTextWriter(new StringWriter(sb)); @@ -82,7 +82,7 @@ private static (string, ImmutableArray) EmitRegexType(RegexType rege generatedName += ComputeStringHash(generatedName).ToString("X"); // Generate the regex type - ImmutableArray diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName); + ImmutableArray diagnostics = EmitRegexMethod(writer, regexClass.Method, generatedName, compilation); while (writer.Indent != 0) { @@ -149,7 +149,7 @@ static bool ExceedsMaxDepthForSimpleCodeGeneration(RegexNode node, int allowedDe } /// Generates the code for a regular expression method. - private static ImmutableArray EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id) + private static ImmutableArray EmitRegexMethod(IndentedTextWriter writer, RegexMethod rm, string id, Compilation compilation) { string patternExpression = Literal(rm.Pattern); string optionsExpression = Literal(rm.Options); @@ -174,6 +174,8 @@ private static ImmutableArray EmitRegexMethod(IndentedTextWriter wri return ImmutableArray.Create(Diagnostic.Create(DiagnosticDescriptors.LimitedSourceGeneration, rm.MethodSyntax.GetLocation())); } + bool allowUnsafe = compilation.Options is CSharpCompilationOptions { AllowUnsafe: true }; + writer.WriteLine($"new {id}();"); writer.WriteLine(); writer.WriteLine($" private {id}()"); @@ -231,6 +233,10 @@ private static ImmutableArray EmitRegexMethod(IndentedTextWriter wri writer.Indent -= 4; writer.WriteLine($" }}"); writer.WriteLine(); + if (allowUnsafe) + { + writer.WriteLine($" [global::System.Runtime.CompilerServices.SkipLocalsInit]"); + } writer.WriteLine($" protected override void Go()"); writer.WriteLine($" {{"); writer.Indent += 4; diff --git a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.cs b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.cs index a459c8312c2639..558c613eae3a8f 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.cs +++ b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.cs @@ -49,7 +49,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) { Debug.Assert(state.Item1 is not null); object? result = GetRegexTypeToEmit(state.Item2, state.Item1, cancellationToken); - return result is RegexType regexType ? EmitRegexType(regexType) : result; + return result is RegexType regexType ? EmitRegexType(regexType, state.Item2) : result; }) .Collect(); diff --git a/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs b/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs index 1e8523d2f73f4a..da7e19c820128e 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs @@ -297,8 +297,10 @@ partial class C ", compile: true)); } - [Fact] - public async Task Valid_ClassWithNamespace() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Valid_ClassWithNamespace(bool allowUnsafe) { Assert.Empty(await RunGenerator(@" using System.Text.RegularExpressions; @@ -310,7 +312,7 @@ partial class C private static partial Regex Valid(); } } - ", compile: true)); + ", compile: true, allowUnsafe: allowUnsafe)); } [Fact] @@ -557,13 +559,13 @@ partial class C } private async Task> RunGenerator( - string code, bool compile = false, LanguageVersion langVersion = LanguageVersion.Preview, MetadataReference[]? additionalRefs = null, CancellationToken cancellationToken = default) + string code, bool compile = false, LanguageVersion langVersion = LanguageVersion.Preview, MetadataReference[]? additionalRefs = null, bool allowUnsafe = false, CancellationToken cancellationToken = default) { var proj = new AdhocWorkspace() .AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create())) .AddProject("RegexGeneratorTest", "RegexGeneratorTest.dll", "C#") .WithMetadataReferences(additionalRefs is not null ? s_refs.Concat(additionalRefs) : s_refs) - .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: allowUnsafe) .WithNullableContextOptions(NullableContextOptions.Enable)) .WithParseOptions(new CSharpParseOptions(langVersion)) .AddDocument("RegexGenerator.g.cs", SourceText.From(code, Encoding.UTF8)).Project; From d34c0d61971b30cbeb66800ce8c27f19f1441cd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aleksey=20Kliger=20=28=CE=BBgeek=29?= Date: Mon, 3 Jan 2022 14:01:21 -0500 Subject: [PATCH 15/97] [mono] Don't access MonoClassField:parent directly (#63081) Rename it to parent_ and add m_field_get_parent / m_field_set_parent accessors. (The intention is to borrow the bottom bit of the pointer for an EnC metadata update flag) --- src/mono/mono/component/debugger-agent.c | 22 ++++++++-------- src/mono/mono/metadata/class-init.c | 10 +++++-- src/mono/mono/metadata/class-internals.h | 14 ++++++++-- src/mono/mono/metadata/class.c | 32 +++++++++++------------ src/mono/mono/metadata/custom-attrs.c | 2 +- src/mono/mono/metadata/debug-helpers.c | 4 +-- src/mono/mono/metadata/icall.c | 28 ++++++++++---------- src/mono/mono/metadata/loader.c | 7 ++--- src/mono/mono/metadata/marshal-ilgen.c | 2 +- src/mono/mono/metadata/metadata.c | 6 ++--- src/mono/mono/metadata/object.c | 12 ++++----- src/mono/mono/metadata/reflection.c | 2 +- src/mono/mono/metadata/sre.c | 22 ++++++++-------- src/mono/mono/mini/aot-compiler.c | 15 ++++++----- src/mono/mono/mini/interp/transform.c | 14 +++++----- src/mono/mono/mini/intrinsics.c | 2 +- src/mono/mono/mini/jit-icalls.c | 4 +-- src/mono/mono/mini/method-to-ir.c | 10 +++---- src/mono/mono/mini/mini-generic-sharing.c | 8 +++--- src/mono/mono/mini/mini-runtime.c | 2 +- 20 files changed, 118 insertions(+), 100 deletions(-) diff --git a/src/mono/mono/component/debugger-agent.c b/src/mono/mono/component/debugger-agent.c index 2dcc1979d7a273..856e152240a9c6 100644 --- a/src/mono/mono/component/debugger-agent.c +++ b/src/mono/mono/component/debugger-agent.c @@ -2932,7 +2932,7 @@ static gint32 isFixedSizeArray (MonoClassField *f) MonoCustomAttrEntry *attr; int aindex; gint32 ret = 1; - cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error); + cinfo = mono_custom_attrs_from_field_checked (m_field_get_parent (f), f, error); goto_if_nok (error, leave); attr = NULL; if (cinfo) { @@ -7734,12 +7734,12 @@ field_commands (int command, guint8 *p, guint8 *end, Buffer *buf) MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err); buffer_add_string (buf, f->name); - buffer_add_typeid (buf, domain, f->parent); + buffer_add_typeid (buf, domain, m_field_get_parent (f)); buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type)); buffer_add_int (buf, f->type->attrs); if (CHECK_PROTOCOL_VERSION (2, 59)) { buffer_add_int (buf, f->type->type); - buffer_add_int (buf, m_class_get_type_token (f->parent)); + buffer_add_int (buf, m_class_get_type_token (m_field_get_parent (f))); buffer_add_int (buf, m_class_get_type_token (mono_class_from_mono_type_internal (f->type))); } break; @@ -7796,7 +7796,7 @@ static int get_static_field_value(MonoClassField* f, MonoClass* klass, MonoDomai /* Check that the field belongs to the object */ found = FALSE; for (k = klass; k; k = m_class_get_parent(k)) { - if (k == f->parent) { + if (k == m_field_get_parent (f)) { found = TRUE; break; } @@ -7804,7 +7804,7 @@ static int get_static_field_value(MonoClassField* f, MonoClass* klass, MonoDomai if (!found) return -1; - vtable = mono_class_vtable_checked(f->parent, error); + vtable = mono_class_vtable_checked(m_field_get_parent (f), error); if (!is_ok(error)) return -1; @@ -8127,7 +8127,7 @@ type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint /* Check that the field belongs to the object */ found = FALSE; for (k = klass; k; k = m_class_get_parent (k)) { - if (k == f->parent) { + if (k == m_field_get_parent (f)) { found = TRUE; break; } @@ -8137,7 +8137,7 @@ type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint // FIXME: Check for literal/const - vtable = mono_class_vtable_checked (f->parent, error); + vtable = mono_class_vtable_checked (m_field_get_parent (f), error); goto_if_nok (error, invalid_fieldid); val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type))); @@ -9634,7 +9634,7 @@ object_commands (int command, guint8 *p, guint8 *end, Buffer *buf) /* Check that the field belongs to the object */ found = FALSE; for (k = obj_type; k; k = m_class_get_parent (k)) { - if (k == f->parent) { + if (k == m_field_get_parent (f)) { found = TRUE; break; } @@ -9650,7 +9650,7 @@ object_commands (int command, guint8 *p, guint8 *end, Buffer *buf) goto invalid_fieldid; g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC); - vtable = mono_class_vtable_checked (f->parent, error); + vtable = mono_class_vtable_checked (m_field_get_parent (f), error); if (!is_ok (error)) { mono_error_cleanup (error); goto invalid_object; @@ -9681,7 +9681,7 @@ object_commands (int command, guint8 *p, guint8 *end, Buffer *buf) /* Check that the field belongs to the object */ found = FALSE; for (k = obj_type; k; k = m_class_get_parent (k)) { - if (k == f->parent) { + if (k == m_field_get_parent (f)) { found = TRUE; break; } @@ -9697,7 +9697,7 @@ object_commands (int command, guint8 *p, guint8 *end, Buffer *buf) goto invalid_fieldid; g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC); - vtable = mono_class_vtable_checked (f->parent, error); + vtable = mono_class_vtable_checked (m_field_get_parent (f), error); if (!is_ok (error)) { mono_error_cleanup (error); goto invalid_fieldid; diff --git a/src/mono/mono/metadata/class-init.c b/src/mono/mono/metadata/class-init.c index a7c333afb5eb8d..57c156d52e5d64 100644 --- a/src/mono/mono/metadata/class-init.c +++ b/src/mono/mono/metadata/class-init.c @@ -204,7 +204,7 @@ mono_class_setup_basic_field_info (MonoClass *klass) int first_field_idx = mono_class_has_static_metadata (klass) ? mono_class_get_first_field_idx (klass) : 0; for (i = 0; i < top; i++) { field = &fields [i]; - field->parent = klass; + m_field_set_parent (field, klass); if (gtd) { field->name = mono_field_get_name (>d->fields [i]); @@ -2399,7 +2399,7 @@ mono_class_layout_fields (MonoClass *klass, int base_instance_size, int packing_ guint32 field_idx = first_field_idx + (field - p->fields); if (MONO_TYPE_IS_REFERENCE (field->type) && mono_assembly_is_weak_field (p->image, field_idx + 1)) { has_weak_fields = TRUE; - mono_trace_message (MONO_TRACE_TYPE, "Field %s:%s at offset %x is weak.", field->parent->name, field->name, field->offset); + mono_trace_message (MONO_TRACE_TYPE, "Field %s:%s at offset %x is weak.", m_field_get_parent (field)->name, field->name, field->offset); } } } @@ -4080,3 +4080,9 @@ mono_classes_init (void) mono_counters_register ("MonoClass size", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size); } + +void +m_field_set_parent (MonoClassField *field, MonoClass *klass) +{ + field->parent_ = klass; +} diff --git a/src/mono/mono/metadata/class-internals.h b/src/mono/mono/metadata/class-internals.h index 541166813fbe85..04b2c5ecb7f9be 100644 --- a/src/mono/mono/metadata/class-internals.h +++ b/src/mono/mono/metadata/class-internals.h @@ -146,7 +146,8 @@ struct _MonoClassField { const char *name; /* Type where the field was defined */ - MonoClass *parent; + /* Do not access directly, use m_field_get_parent */ + MonoClass *parent_; /* * Offset where this field is stored; if it is an instance @@ -1535,10 +1536,19 @@ mono_method_has_unmanaged_callers_only_attribute (MonoMethod *method); } \ } \ +static inline MonoClass * +m_field_get_parent (MonoClassField *field) +{ + return field->parent_; +} + +void +m_field_set_parent (MonoClassField *field, MonoClass *klass); + static inline gboolean m_field_get_offset (MonoClassField *field) { - g_assert (m_class_is_fields_inited (field->parent)); + g_assert (m_class_is_fields_inited (m_field_get_parent (field))); return field->offset; } diff --git a/src/mono/mono/metadata/class.c b/src/mono/mono/metadata/class.c index 978d09ef3f957f..04af2642f252de 100644 --- a/src/mono/mono/metadata/class.c +++ b/src/mono/mono/metadata/class.c @@ -2501,7 +2501,7 @@ mono_class_get_field_from_name_full (MonoClass *klass, const char *name, MonoTyp guint32 mono_class_get_field_token (MonoClassField *field) { - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); int i; mono_class_setup_fields (klass); @@ -2531,8 +2531,8 @@ mono_class_get_field_token (MonoClassField *field) static int mono_field_get_index (MonoClassField *field) { - int index = field - m_class_get_fields (field->parent); - g_assert (index >= 0 && index < mono_class_get_field_count (field->parent)); + int index = field - m_class_get_fields (m_field_get_parent (field)); + g_assert (index >= 0 && index < mono_class_get_field_count (m_field_get_parent (field))); return index; } @@ -2548,7 +2548,7 @@ mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_typ guint32 cindex; guint32 constant_cols [MONO_CONSTANT_SIZE]; int field_index; - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); MonoFieldDefaultValue *def_values; g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT); @@ -2563,7 +2563,7 @@ mono_class_get_field_default_value (MonoClassField *field, MonoTypeEnum *def_typ field_index = mono_field_get_index (field); if (!def_values [field_index].data) { - MonoImage *field_parent_image = m_class_get_image (field->parent); + MonoImage *field_parent_image = m_class_get_image (m_field_get_parent (field)); cindex = mono_metadata_get_constant_index (field_parent_image, mono_class_get_field_token (field), 0); if (!cindex) return NULL; @@ -5402,7 +5402,7 @@ mono_field_get_type_checked (MonoClassField *field, MonoError *error) MonoClass* mono_field_get_parent (MonoClassField *field) { - return field->parent; + return m_field_get_parent (field); } /** @@ -5431,7 +5431,7 @@ mono_field_get_flags (MonoClassField *field) guint32 mono_field_get_offset (MonoClassField *field) { - mono_class_setup_fields(field->parent); + mono_class_setup_fields(m_field_get_parent (field)); return field->offset; } @@ -5440,7 +5440,7 @@ mono_field_get_rva (MonoClassField *field, int swizzle) { guint32 rva; int field_index; - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); MonoFieldDefaultValue *def_values; g_assert (field->type->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA); @@ -5459,11 +5459,11 @@ mono_field_get_rva (MonoClassField *field, int swizzle) if (!image_is_dynamic (m_class_get_image (klass))) { int first_field_idx = mono_class_get_first_field_idx (klass); - mono_metadata_field_info (m_class_get_image (field->parent), first_field_idx + field_index, NULL, &rva, NULL); + mono_metadata_field_info (m_class_get_image (m_field_get_parent (field)), first_field_idx + field_index, NULL, &rva, NULL); if (!rva) - g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), m_class_get_name (field->parent)); + g_warning ("field %s in %s should have RVA data, but hasn't", mono_field_get_name (field), m_class_get_name (m_field_get_parent (field))); - rvaData = mono_image_rva_map (m_class_get_image (field->parent), rva); + rvaData = mono_image_rva_map (m_class_get_image (m_field_get_parent (field)), rva); } else { rvaData = mono_field_get_data (field); } @@ -6170,11 +6170,11 @@ gboolean mono_method_can_access_field (MonoMethod *method, MonoClassField *field) { /* FIXME: check all overlapping fields */ - int can = can_access_member (method->klass, field->parent, NULL, mono_field_get_type_internal (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK); + int can = can_access_member (method->klass, m_field_get_parent (field), NULL, mono_field_get_type_internal (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK); if (!can) { MonoClass *nested = m_class_get_nested_in (method->klass); while (nested) { - can = can_access_member (nested, field->parent, NULL, mono_field_get_type_internal (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK); + can = can_access_member (nested, m_field_get_parent (field), NULL, mono_field_get_type_internal (field)->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK); if (can) return TRUE; nested = m_class_get_nested_in (nested); @@ -6282,7 +6282,7 @@ gboolean mono_method_can_access_field_full (MonoMethod *method, MonoClassField *field, MonoClass *context_klass) { MonoClass *access_class = method->klass; - MonoClass *member_class = field->parent; + MonoClass *member_class = m_field_get_parent (field); /* FIXME: check all overlapping fields */ int can = can_access_member (access_class, member_class, context_klass, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK); if (!can) { @@ -6413,7 +6413,7 @@ mono_generic_class_is_generic_type_definition (MonoGenericClass *gklass) void mono_field_resolve_type (MonoClassField *field, MonoError *error) { - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); MonoImage *image = m_class_get_image (klass); MonoClass *gtd = mono_class_is_ginst (klass) ? mono_class_get_generic_type_definition (klass) : NULL; MonoType *ftype; @@ -6475,7 +6475,7 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error) static guint32 mono_field_resolve_flags (MonoClassField *field) { - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); MonoImage *image = m_class_get_image (klass); MonoClass *gtd = mono_class_is_ginst (klass) ? mono_class_get_generic_type_definition (klass) : NULL; int field_idx = field - m_class_get_fields (klass); diff --git a/src/mono/mono/metadata/custom-attrs.c b/src/mono/mono/metadata/custom-attrs.c index b70349f20789b9..580a51b497d37d 100644 --- a/src/mono/mono/metadata/custom-attrs.c +++ b/src/mono/mono/metadata/custom-attrs.c @@ -2132,7 +2132,7 @@ mono_reflection_get_custom_attrs_info_checked (MonoObjectHandle obj, MonoError * } else if (strcmp ("RuntimeFieldInfo", klass_name) == 0) { MonoReflectionFieldHandle rfield = MONO_HANDLE_CAST (MonoReflectionField, obj); MonoClassField *field = MONO_HANDLE_GETVAL (rfield, field); - cinfo = mono_custom_attrs_from_field_checked (field->parent, field, error); + cinfo = mono_custom_attrs_from_field_checked (m_field_get_parent (field), field, error); goto_if_nok (error, leave); } else if ((strcmp ("RuntimeMethodInfo", klass_name) == 0) || (strcmp ("RuntimeConstructorInfo", klass_name) == 0)) { MonoReflectionMethodHandle rmethod = MONO_HANDLE_CAST (MonoReflectionMethod, obj); diff --git a/src/mono/mono/metadata/debug-helpers.c b/src/mono/mono/metadata/debug-helpers.c index c294477458f232..b2743a89b03267 100644 --- a/src/mono/mono/metadata/debug-helpers.c +++ b/src/mono/mono/metadata/debug-helpers.c @@ -868,10 +868,10 @@ char * mono_field_full_name (MonoClassField *field) { char *res; - const char *nspace = field->parent->name_space; + const char *nspace = m_field_get_parent (field)->name_space; res = g_strdup_printf ("%s%s%s:%s", nspace, *nspace ? "." : "", - field->parent->name, mono_field_get_name (field)); + m_field_get_parent (field)->name, mono_field_get_name (field)); return res; } diff --git a/src/mono/mono/metadata/icall.c b/src/mono/mono/metadata/icall.c index 1597b0b866af35..2285778320b9b9 100644 --- a/src/mono/mono/metadata/icall.c +++ b/src/mono/mono/metadata/icall.c @@ -1839,7 +1839,7 @@ MonoReflectionMarshalAsAttributeHandle ves_icall_System_Reflection_FieldInfo_get_marshal_info (MonoReflectionFieldHandle field_h, MonoError *error) { MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field); - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); MonoGenericClass *gklass = mono_class_try_get_generic_class (klass); if (mono_class_is_gtd (klass) || @@ -1873,11 +1873,11 @@ ves_icall_System_Reflection_FieldInfo_internal_from_handle_type (MonoClassField g_assert (handle); if (!type) { - klass = handle->parent; + klass = m_field_get_parent (handle); } else { klass = mono_class_from_mono_type_internal (type); - gboolean found = klass == handle->parent || mono_class_has_parent (klass, handle->parent); + gboolean found = klass == m_field_get_parent (handle) || mono_class_has_parent (klass, m_field_get_parent (handle)); if (!found) /* The managed code will throw the exception */ @@ -2014,7 +2014,7 @@ gint32 ves_icall_RuntimeFieldInfo_GetFieldOffset (MonoReflectionFieldHandle field, MonoError *error) { MonoClassField *class_field = MONO_HANDLE_GETVAL (field, field); - mono_class_setup_fields (class_field->parent); + mono_class_setup_fields (m_field_get_parent (class_field)); return class_field->offset - MONO_ABI_SIZEOF (MonoObject); } @@ -2026,7 +2026,7 @@ ves_icall_RuntimeFieldInfo_GetParentType (MonoReflectionFieldHandle field, MonoB if (declaring) { MonoClassField *f = MONO_HANDLE_GETVAL (field, field); - parent = f->parent; + parent = m_field_get_parent (f); } else { parent = MONO_HANDLE_GETVAL (field, klass); } @@ -2133,7 +2133,7 @@ ves_icall_RuntimeFieldInfo_SetValueInternal (MonoReflectionFieldHandle field, Mo (!isref && v == NULL && value_gchandle == 0)); if (type->attrs & FIELD_ATTRIBUTE_STATIC) { - MonoVTable *vtable = mono_class_vtable_checked (cf->parent, error); + MonoVTable *vtable = mono_class_vtable_checked (m_field_get_parent (cf), error); goto_if_nok (error, leave); if (!vtable->initialized) { @@ -2179,7 +2179,7 @@ ves_icall_System_RuntimeFieldHandle_GetValueDirect (MonoReflectionFieldHandle fi MonoClassField *field = MONO_HANDLE_GETVAL (field_h, field); MonoClass *klass = mono_class_from_mono_type_internal (field->type); - if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (field->parent))) { + if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (m_field_get_parent (field)))) { mono_error_set_not_implemented (error, ""); return MONO_HANDLE_NEW (MonoObject, NULL); } else if (MONO_TYPE_IS_REFERENCE (field->type)) { @@ -2196,9 +2196,9 @@ ves_icall_System_RuntimeFieldHandle_SetValueDirect (MonoReflectionFieldHandle fi g_assert (obj); - mono_class_setup_fields (f->parent); + mono_class_setup_fields (m_field_get_parent (f)); - if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (f->parent))) { + if (!MONO_TYPE_ISSTRUCT (m_class_get_byval_arg (m_field_get_parent (f)))) { MonoObjectHandle objHandle = typed_reference_to_object (obj, error); return_if_nok (error); ves_icall_RuntimeFieldInfo_SetValueInternal (field_h, objHandle, value_h, error); @@ -2226,7 +2226,7 @@ ves_icall_RuntimeFieldInfo_GetRawConstantValue (MonoReflectionFieldHandle rfield MonoType *t; MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed. - mono_class_init_internal (field->parent); + mono_class_init_internal (m_field_get_parent (field)); t = mono_field_get_type_checked (field, error); goto_if_nok (error, return_null); @@ -2234,8 +2234,8 @@ ves_icall_RuntimeFieldInfo_GetRawConstantValue (MonoReflectionFieldHandle rfield if (!(t->attrs & FIELD_ATTRIBUTE_HAS_DEFAULT)) goto invalid_operation; - if (image_is_dynamic (m_class_get_image (field->parent))) { - MonoClass *klass = field->parent; + if (image_is_dynamic (m_class_get_image (m_field_get_parent (field)))) { + MonoClass *klass = m_field_get_parent (field); int fidx = field - m_class_get_fields (klass); MonoFieldDefaultValue *def_values = mono_class_get_field_def_values (klass); @@ -5959,7 +5959,7 @@ ves_icall_System_Reflection_RuntimeModule_ResolveMemberToken (MonoImage *image, case MONO_TABLE_FIELD: { MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror); if (f) { - return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (f->parent, f, merror)); + return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (m_field_get_parent (f), f, merror)); } else return NULL_HANDLE; @@ -5975,7 +5975,7 @@ ves_icall_System_Reflection_RuntimeModule_ResolveMemberToken (MonoImage *image, else { MonoClassField *f = module_resolve_field_token (image, token, type_args, method_args, error, merror); if (f) { - return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (f->parent, f, merror)); + return MONO_HANDLE_CAST (MonoObject, mono_field_get_object_handle (m_field_get_parent (f), f, merror)); } else return NULL_HANDLE; diff --git a/src/mono/mono/metadata/loader.c b/src/mono/mono/metadata/loader.c index a3e451d4517f44..f31ad254bad36e 100644 --- a/src/mono/mono/metadata/loader.c +++ b/src/mono/mono/metadata/loader.c @@ -350,12 +350,12 @@ mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retk mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token); return NULL; } - *retklass = result->parent; + *retklass = m_field_get_parent (result); return result; } if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) { - *retklass = field->parent; + *retklass = m_field_get_parent (field); return field; } @@ -387,7 +387,8 @@ mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retk } } - if (field && field->parent && !mono_class_is_ginst (field->parent) && !mono_class_is_gtd (field->parent)) { + MonoClass *field_parent = NULL; + if (field && ((field_parent = m_field_get_parent (field))) && !mono_class_is_ginst (field_parent) && !mono_class_is_gtd (field_parent)) { mono_image_lock (image); mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field); mono_image_unlock (image); diff --git a/src/mono/mono/metadata/marshal-ilgen.c b/src/mono/mono/metadata/marshal-ilgen.c index 8df471352803e8..b8a12826aac4bc 100644 --- a/src/mono/mono/metadata/marshal-ilgen.c +++ b/src/mono/mono/metadata/marshal-ilgen.c @@ -175,7 +175,7 @@ get_fixed_buffer_attr (MonoClassField *field, MonoType **out_etype, int *out_len MonoCustomAttrEntry *attr; int aindex; - cinfo = mono_custom_attrs_from_field_checked (field->parent, field, error); + cinfo = mono_custom_attrs_from_field_checked (m_field_get_parent (field), field, error); if (!is_ok (error)) return FALSE; attr = NULL; diff --git a/src/mono/mono/metadata/metadata.c b/src/mono/mono/metadata/metadata.c index 5912a12a0c9093..04a43f5e0076fa 100644 --- a/src/mono/mono/metadata/metadata.c +++ b/src/mono/mono/metadata/metadata.c @@ -7568,11 +7568,11 @@ mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassFie MonoClass *gtd; int offset; - if (!mono_class_is_ginst (field->parent)) + if (!mono_class_is_ginst (m_field_get_parent (field))) return field; - gtd = mono_class_get_generic_class (field->parent)->container_class; - offset = field - m_class_get_fields (field->parent); + gtd = mono_class_get_generic_class (m_field_get_parent (field))->container_class; + offset = field - m_class_get_fields (m_field_get_parent (field)); return m_class_get_fields (gtd) + offset; } diff --git a/src/mono/mono/metadata/object.c b/src/mono/mono/metadata/object.c index 752a4dcd1faa82..fe03fcab2b5ab6 100644 --- a/src/mono/mono/metadata/object.c +++ b/src/mono/mono/metadata/object.c @@ -908,7 +908,7 @@ compute_class_bitmap (MonoClass *klass, gsize *bitmap, int size, int offset, int case MONO_TYPE_CHAR: break; default: - g_error ("compute_class_bitmap: Invalid type %x for field %s:%s\n", type->type, mono_type_get_full_name (field->parent), field->name); + g_error ("compute_class_bitmap: Invalid type %x for field %s:%s\n", type->type, mono_type_get_full_name (m_field_get_parent (field)), field->name); break; } } @@ -2245,7 +2245,7 @@ mono_class_field_is_special_static (MonoClassField *field) if (mono_field_is_deleted (field)) return FALSE; if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) { - if (field_is_special_static (field->parent, field) != SPECIAL_STATIC_NONE) + if (field_is_special_static (m_field_get_parent (field), field) != SPECIAL_STATIC_NONE) return TRUE; } return FALSE; @@ -2267,7 +2267,7 @@ mono_class_field_get_special_static_type (MonoClassField *field) if (mono_field_is_deleted (field)) return SPECIAL_STATIC_NONE; if (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL)) - return field_is_special_static (field->parent, field); + return field_is_special_static (m_field_get_parent (field), field); return SPECIAL_STATIC_NONE; } @@ -2285,7 +2285,7 @@ mono_class_has_special_static_fields (MonoClass *klass) iter = NULL; while ((field = mono_class_get_fields_internal (klass, &iter))) { - g_assert (field->parent == klass); + g_assert (m_field_get_parent (field) == klass); if (mono_class_field_is_special_static (field)) return TRUE; } @@ -2793,7 +2793,7 @@ mono_field_static_set_value_internal (MonoVTable *vt, MonoClassField *field, voi gpointer mono_special_static_field_get_offset (MonoClassField *field, MonoError *error) { - MonoMemoryManager *mem_manager = m_class_get_mem_manager (field->parent); + MonoMemoryManager *mem_manager = m_class_get_mem_manager (m_field_get_parent (field)); gpointer addr = NULL; mono_mem_manager_lock (mem_manager); @@ -3020,7 +3020,7 @@ mono_field_get_value_object_checked (MonoClassField *field, MonoObject *obj, Mon is_static = TRUE; if (!is_literal) { - vtable = mono_class_vtable_checked (field->parent, error); + vtable = mono_class_vtable_checked (m_field_get_parent (field), error); goto_if_nok (error, return_null); if (!vtable->initialized) { diff --git a/src/mono/mono/metadata/reflection.c b/src/mono/mono/metadata/reflection.c index 181770ca8ef98e..9c39731d698b21 100644 --- a/src/mono/mono/metadata/reflection.c +++ b/src/mono/mono/metadata/reflection.c @@ -746,7 +746,7 @@ MonoReflectionFieldHandle mono_field_get_object_handle (MonoClass *klass, MonoClassField *field, MonoError *error) { error_init (error); - return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionField, m_class_get_mem_manager (field->parent), field, klass, field_object_construct, NULL); + return CHECK_OR_CONSTRUCT_HANDLE (MonoReflectionField, m_class_get_mem_manager (m_field_get_parent (field)), field, klass, field_object_construct, NULL); } /* diff --git a/src/mono/mono/metadata/sre.c b/src/mono/mono/metadata/sre.c index d86b18b1bcc0c9..912c4a9e94578c 100644 --- a/src/mono/mono/metadata/sre.c +++ b/src/mono/mono/metadata/sre.c @@ -744,13 +744,13 @@ mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, static gboolean is_field_on_inst (MonoClassField *field) { - return mono_class_is_ginst (field->parent) && mono_class_get_generic_class (field->parent)->is_dynamic; + return mono_class_is_ginst (m_field_get_parent (field)) && mono_class_get_generic_class (m_field_get_parent (field))->is_dynamic; } static gboolean is_field_on_gtd (MonoClassField *field) { - return mono_class_is_gtd (field->parent); + return mono_class_is_gtd (m_field_get_parent (field)); } #ifndef DISABLE_REFLECTION_EMIT @@ -760,13 +760,13 @@ mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoClassField *field guint32 token; g_assert (field); - g_assert (field->parent); + g_assert (m_field_get_parent (field)); token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, field)); if (token) return token; - token = mono_image_get_memberref_token (assembly, m_class_get_byval_arg (field->parent)); + token = mono_image_get_memberref_token (assembly, m_class_get_byval_arg (m_field_get_parent (field))); g_hash_table_insert (assembly->handleref, field, GUINT_TO_POINTER(token)); return token; } @@ -1136,20 +1136,20 @@ mono_image_create_token (MonoDynamicImage *assembly, MonoObjectHandle obj, } else if (strcmp (klass->name, "RuntimeFieldInfo") == 0) { MonoReflectionFieldHandle f = MONO_HANDLE_CAST (MonoReflectionField, obj); MonoClassField *field = MONO_HANDLE_GETVAL (f, field); - if ((field->parent->image == &assembly->image) && + if ((m_field_get_parent (field)->image == &assembly->image) && !is_field_on_gtd (field) && !is_field_on_inst (field)) { static guint32 field_table_idx = 0xffffff; field_table_idx --; token = MONO_TOKEN_FIELD_DEF | field_table_idx; - g_assert (!mono_class_is_gtd (field->parent)); + g_assert (!mono_class_is_gtd (m_field_get_parent (field))); how_collide = MONO_DYN_IMAGE_TOK_NEW; } else { guint32 fieldref_token = mono_image_get_fieldref_token (assembly, field); /* Same as methodref: get a canonical object to * register with the token. */ MonoReflectionFieldHandle canonical_obj = - mono_field_get_object_handle (field->parent, field, error); + mono_field_get_object_handle (m_field_get_parent (field), field, error); goto_if_nok (error, leave); MONO_HANDLE_ASSIGN (register_obj, canonical_obj); token = fieldref_token; @@ -3299,7 +3299,7 @@ fix_partial_generic_class (MonoClass *klass, MonoError *error) for (i = 0; i < gfcount; i++) { klass->fields [i] = gklass->fields [i]; - klass->fields [i].parent = klass; + m_field_set_parent (&klass->fields [i], klass); klass->fields [i].type = mono_class_inflate_generic_type_checked (gklass->fields [i].type, mono_class_get_context (klass), error); return_val_if_nok (error, FALSE); } @@ -3534,7 +3534,7 @@ typebuilder_setup_one_field (MonoDynamicImage *dynamic_image, MonoClass *klass, fb = (MonoReflectionFieldBuilder *)mono_array_get_internal (tb_fields, gpointer, i); field = &klass->fields [i]; - field->parent = klass; + m_field_set_parent (field, klass); field->name = string_to_utf8_image_raw (image, fb->name, error); /* FIXME use handles */ goto_if_nok (error, leave); if (fb->attrs) { @@ -4218,11 +4218,11 @@ mono_reflection_resolve_object (MonoImage *image, MonoObject *obj, MonoClass **h } else if (strcmp (oklass->name, "RuntimeFieldInfo") == 0) { MonoClassField *field = ((MonoReflectionField*)obj)->field; - ensure_complete_type (field->parent, error); + ensure_complete_type (m_field_get_parent (field), error); goto_if_nok (error, return_null); if (context) { - MonoType *inflated = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (field->parent), context, error); + MonoType *inflated = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (m_field_get_parent (field)), context, error); goto_if_nok (error, return_null); MonoClass *klass; diff --git a/src/mono/mono/mini/aot-compiler.c b/src/mono/mono/mini/aot-compiler.c index c8aac849ad17ec..4a3ca8efe039c1 100644 --- a/src/mono/mono/mini/aot-compiler.c +++ b/src/mono/mono/mini/aot-compiler.c @@ -2989,7 +2989,7 @@ arch_emit_unbox_arbitrary_trampoline (MonoAotCompile *acfg, int offset, int *tra static guint32 mono_get_field_token (MonoClassField *field) { - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); int i; int fcount = mono_class_get_field_count (klass); @@ -3484,7 +3484,7 @@ encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guin guint32 token = mono_get_field_token (field); guint8 *p = buf; - encode_klass_ref (cfg, field->parent, p, &p); + encode_klass_ref (cfg, m_field_get_parent (field), p, &p); g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF); encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p); *endbuf = p; @@ -8077,14 +8077,15 @@ mono_aot_readonly_field_override (MonoClassField *field) for (rdv = readonly_values; rdv; rdv = rdv->next) { char *p = rdv->name; int len; - len = strlen (m_class_get_name_space (field->parent)); - if (strncmp (p, m_class_get_name_space (field->parent), len)) + MonoClass *field_parent = m_field_get_parent (field); + len = strlen (m_class_get_name_space (field_parent)); + if (strncmp (p, m_class_get_name_space (field_parent), len)) continue; p += len; if (*p++ != '.') continue; - len = strlen (m_class_get_name (field->parent)); - if (strncmp (p, m_class_get_name (field->parent), len)) + len = strlen (m_class_get_name (field_parent)); + if (strncmp (p, m_class_get_name (field_parent), len)) continue; p += len; if (*p++ != '.') @@ -9121,7 +9122,7 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method) break; } case MONO_PATCH_INFO_SFLDA: { - MonoClass *klass = patch_info->data.field->parent; + MonoClass *klass = m_field_get_parent (patch_info->data.field); /* The .cctor needs to run at runtime. */ if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass)) diff --git a/src/mono/mono/mini/interp/transform.c b/src/mono/mono/mini/interp/transform.c index 96ec25f929e8fd..263603de741c18 100644 --- a/src/mono/mono/mini/interp/transform.c +++ b/src/mono/mono/mini/interp/transform.c @@ -3556,9 +3556,9 @@ interp_field_from_token (MonoMethod *method, guint32 token, MonoClass **klass, M MonoClassField *field = NULL; if (method->wrapper_type != MONO_WRAPPER_NONE) { field = (MonoClassField *) mono_method_get_wrapper_data (method, token); - *klass = field->parent; + *klass = m_field_get_parent (field); - mono_class_setup_fields (field->parent); + mono_class_setup_fields (m_field_get_parent (field)); } else { field = mono_field_from_token_checked (m_class_get_image (method->klass), token, klass, generic_context, error); return_val_if_nok (error, NULL); @@ -4091,7 +4091,7 @@ static void interp_emit_ldsflda (TransformData *td, MonoClassField *field, MonoError *error) { // Initialize the offset for the field - MonoVTable *vtable = mono_class_vtable_checked (field->parent, error); + MonoVTable *vtable = mono_class_vtable_checked (m_field_get_parent (field), error); return_if_nok (error); push_simple_type (td, STACK_TYPE_MP); @@ -4164,7 +4164,7 @@ static void interp_emit_sfld_access (TransformData *td, MonoClassField *field, MonoClass *field_class, int mt, gboolean is_load, MonoError *error) { // Initialize the offset for the field - MonoVTable *vtable = mono_class_vtable_checked (field->parent, error); + MonoVTable *vtable = mono_class_vtable_checked (m_field_get_parent (field), error); return_if_nok (error); if (mono_class_field_is_special_static (field)) { @@ -6146,11 +6146,11 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, MonoType *ftype = mono_field_get_type_internal (field); mt = mint_type (ftype); klass = mono_class_from_mono_type_internal (ftype); - gboolean in_corlib = m_class_get_image (field->parent) == mono_defaults.corlib; + gboolean in_corlib = m_class_get_image (m_field_get_parent (field)) == mono_defaults.corlib; if (in_corlib && !strcmp (field->name, "IsLittleEndian") && - !strcmp (m_class_get_name (field->parent), "BitConverter") && - !strcmp (m_class_get_name_space (field->parent), "System")) + !strcmp (m_class_get_name (m_field_get_parent (field)), "BitConverter") && + !strcmp (m_class_get_name_space (m_field_get_parent (field)), "System")) { interp_add_ins (td, (TARGET_BYTE_ORDER == G_LITTLE_ENDIAN) ? MINT_LDC_I4_1 : MINT_LDC_I4_0); push_simple_type (td, STACK_TYPE_I4); diff --git a/src/mono/mono/mini/intrinsics.c b/src/mono/mono/mini/intrinsics.c index a25a215d08235a..4e30c67c85dd83 100644 --- a/src/mono/mono/mini/intrinsics.c +++ b/src/mono/mono/mini/intrinsics.c @@ -2262,7 +2262,7 @@ emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **a MonoInst* mini_emit_inst_for_field_load (MonoCompile *cfg, MonoClassField *field) { - MonoClass *klass = field->parent; + MonoClass *klass = m_field_get_parent (field); const char *klass_name_space = m_class_get_name_space (klass); const char *klass_name = m_class_get_name (klass); MonoImage *klass_image = m_class_get_image (klass); diff --git a/src/mono/mono/mini/jit-icalls.c b/src/mono/mono/mini/jit-icalls.c index 32ff6c88fb9956..8d92b1c06f2120 100644 --- a/src/mono/mono/mini/jit-icalls.c +++ b/src/mono/mono/mini/jit-icalls.c @@ -865,9 +865,9 @@ mono_class_static_field_address (MonoClassField *field) //printf ("SFLDA0 %s.%s::%s %d\n", field->parent->name_space, field->parent->name, field->name, field->offset, field->parent->inited); - mono_class_init_internal (field->parent); + mono_class_init_internal (m_field_get_parent (field)); - vtable = mono_class_vtable_checked (field->parent, error); + vtable = mono_class_vtable_checked (m_field_get_parent (field), error); if (!is_ok (error)) { mono_error_set_pending_exception (error); return NULL; diff --git a/src/mono/mono/mini/method-to-ir.c b/src/mono/mono/mini/method-to-ir.c index db3be9c80bd401..d6ef76676cfb46 100644 --- a/src/mono/mono/mini/method-to-ir.c +++ b/src/mono/mono/mini/method-to-ir.c @@ -9566,7 +9566,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b if (method->wrapper_type != MONO_WRAPPER_NONE) { field = (MonoClassField *)mono_method_get_wrapper_data (method, token); - klass = field->parent; + klass = m_field_get_parent (field); } else { klass = NULL; @@ -9748,7 +9748,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b context_used = mini_class_check_context_used (cfg, klass); if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) { - mono_error_set_field_missing (cfg->error, field->parent, field->name, NULL, "Using static instructions with literal field"); + mono_error_set_field_missing (cfg->error, m_field_get_parent (field), field->name, NULL, "Using static instructions with literal field"); CHECK_CFG_ERROR; } @@ -9823,7 +9823,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b (context_used && is_special_static)) { MonoInst *iargs [1]; - g_assert (field->parent); + g_assert (m_field_get_parent (field)); if (context_used) { iargs [0] = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_CLASS_FIELD); @@ -9868,7 +9868,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b } else if (cfg->compile_aot && addr) { MonoInst *iargs [1]; - g_assert (field->parent); + g_assert (m_field_get_parent (field)); EMIT_NEW_FIELDCONST (cfg, iargs [0], field); ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs); } else { @@ -10404,7 +10404,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b } else if (handle_class == mono_defaults.typehandle_class) { context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type_internal ((MonoType *)handle)); } else if (handle_class == mono_defaults.fieldhandle_class) - context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent); + context_used = mini_class_check_context_used (cfg, m_field_get_parent (((MonoClassField*)handle))); else if (handle_class == mono_defaults.methodhandle_class) context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle); else diff --git a/src/mono/mono/mini/mini-generic-sharing.c b/src/mono/mono/mini/mini-generic-sharing.c index f974b56f94cb76..449cf376fbaea3 100644 --- a/src/mono/mono/mini/mini-generic-sharing.c +++ b/src/mono/mono/mini/mini-generic-sharing.c @@ -672,11 +672,11 @@ inflate_info (MonoMemoryManager *mem_manager, MonoRuntimeGenericContextInfoTempl case MONO_RGCTX_INFO_FIELD_OFFSET: { ERROR_DECL (error); MonoClassField *field = (MonoClassField *)data; - MonoType *inflated_type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (field->parent), context, error); + MonoType *inflated_type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (m_field_get_parent (field)), context, error); mono_error_assert_ok (error); /* FIXME don't swallow the error */ MonoClass *inflated_class = mono_class_from_mono_type_internal (inflated_type); - int i = field - m_class_get_fields (field->parent); + int i = field - m_class_get_fields (m_field_get_parent (field)); gpointer dummy = NULL; mono_metadata_free_type (inflated_type); @@ -2316,7 +2316,7 @@ instantiate_info (MonoMemoryManager *mem_manager, MonoRuntimeGenericContextInfoT if (mono_class_field_is_special_static (field)) { gpointer addr; - mono_class_vtable_checked (field->parent, error); + mono_class_vtable_checked (m_field_get_parent (field), error); mono_error_assert_ok (error); /* Return the TLS offset */ @@ -2326,7 +2326,7 @@ instantiate_info (MonoMemoryManager *mem_manager, MonoRuntimeGenericContextInfoT } /* The value is offset by 1 */ - if (m_class_is_valuetype (field->parent) && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) + if (m_class_is_valuetype (m_field_get_parent (field)) && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) return GUINT_TO_POINTER (field->offset - MONO_ABI_SIZEOF (MonoObject) + 1); else return GUINT_TO_POINTER (field->offset + 1); diff --git a/src/mono/mono/mini/mini-runtime.c b/src/mono/mono/mini/mini-runtime.c index 2af85253234adc..5aa5426d4e4f31 100644 --- a/src/mono/mono/mini/mini-runtime.c +++ b/src/mono/mono/mini/mini-runtime.c @@ -1506,7 +1506,7 @@ mono_resolve_patch_target_ext (MonoMemoryManager *mem_manager, MonoMethod *metho break; } case MONO_PATCH_INFO_SFLDA: { - MonoVTable *vtable = mono_class_vtable_checked (patch_info->data.field->parent, error); + MonoVTable *vtable = mono_class_vtable_checked (m_field_get_parent (patch_info->data.field), error); mono_error_assert_ok (error); if (mono_class_field_is_special_static (patch_info->data.field)) { From 2d52010e8c6a94c69dd9820fd000943669dc6671 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 3 Jan 2022 14:02:58 -0500 Subject: [PATCH 16/97] Use pattern matching to reduce some duplication (#63278) --- .../Text/RegularExpressions/RegexNode.cs | 66 +++++-------------- 1 file changed, 16 insertions(+), 50 deletions(-) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs index 49c0696776d40b..fe04caca5e7bbe 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs @@ -393,12 +393,7 @@ internal RegexNode FinalOptimize() node = node.Child(0); continue; - case Oneloop when node.N == int.MaxValue: - case Oneloopatomic when node.N == int.MaxValue: - case Notoneloop when node.N == int.MaxValue: - case Notoneloopatomic when node.N == int.MaxValue: - case Setloop when node.N == int.MaxValue: - case Setloopatomic when node.N == int.MaxValue: + case Oneloop or Oneloopatomic or Notoneloop or Notoneloopatomic or Setloop or Setloopatomic when node.N == int.MaxValue: RegexNode? parent = node.Next; if (parent != null && parent.Type == Concatenate) { @@ -1615,15 +1610,8 @@ static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) switch (currentNode.Type) { // Coalescing a loop with its same type - case Oneloop when nextNode.Type == Oneloop && currentNode.Ch == nextNode.Ch: - case Oneloopatomic when nextNode.Type == Oneloopatomic && currentNode.Ch == nextNode.Ch: - case Onelazy when nextNode.Type == Onelazy && currentNode.Ch == nextNode.Ch: - case Notoneloop when nextNode.Type == Notoneloop && currentNode.Ch == nextNode.Ch: - case Notoneloopatomic when nextNode.Type == Notoneloopatomic && currentNode.Ch == nextNode.Ch: - case Notonelazy when nextNode.Type == Notonelazy && currentNode.Ch == nextNode.Ch: - case Setloop when nextNode.Type == Setloop && currentNode.Str == nextNode.Str: - case Setloopatomic when nextNode.Type == Setloopatomic && currentNode.Str == nextNode.Str: - case Setlazy when nextNode.Type == Setlazy && currentNode.Str == nextNode.Str: + case Oneloop or Oneloopatomic or Onelazy or Notoneloop or Notoneloopatomic or Notonelazy when nextNode.Type == currentNode.Type && currentNode.Ch == nextNode.Ch: + case Setloop or Setloopatomic or Setlazy when nextNode.Type == currentNode.Type && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) { currentNode.M += nextNode.M; @@ -1637,15 +1625,9 @@ static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) break; // Coalescing a loop with an additional item of the same type - case Oneloop when nextNode.Type == One && currentNode.Ch == nextNode.Ch: - case Oneloopatomic when nextNode.Type == One && currentNode.Ch == nextNode.Ch: - case Onelazy when nextNode.Type == One && currentNode.Ch == nextNode.Ch: - case Notoneloop when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: - case Notoneloopatomic when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: - case Notonelazy when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: - case Setloop when nextNode.Type == Set && currentNode.Str == nextNode.Str: - case Setloopatomic when nextNode.Type == Set && currentNode.Str == nextNode.Str: - case Setlazy when nextNode.Type == Set && currentNode.Str == nextNode.Str: + case Oneloop or Oneloopatomic or Onelazy when nextNode.Type == One && currentNode.Ch == nextNode.Ch: + case Notoneloop or Notoneloopatomic or Notonelazy when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: + case Setloop or Setloopatomic or Setlazy when nextNode.Type == Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; @@ -1673,8 +1655,7 @@ static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) break; // Coalescing an individual item with another individual item. - case One when nextNode.Type == One && currentNode.Ch == nextNode.Ch: - case Notone when nextNode.Type == Notone && currentNode.Ch == nextNode.Ch: + case One or Notone when nextNode.Type == currentNode.Type && currentNode.Ch == nextNode.Ch: case Set when nextNode.Type == Set && currentNode.Str == nextNode.Str: currentNode.MakeRep(Oneloop, 2, 2); next++; @@ -1860,8 +1841,7 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) case Capture: case Atomic: case Require when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL Require nodes) - case Loop when subsequent.M > 0: - case Lazyloop when subsequent.M > 0: + case Loop or Lazyloop when subsequent.M > 0: subsequent = subsequent.Child(0); continue; } @@ -1900,21 +1880,14 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) switch (subsequent.Type) { case One when node.Ch != subsequent.Ch: - case Onelazy when subsequent.M > 0 && node.Ch != subsequent.Ch: - case Oneloop when subsequent.M > 0 && node.Ch != subsequent.Ch: - case Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: + case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: case Notone when node.Ch == subsequent.Ch: - case Notonelazy when subsequent.M > 0 && node.Ch == subsequent.Ch: - case Notoneloop when subsequent.M > 0 && node.Ch == subsequent.Ch: - case Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: + case Notonelazy or Notoneloop or Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case Multi when node.Ch != subsequent.Str![0]: case Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): - case Setlazy when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): - case Setloop when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): - case Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): + case Setlazy or Setloop or Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case End: - case EndZ when node.Ch != '\n': - case Eol when node.Ch != '\n': + case EndZ or Eol when node.Ch != '\n': case Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): case NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): case ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): @@ -1927,9 +1900,7 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) switch (subsequent.Type) { case One when node.Ch == subsequent.Ch: - case Onelazy when subsequent.M > 0 && node.Ch == subsequent.Ch: - case Oneloop when subsequent.M > 0 && node.Ch == subsequent.Ch: - case Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: + case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case Multi when node.Ch == subsequent.Str![0]: case End: return true; @@ -1940,17 +1911,12 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) switch (subsequent.Type) { case One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): - case Onelazy when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): - case Oneloop when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): - case Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): + case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): - case Setlazy when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): - case Setloop when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): - case Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): + case Setlazy or Setloop or Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case End: - case EndZ when !RegexCharClass.CharInClass('\n', node.Str!): - case Eol when !RegexCharClass.CharInClass('\n', node.Str!): + case EndZ or Eol when !RegexCharClass.CharInClass('\n', node.Str!): case Boundary when node.Str == RegexCharClass.WordClass || node.Str == RegexCharClass.DigitClass: case NonBoundary when node.Str == RegexCharClass.NotWordClass || node.Str == RegexCharClass.NotDigitClass: case ECMABoundary when node.Str == RegexCharClass.ECMAWordClass || node.Str == RegexCharClass.ECMADigitClass: From 4e92eae9b90b6314c32b8911fb952c68a9fe1904 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 3 Jan 2022 14:56:44 -0500 Subject: [PATCH 17/97] Fix user => use typo in comments (#63288) --- .../Runtime/CompilerServices/RuntimeHelpers.cs | 2 +- .../Runtime/CompilerServices/TaskAwaiter.cs | 16 ++++++++-------- .../Runtime/CompilerServices/YieldAwaitable.cs | 2 +- .../src/System/Threading/Tasks/Future.cs | 2 +- .../src/System/Threading/Tasks/Task.cs | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index ddaf26982c575d..8187320ec97683 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -114,7 +114,7 @@ internal static bool IsPrimitiveType(this CorElementType et) /// A field handle that specifies the location of the data to be referred to by the ReadOnlySpan{T}. The Rva of the field must be aligned on a natural boundary of type T /// A ReadOnlySpan{T} of the data stored in the field /// does not refer to a field which is an Rva, is misaligned, or T is of an invalid type. - /// This method is intended for compiler user rather than use directly in code. T must be one of byte, sbyte, char, short, ushort, int, long, ulong, float, or double. + /// This method is intended for compiler use rather than use directly in code. T must be one of byte, sbyte, char, short, ushort, int, long, ulong, float, or double. [Intrinsic] public static unsafe ReadOnlySpan CreateSpan(RuntimeFieldHandle fldHandle) => new ReadOnlySpan(GetSpanDataFrom(fldHandle, typeof(T).TypeHandle, out int length), length); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs index 7e3666d23314d7..913cf3ae13abf5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -88,7 +88,7 @@ public void OnCompleted(Action continuation) /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); @@ -197,7 +197,7 @@ private static void ThrowForNonSuccess(Task task) /// Whether to flow ExecutionContext across the await. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException(nameof(continuation)); @@ -336,7 +336,7 @@ internal TaskAwaiter(Task task) /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); @@ -346,7 +346,7 @@ public void OnCompleted(Action continuation) /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); @@ -438,7 +438,7 @@ internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); @@ -448,7 +448,7 @@ public void OnCompleted(Action continuation) /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); @@ -523,7 +523,7 @@ internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContex /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); @@ -533,7 +533,7 @@ public void OnCompleted(Action continuation) /// The action to invoke when the await operation completes. /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs index 7500cba3d4e303..3e17c5b74d973c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -38,7 +38,7 @@ public readonly struct YieldAwaitable { /// Gets an awaiter for this . /// An awaiter for this awaitable. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public YieldAwaiter GetAwaiter() { return default; } /// Provides an awaiter that switches into a target environment. diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs index 72fd3feffff115..735a3d61e1ac9c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs @@ -516,7 +516,7 @@ internal override void InnerInvoke() /// Gets an awaiter used to await this . /// An awaiter instance. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public new TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index fe0db4cc3bd5db..96a13501ce91f4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -2428,7 +2428,7 @@ private void HandleException(Exception unhandledException) #region Await Support /// Gets an awaiter used to await this . /// An awaiter instance. - /// This method is intended for compiler user rather than use directly in code. + /// This method is intended for compiler use rather than use directly in code. public TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); From 046cbf0c412a2293536d5617e857a006f3c9bef8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 4 Jan 2022 05:00:43 +0900 Subject: [PATCH 18/97] Unify threading between crossgen2 and ilc (#63282) They don't have to differ in the `--parallelism` vs `--singlethreaded` argument. --- .../coreclr/debugging-aot-compilers.md | 2 +- .../Common/Compiler/CompilationBuilder.cs | 7 ++ .../Compiler/CompilationBuilder.Aot.cs | 7 -- .../ILCompiler.Compiler/Compiler/ILScanner.cs | 34 ++---- .../Compiler/ILScannerBuilder.cs | 8 +- .../ReadyToRunCodegenCompilationBuilder.cs | 7 -- .../Compiler/RyuJitCompilation.cs | 104 ++++++++---------- .../Compiler/RyuJitCompilationBuilder.cs | 5 +- .../ILCompiler.RyuJit.csproj | 2 +- src/coreclr/tools/aot/ILCompiler/Program.cs | 8 +- src/coreclr/tools/aot/crossgen2/Program.cs | 2 +- 11 files changed, 75 insertions(+), 111 deletions(-) diff --git a/docs/workflow/debugging/coreclr/debugging-aot-compilers.md b/docs/workflow/debugging/coreclr/debugging-aot-compilers.md index 048d571df45f21..0a216b7320100a 100644 --- a/docs/workflow/debugging/coreclr/debugging-aot-compilers.md +++ b/docs/workflow/debugging/coreclr/debugging-aot-compilers.md @@ -19,7 +19,7 @@ Built in debugging aids in the managed compilers --------------------------------- - When debugging a multi-threaded component of the compiler and not investigating a multi-threading issue itself, it is generally advisable to disable the use of multiple threads. -To do this use the `--parallelism 1` switch (for crossgen2) or `--singlethreaded` (for ILC) to specify that the maximum parallelism of the process shall be 1. +To do this use the `--parallelism 1` switch to specify that the maximum parallelism of the process shall be 1. - When debugging the behavior of compiling a single method, the compiler may be instructed to only compile a single method. This is done via the various --singlemethod options diff --git a/src/coreclr/tools/Common/Compiler/CompilationBuilder.cs b/src/coreclr/tools/Common/Compiler/CompilationBuilder.cs index f3c9e7ef8f8f2d..b246a9847f2274 100644 --- a/src/coreclr/tools/Common/Compiler/CompilationBuilder.cs +++ b/src/coreclr/tools/Common/Compiler/CompilationBuilder.cs @@ -23,6 +23,7 @@ public abstract partial class CompilationBuilder private DependencyTrackingLevel _dependencyTrackingLevel = DependencyTrackingLevel.None; protected IEnumerable _compilationRoots = Array.Empty(); protected OptimizationMode _optimizationMode = OptimizationMode.None; + protected int _parallelism = -1; public CompilationBuilder(CompilerTypeSystemContext context, CompilationModuleGroup compilationGroup, NameMangler nameMangler) { @@ -41,6 +42,12 @@ public CompilationBuilder UseLogger(Logger logger) return this; } + public CompilationBuilder UseParallelism(int parallelism) + { + _parallelism = parallelism; + return this; + } + public CompilationBuilder UseCompilationUnitPrefix(string prefix) { _nameMangler.CompilationUnitPrefix = prefix; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs index 25cd0bc9b85a6b..fb4ad5ce51b7f6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs @@ -22,7 +22,6 @@ partial class CompilationBuilder protected MethodImportationErrorProvider _methodImportationErrorProvider = new MethodImportationErrorProvider(); protected IInliningPolicy _inliningPolicy; protected bool _methodBodyFolding; - protected bool _singleThreaded; protected InstructionSetSupport _instructionSetSupport; protected SecurityMitigationOptions _mitigationOptions; @@ -92,12 +91,6 @@ public CompilationBuilder UseMethodBodyFolding(bool enable) return this; } - public CompilationBuilder UseSingleThread(bool enable) - { - _singleThreaded = enable; - return this; - } - public CompilationBuilder UsePreinitializationManager(PreinitializationManager manager) { _preinitializationManager = manager; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs index e10bbe95f07971..ae9e60343dfb42 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs @@ -4,18 +4,18 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Threading; +using System.Threading.Tasks; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; using Internal.IL; using Internal.IL.Stubs; +using Internal.JitInterface; using Internal.TypeSystem; using Internal.ReadyToRunConstants; using Debug = System.Diagnostics.Debug; -using Internal.JitInterface; namespace ILCompiler { @@ -26,8 +26,7 @@ namespace ILCompiler /// internal sealed class ILScanner : Compilation, IILScanner { - private CountdownEvent _compilationCountdown; - private readonly bool _singleThreaded; + private readonly int _parallelism; internal ILScanner( DependencyAnalyzerBase dependencyGraph, @@ -36,11 +35,11 @@ internal ILScanner( ILProvider ilProvider, DebugInformationProvider debugInformationProvider, Logger logger, - bool singleThreaded) + int parallelism) : base(dependencyGraph, nodeFactory, roots, ilProvider, debugInformationProvider, null, nodeFactory.CompilationModuleGroup, logger) { _helperCache = new HelperCache(this); - _singleThreaded = singleThreaded; + _parallelism = parallelism; } protected override void CompileInternal(string outputFile, ObjectDumper dumper) @@ -78,7 +77,7 @@ protected override void ComputeDependencyNodeDependencies(List methodsToCompile) Logger.Writer.WriteLine($"Scanning {methodsToCompile.Count} methods..."); } - WaitCallback compileSingleMethodDelegate = m => CompileSingleMethod((ScannedMethodNode)m); - - using (_compilationCountdown = new CountdownEvent(methodsToCompile.Count)) - { - foreach (ScannedMethodNode methodCodeNodeNeedingCode in methodsToCompile) - { - ThreadPool.QueueUserWorkItem(compileSingleMethodDelegate, methodCodeNodeNeedingCode); - } - - _compilationCountdown.Wait(); - _compilationCountdown = null; - } + Parallel.ForEach( + methodsToCompile, + new ParallelOptions { MaxDegreeOfParallelism = _parallelism }, + CompileSingleMethod); } private void CompileSingleThreaded(List methodsToCompile) @@ -142,11 +133,6 @@ private void CompileSingleMethod(ScannedMethodNode methodCodeNodeNeedingCode) { throw new CodeGenerationFailedException(method, ex); } - finally - { - if (_compilationCountdown != null) - _compilationCountdown.Signal(); - } } ILScanResults IILScanner.Scan() diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs index 27e7e64b6ce193..cf784d458dde24 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs @@ -27,7 +27,7 @@ public sealed class ILScannerBuilder private IEnumerable _compilationRoots = Array.Empty(); private MetadataManager _metadataManager; private InteropStubManager _interopStubManager = new EmptyInteropStubManager(); - private bool _singleThreaded; + private int _parallelism = -1; internal ILScannerBuilder(CompilerTypeSystemContext context, CompilationModuleGroup compilationGroup, NameMangler mangler, ILProvider ilProvider, PreinitializationManager preinitializationManager) { @@ -63,9 +63,9 @@ public ILScannerBuilder UseInteropStubManager(InteropStubManager interopStubMana return this; } - public ILScannerBuilder UseSingleThread(bool enable) + public ILScannerBuilder UseParallelism(int parallelism) { - _singleThreaded = enable; + _parallelism = parallelism; return this; } @@ -74,7 +74,7 @@ public IILScanner ToILScanner() var nodeFactory = new ILScanNodeFactory(_context, _compilationGroup, _metadataManager, _interopStubManager, _nameMangler, _preinitializationManager); DependencyAnalyzerBase graph = _dependencyTrackingLevel.CreateDependencyGraph(nodeFactory); - return new ILScanner(graph, nodeFactory, _compilationRoots, _ilProvider, new NullDebugInformationProvider(), _logger, _singleThreaded); + return new ILScanner(graph, nodeFactory, _compilationRoots, _ilProvider, new NullDebugInformationProvider(), _logger, _parallelism); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs index 34aced76b44b01..8f468f78b39771 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCodegenCompilationBuilder.cs @@ -33,7 +33,6 @@ public sealed class ReadyToRunCodegenCompilationBuilder : CompilationBuilder private string _perfMapPath; private int _perfMapFormatVersion; private bool _generateProfileFile; - private int _parallelism; Func _printReproInstructions; private InstructionSetSupport _instructionSetSupport; private ProfileDataManager _profileData; @@ -170,12 +169,6 @@ public ReadyToRunCodegenCompilationBuilder UseProfileFile(bool generateProfileFi return this; } - public ReadyToRunCodegenCompilationBuilder UseParallelism(int parallelism) - { - _parallelism = parallelism; - return this; - } - public ReadyToRunCodegenCompilationBuilder UsePrintReproInstructions(Func printReproInstructions) { _printReproInstructions = printReproInstructions; diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilation.cs b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilation.cs index e794bdd1a94790..0d8b11c51f82e2 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilation.cs +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilation.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; +using System.Threading.Tasks; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; @@ -21,10 +22,10 @@ public sealed class RyuJitCompilation : Compilation private readonly ConditionalWeakTable _corinfos = new ConditionalWeakTable(); internal readonly RyuJitCompilationOptions _compilationOptions; private readonly ExternSymbolMappedField _hardwareIntrinsicFlags; - private CountdownEvent _compilationCountdown; private readonly Dictionary _instructionSetMap; private readonly ProfileDataManager _profileDataManager; private readonly MethodImportationErrorProvider _methodImportationErrorProvider; + private readonly int _parallelism; public InstructionSetSupport InstructionSetSupport { get; } @@ -40,7 +41,8 @@ internal RyuJitCompilation( InstructionSetSupport instructionSetSupport, ProfileDataManager profileDataManager, MethodImportationErrorProvider errorProvider, - RyuJitCompilationOptions options) + RyuJitCompilationOptions options, + int parallelism) : base(dependencyGraph, nodeFactory, roots, ilProvider, debugInformationProvider, devirtualizationManager, inliningPolicy, logger) { _compilationOptions = options; @@ -59,6 +61,8 @@ internal RyuJitCompilation( _profileDataManager = profileDataManager; _methodImportationErrorProvider = errorProvider; + + _parallelism = parallelism; } public ProfileDataManager ProfileData => _profileDataManager; @@ -125,7 +129,7 @@ protected override void ComputeDependencyNodeDependencies(List methodsToCompile) Logger.Writer.WriteLine($"Compiling {methodsToCompile.Count} methods..."); } - WaitCallback compileSingleMethodDelegate = m => - { - CorInfoImpl corInfo = _corinfos.GetValue(Thread.CurrentThread, thread => new CorInfoImpl(this)); - CompileSingleMethod(corInfo, (MethodCodeNode)m); - }; - - using (_compilationCountdown = new CountdownEvent(methodsToCompile.Count)) - { - - foreach (MethodCodeNode methodCodeNodeNeedingCode in methodsToCompile) - { - ThreadPool.QueueUserWorkItem(compileSingleMethodDelegate, methodCodeNodeNeedingCode); - } - - _compilationCountdown.Wait(); - _compilationCountdown = null; - } + Parallel.ForEach( + methodsToCompile, + new ParallelOptions { MaxDegreeOfParallelism = _parallelism }, + CompileSingleMethod); } @@ -176,52 +167,50 @@ private void CompileSingleThreaded(List methodsToCompile) } } + private void CompileSingleMethod(MethodCodeNode methodCodeNodeNeedingCode) + { + CorInfoImpl corInfo = _corinfos.GetValue(Thread.CurrentThread, thread => new CorInfoImpl(this)); + CompileSingleMethod(corInfo, methodCodeNodeNeedingCode); + } + private void CompileSingleMethod(CorInfoImpl corInfo, MethodCodeNode methodCodeNodeNeedingCode) { - try - { - MethodDesc method = methodCodeNodeNeedingCode.Method; + MethodDesc method = methodCodeNodeNeedingCode.Method; - TypeSystemException exception = _methodImportationErrorProvider.GetCompilationError(method); + TypeSystemException exception = _methodImportationErrorProvider.GetCompilationError(method); - // If we previously failed to import the method, do not try to import it again and go - // directly to the error path. - if (exception == null) + // If we previously failed to import the method, do not try to import it again and go + // directly to the error path. + if (exception == null) + { + try { - try - { - corInfo.CompileMethod(methodCodeNodeNeedingCode); - } - catch (TypeSystemException ex) - { - exception = ex; - } + corInfo.CompileMethod(methodCodeNodeNeedingCode); } - - if (exception != null) + catch (TypeSystemException ex) { - // TODO: fail compilation if a switch was passed - - // Try to compile the method again, but with a throwing method body this time. - MethodIL throwingIL = TypeSystemThrowingILEmitter.EmitIL(method, exception); - corInfo.CompileMethod(methodCodeNodeNeedingCode, throwingIL); - - if (exception is TypeSystemException.InvalidProgramException - && method.OwningType is MetadataType mdOwningType - && mdOwningType.HasCustomAttribute("System.Runtime.InteropServices", "ClassInterfaceAttribute")) - { - Logger.LogWarning("COM interop is not supported with full ahead of time compilation", 3052, method, MessageSubCategory.AotAnalysis); - } - else - { - Logger.LogWarning($"Method will always throw because: {exception.Message}", 1005, method, MessageSubCategory.AotAnalysis); - } + exception = ex; } } - finally + + if (exception != null) { - if (_compilationCountdown != null) - _compilationCountdown.Signal(); + // TODO: fail compilation if a switch was passed + + // Try to compile the method again, but with a throwing method body this time. + MethodIL throwingIL = TypeSystemThrowingILEmitter.EmitIL(method, exception); + corInfo.CompileMethod(methodCodeNodeNeedingCode, throwingIL); + + if (exception is TypeSystemException.InvalidProgramException + && method.OwningType is MetadataType mdOwningType + && mdOwningType.HasCustomAttribute("System.Runtime.InteropServices", "ClassInterfaceAttribute")) + { + Logger.LogWarning("COM interop is not supported with full ahead of time compilation", 3052, method, MessageSubCategory.AotAnalysis); + } + else + { + Logger.LogWarning($"Method will always throw because: {exception.Message}", 1005, method, MessageSubCategory.AotAnalysis); + } } } @@ -252,7 +241,6 @@ public override MethodIL GetMethodIL(MethodDesc method) public enum RyuJitCompilationOptions { MethodBodyFolding = 0x1, - SingleThreadedCompilation = 0x2, - ControlFlowGuardAnnotations = 0x4, + ControlFlowGuardAnnotations = 0x2, } } diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilationBuilder.cs b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilationBuilder.cs index 162f1a39e86bbc..8b753c71039942 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilationBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/RyuJitCompilationBuilder.cs @@ -107,9 +107,6 @@ public override ICompilation ToCompilation() if (_methodBodyFolding) options |= RyuJitCompilationOptions.MethodBodyFolding; - if (_singleThreaded) - options |= RyuJitCompilationOptions.SingleThreadedCompilation; - if ((_mitigationOptions & SecurityMitigationOptions.ControlFlowGuardAnnotations) != 0) options |= RyuJitCompilationOptions.ControlFlowGuardAnnotations; @@ -117,7 +114,7 @@ public override ICompilation ToCompilation() JitConfigProvider.Initialize(_context.Target, jitFlagBuilder.ToArray(), _ryujitOptions); DependencyAnalyzerBase graph = CreateDependencyGraph(factory, new ObjectNode.ObjectNodeComparer(new CompilerComparer())); - return new RyuJitCompilation(graph, factory, _compilationRoots, _ilProvider, _debugInformationProvider, _logger, _devirtualizationManager, _inliningPolicy ?? _compilationGroup, _instructionSetSupport, _profileDataManager, _methodImportationErrorProvider, options); + return new RyuJitCompilation(graph, factory, _compilationRoots, _ilProvider, _debugInformationProvider, _logger, _devirtualizationManager, _inliningPolicy ?? _compilationGroup, _instructionSetSupport, _profileDataManager, _methodImportationErrorProvider, options, _parallelism); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/ILCompiler.RyuJit.csproj b/src/coreclr/tools/aot/ILCompiler.RyuJit/ILCompiler.RyuJit.csproj index efff02a77708c0..cecc90d6da81b0 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/ILCompiler.RyuJit.csproj +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/ILCompiler.RyuJit.csproj @@ -3,7 +3,7 @@ Library ILCompiler ILCompiler.RyuJit - net5.0 + net6.0 true false x64;x86 diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index d9b7d79b012d3b..5cfac3990b7673 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -57,7 +57,7 @@ internal class Program private bool _reflectedOnly; private bool _scanReflection; private bool _methodBodyFolding; - private bool _singleThreaded; + private int _parallelism = Environment.ProcessorCount; private string _instructionSet; private string _guard; @@ -205,7 +205,7 @@ private ArgumentSyntax ParseCommandLine(string[] args) syntax.DefineOptionList("appcontextswitch", ref _appContextSwitches, "System.AppContext switches to set (format: 'Key=Value')"); syntax.DefineOptionList("feature", ref _featureSwitches, "Feature switches to apply (format: 'Namespace.Name=[true|false]'"); syntax.DefineOptionList("runtimeopt", ref _runtimeOptions, "Runtime options to set"); - syntax.DefineOption("singlethreaded", ref _singleThreaded, "Run compilation on a single thread"); + syntax.DefineOption("parallelism", ref _parallelism, "Maximum number of threads to use during compilation"); syntax.DefineOption("instructionset", ref _instructionSet, "Instruction set to allow or disallow"); syntax.DefineOption("guard", ref _guard, "Enable mitigations. Options: 'cf': CFG (Control Flow Guard, Windows only)"); syntax.DefineOption("preinitstatics", ref _preinitStatics, "Interpret static constructors at compile time if possible (implied by -O)"); @@ -730,7 +730,7 @@ static string ILLinkify(string rootedAssembly) ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder() .UseCompilationRoots(compilationRoots) .UseMetadataManager(metadataManager) - .UseSingleThread(enable: _singleThreaded) + .UseParallelism(_parallelism) .UseInteropStubManager(interopStubManager); if (_scanDgmlLogFileName != null) @@ -759,7 +759,7 @@ static string ILLinkify(string rootedAssembly) .UseInstructionSetSupport(instructionSetSupport) .UseBackendOptions(_codegenOptions) .UseMethodBodyFolding(enable: _methodBodyFolding) - .UseSingleThread(enable: _singleThreaded) + .UseParallelism(_parallelism) .UseMetadataManager(metadataManager) .UseInteropStubManager(interopStubManager) .UseLogger(logger) diff --git a/src/coreclr/tools/aot/crossgen2/Program.cs b/src/coreclr/tools/aot/crossgen2/Program.cs index d4c693805f5e20..ff538c05fd64c4 100644 --- a/src/coreclr/tools/aot/crossgen2/Program.cs +++ b/src/coreclr/tools/aot/crossgen2/Program.cs @@ -736,7 +736,6 @@ private void RunSingleCompilation(Dictionary inFilePaths, Instru .UsePdbFile(_commandLineOptions.Pdb, _commandLineOptions.PdbPath) .UsePerfMapFile(_commandLineOptions.PerfMap, _commandLineOptions.PerfMapPath, _commandLineOptions.PerfMapFormatVersion) .UseProfileFile(jsonProfile != null) - .UseParallelism(_commandLineOptions.Parallelism) .UseProfileData(profileDataManager) .FileLayoutAlgorithms(_methodLayout, _fileLayout) .UseCompositeImageSettings(compositeImageSettings) @@ -748,6 +747,7 @@ private void RunSingleCompilation(Dictionary inFilePaths, Instru .UseILProvider(ilProvider) .UseBackendOptions(_commandLineOptions.CodegenOptions) .UseLogger(logger) + .UseParallelism(_commandLineOptions.Parallelism) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(optimizationMode); From 9472bfe8ceb58f8097e48f7e271db8e99903eba1 Mon Sep 17 00:00:00 2001 From: NN <580536+NN---@users.noreply.github.com> Date: Mon, 3 Jan 2022 22:29:30 +0200 Subject: [PATCH 19/97] Use SAL2 _In_, _Out_ to prevent conflicts (#63261) --- src/coreclr/debug/daccess/daccess.cpp | 34 ++++---- src/coreclr/debug/daccess/dacfn.cpp | 2 +- src/coreclr/debug/daccess/dacimpl.h | 6 +- src/coreclr/debug/di/publish.cpp | 2 +- src/coreclr/debug/di/rspriv.h | 2 +- src/coreclr/debug/di/shimcallback.cpp | 6 +- src/coreclr/debug/di/shimpriv.h | 10 +-- src/coreclr/dlls/dbgshim/dbgshim.cpp | 82 +++++++++--------- src/coreclr/dlls/dbgshim/dbgshim.h | 78 ++++++++--------- src/coreclr/dlls/mscoree/mscoree.cpp | 2 +- src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp | 8 +- src/coreclr/dlls/mscorpe/iceefilegen.cpp | 16 ++-- src/coreclr/dlls/mscorpe/pewriter.cpp | 4 +- src/coreclr/dlls/mscorpe/pewriter.h | 8 +- src/coreclr/ilasm/asmman.cpp | 28 +++---- src/coreclr/ilasm/asmman.hpp | 32 +++---- src/coreclr/ilasm/asmparse.h | 30 +++---- src/coreclr/ilasm/assem.cpp | 6 +- src/coreclr/ilasm/assembler.cpp | 44 +++++----- src/coreclr/ilasm/assembler.h | 84 +++++++++---------- src/coreclr/ilasm/grammar_after.cpp | 30 +++---- src/coreclr/ilasm/grammar_before.cpp | 16 ++-- src/coreclr/ilasm/main.cpp | 10 +-- src/coreclr/ilasm/method.cpp | 2 +- src/coreclr/ilasm/method.hpp | 6 +- src/coreclr/ilasm/writer.cpp | 4 +- src/coreclr/ildasm/dasm.cpp | 14 ++-- src/coreclr/ildasm/dasm_formattype.cpp | 8 +- src/coreclr/ildasm/dis.cpp | 32 +++---- src/coreclr/ildasm/dis.h | 24 +++--- src/coreclr/ildasm/dres.cpp | 2 +- src/coreclr/ildasm/windasm.cpp | 16 ++-- src/coreclr/inc/blobfetcher.h | 12 +-- src/coreclr/inc/ceefilegenwriter.h | 10 +-- src/coreclr/inc/ceegen.h | 14 ++-- src/coreclr/inc/clrconfig.h | 2 +- src/coreclr/inc/clrnt.h | 36 ++++---- src/coreclr/inc/cycletimer.h | 4 +- src/coreclr/inc/daccess.h | 6 +- src/coreclr/inc/eventtracebase.h | 22 ++--- src/coreclr/inc/formattype.h | 8 +- src/coreclr/inc/fstring.h | 4 +- src/coreclr/inc/loaderheap.h | 36 ++++---- src/coreclr/inc/pesectionman.h | 4 +- src/coreclr/inc/stacktrace.h | 2 +- src/coreclr/inc/strongnameholders.h | 2 +- src/coreclr/inc/utilcode.h | 24 +++--- src/coreclr/jit/gentree.cpp | 4 +- src/coreclr/md/ceefilegen/blobfetcher.cpp | 4 +- src/coreclr/md/ceefilegen/cceegen.cpp | 2 +- src/coreclr/md/ceefilegen/pesectionman.cpp | 4 +- src/coreclr/md/compiler/regmeta.cpp | 10 +-- src/coreclr/md/compiler/regmeta.h | 22 ++--- .../md/compiler/regmeta_imetadatatables.cpp | 24 +++--- src/coreclr/md/compressedinteger.h | 6 +- src/coreclr/md/compressedinteger.inl | 6 +- src/coreclr/md/datablob.h | 30 +++---- src/coreclr/md/datablob.inl | 30 +++---- src/coreclr/md/enc/mdinternalrw.cpp | 2 +- src/coreclr/md/enc/stgtiggerstorage.cpp | 8 +- src/coreclr/md/heaps/blobheap.h | 14 ++-- src/coreclr/md/heaps/guidheap.h | 6 +- src/coreclr/md/heaps/stringheap.h | 10 +-- src/coreclr/md/inc/metamodel.h | 6 +- src/coreclr/md/inc/metamodelro.h | 4 +- src/coreclr/md/inc/metamodelrw.h | 4 +- src/coreclr/md/inc/stgtiggerstorage.h | 10 +-- src/coreclr/md/runtime/mdinternalro.cpp | 2 +- src/coreclr/md/tables/table.h | 4 +- src/coreclr/nativeaot/Runtime/eventtrace.cpp | 8 +- .../nativeaot/Runtime/eventtracebase.h | 20 ++--- src/coreclr/nativeaot/Runtime/inc/daccess.h | 2 +- src/coreclr/pal/inc/rt/sal.h | 6 -- src/coreclr/pal/inc/rt/specstrings.h | 6 +- src/coreclr/pal/inc/rt/specstrings_strict.h | 20 ++--- src/coreclr/pal/src/safecrt/internal.h | 58 ++++++------- .../pal/src/safecrt/internal_securecrt.h | 2 +- src/coreclr/pal/src/safecrt/tsplitpath_s.inl | 8 +- src/coreclr/tools/metainfo/mdinfo.cpp | 12 +-- src/coreclr/tools/metainfo/mdinfo.h | 12 +-- src/coreclr/tools/metainfo/mdobj.cpp | 6 +- src/coreclr/tools/util/consoleargs.cpp | 4 +- src/coreclr/tools/util/consoleargs.h | 4 +- src/coreclr/unwinder/amd64/dbs_stack_x64.cpp | 42 +++++----- src/coreclr/unwinder/amd64/unwinder_amd64.cpp | 54 ++++++------ src/coreclr/unwinder/amd64/unwinder_amd64.h | 40 ++++----- src/coreclr/unwinder/arm/unwinder_arm.cpp | 68 +++++++-------- src/coreclr/unwinder/arm/unwinder_arm.h | 30 +++---- src/coreclr/unwinder/arm64/unwinder_arm64.cpp | 50 +++++------ src/coreclr/unwinder/arm64/unwinder_arm64.h | 30 +++---- src/coreclr/unwinder/i386/unwinder_i386.cpp | 24 +++--- src/coreclr/unwinder/i386/unwinder_i386.h | 12 +-- src/coreclr/unwinder/unwinder.cpp | 2 +- src/coreclr/unwinder/unwinder.h | 2 +- src/coreclr/utilcode/clrconfig.cpp | 2 +- src/coreclr/utilcode/fstring.cpp | 4 +- src/coreclr/utilcode/loaderheap.cpp | 20 ++--- src/coreclr/utilcode/makepath.cpp | 10 +-- src/coreclr/utilcode/splitpath.cpp | 4 +- src/coreclr/utilcode/stacktrace.cpp | 2 +- src/coreclr/utilcode/util.cpp | 2 +- src/coreclr/vm/ceemain.cpp | 4 +- src/coreclr/vm/clsload.cpp | 2 +- src/coreclr/vm/clsload.hpp | 2 +- src/coreclr/vm/codeman.cpp | 6 +- src/coreclr/vm/codeman.h | 6 +- src/coreclr/vm/eventreporter.cpp | 2 +- src/coreclr/vm/eventreporter.h | 2 +- src/coreclr/vm/eventtrace.cpp | 8 +- src/coreclr/vm/interpreter.cpp | 4 +- src/mono/dlls/dbgshim/dbgshim.cpp | 78 ++++++++--------- src/mono/dlls/dbgshim/dbgshim.h | 78 ++++++++--------- 112 files changed, 896 insertions(+), 908 deletions(-) diff --git a/src/coreclr/debug/daccess/daccess.cpp b/src/coreclr/debug/daccess/daccess.cpp index f9ec95c1f41838..1280b69561c8b3 100644 --- a/src/coreclr/debug/daccess/daccess.cpp +++ b/src/coreclr/debug/daccess/daccess.cpp @@ -92,7 +92,7 @@ BOOL WINAPI DllMain(HANDLE instance, DWORD reason, LPVOID reserved) } HRESULT -ConvertUtf8(__in LPCUTF8 utf8, +ConvertUtf8(_In_ LPCUTF8 utf8, ULONG32 bufLen, ULONG32* nameLen, __out_ecount_part_opt(bufLen, *nameLen) PWSTR buffer) @@ -228,7 +228,7 @@ GetFullMethodNameFromMetadata(IMDInternalImport* mdImport, } HRESULT -SplitFullName(__in_z __in PCWSTR fullName, +SplitFullName(__in_z _In_ PCWSTR fullName, SplitSyntax syntax, ULONG32 memberDots, __deref_out_opt LPUTF8* namespaceName, @@ -401,7 +401,7 @@ SplitFullName(__in_z __in PCWSTR fullName, } int -CompareUtf8(__in LPCUTF8 str1, __in LPCUTF8 str2, __in ULONG32 nameFlags) +CompareUtf8(_In_ LPCUTF8 str1, _In_ LPCUTF8 str2, _In_ ULONG32 nameFlags) { if (nameFlags & CLRDATA_BYNAME_CASE_INSENSITIVE) { @@ -7565,9 +7565,9 @@ typedef struct _WER_RUNTIME_EXCEPTION_INFORMATION // else detailed error code. // //---------------------------------------------------------------------------- -STDAPI OutOfProcessExceptionEventGetWatsonBucket(__in PDWORD pContext, - __in const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, - __out GenericModeBlock * pGMB) +STDAPI OutOfProcessExceptionEventGetWatsonBucket(_In_ PDWORD pContext, + _In_ const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, + _Out_ GenericModeBlock * pGMB) { HANDLE hProcess = pExceptionInformation->hProcess; HANDLE hThread = pExceptionInformation->hThread; @@ -7656,12 +7656,12 @@ STDAPI OutOfProcessExceptionEventGetWatsonBucket(__in PDWORD pContext, // Since this is called by external modules it's important that we don't let any exceptions leak out (see Win8 95224). // //---------------------------------------------------------------------------- -STDAPI OutOfProcessExceptionEventCallback(__in PDWORD pContext, - __in const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, - __out BOOL * pbOwnershipClaimed, +STDAPI OutOfProcessExceptionEventCallback(_In_ PDWORD pContext, + _In_ const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, + _Out_ BOOL * pbOwnershipClaimed, __out_ecount(*pchSize) PWSTR pwszEventName, __inout PDWORD pchSize, - __out PDWORD pdwSignatureCount) + _Out_ PDWORD pdwSignatureCount) { SUPPORTS_DAC_HOST_ONLY; @@ -7748,9 +7748,9 @@ STDAPI OutOfProcessExceptionEventCallback(__in PDWORD pContext, // Since this is called by external modules it's important that we don't let any exceptions leak out (see Win8 95224). // //---------------------------------------------------------------------------- -STDAPI OutOfProcessExceptionEventSignatureCallback(__in PDWORD pContext, - __in const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, - __in DWORD dwIndex, +STDAPI OutOfProcessExceptionEventSignatureCallback(_In_ PDWORD pContext, + _In_ const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, + _In_ DWORD dwIndex, __out_ecount(*pchName) PWSTR pwszName, __inout PDWORD pchName, __out_ecount(*pchValue) PWSTR pwszValue, @@ -7873,12 +7873,12 @@ STDAPI OutOfProcessExceptionEventSignatureCallback(__in PDWORD pContext, // this function are of the pwszName and pwszValue buffers. // //---------------------------------------------------------------------------- -STDAPI OutOfProcessExceptionEventDebuggerLaunchCallback(__in PDWORD pContext, - __in const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, - __out BOOL * pbCustomDebuggerNeeded, +STDAPI OutOfProcessExceptionEventDebuggerLaunchCallback(_In_ PDWORD pContext, + _In_ const PWER_RUNTIME_EXCEPTION_INFORMATION pExceptionInformation, + _Out_ BOOL * pbCustomDebuggerNeeded, __out_ecount_opt(*pchSize) PWSTR pwszDebuggerLaunch, __inout PDWORD pchSize, - __out BOOL * pbAutoLaunchDebugger) + _Out_ BOOL * pbAutoLaunchDebugger) { SUPPORTS_DAC_HOST_ONLY; diff --git a/src/coreclr/debug/daccess/dacfn.cpp b/src/coreclr/debug/daccess/dacfn.cpp index e1b83aba17e20c..11f798ed04c199 100644 --- a/src/coreclr/debug/daccess/dacfn.cpp +++ b/src/coreclr/debug/daccess/dacfn.cpp @@ -89,7 +89,7 @@ DacExceptionFilter(Exception* ex, ClrDataAccess* access, } void __cdecl -DacWarning(__in char* format, ...) +DacWarning(_In_ char* format, ...) { char text[256]; va_list args; diff --git a/src/coreclr/debug/daccess/dacimpl.h b/src/coreclr/debug/daccess/dacimpl.h index 948bef16e498da..03697ba5ab53c0 100644 --- a/src/coreclr/debug/daccess/dacimpl.h +++ b/src/coreclr/debug/daccess/dacimpl.h @@ -222,7 +222,7 @@ struct METH_EXTENTS CLRDATA_ADDRESS_RANGE extents[1]; }; -HRESULT ConvertUtf8(__in LPCUTF8 utf8, +HRESULT ConvertUtf8(_In_ LPCUTF8 utf8, ULONG32 bufLen, ULONG32* nameLen, __out_ecount_part_opt(bufLen, *nameLen) PWSTR buffer); @@ -247,7 +247,7 @@ enum SplitSyntax SPLIT_NO_NAME, }; -HRESULT SplitFullName(__in_z __in PCWSTR fullName, +HRESULT SplitFullName(__in_z _In_ PCWSTR fullName, SplitSyntax syntax, ULONG32 memberDots, __deref_out_opt LPUTF8* namespaceName, @@ -255,7 +255,7 @@ HRESULT SplitFullName(__in_z __in PCWSTR fullName, __deref_out_opt LPUTF8* memberName, __deref_out_opt LPUTF8* params); -int CompareUtf8(__in LPCUTF8 str1, __in LPCUTF8 str2, __in ULONG32 nameFlags); +int CompareUtf8(_In_ LPCUTF8 str1, _In_ LPCUTF8 str2, _In_ ULONG32 nameFlags); #define INH_STATIC \ (CLRDATA_VALUE_ALL_KINDS | \ diff --git a/src/coreclr/debug/di/publish.cpp b/src/coreclr/debug/di/publish.cpp index 23003b980ad9f1..801e334c323037 100644 --- a/src/coreclr/debug/di/publish.cpp +++ b/src/coreclr/debug/di/publish.cpp @@ -928,7 +928,7 @@ HRESULT CorpubProcess::GetDisplayName(ULONG32 cchName, // CorpubAppDomain // ****************************************** -CorpubAppDomain::CorpubAppDomain (__in LPWSTR szAppDomainName, ULONG Id) +CorpubAppDomain::CorpubAppDomain (_In_ LPWSTR szAppDomainName, ULONG Id) : CordbCommonBase (0, enumCorpubAppDomain), m_pNext (NULL), m_szAppDomainName (szAppDomainName), diff --git a/src/coreclr/debug/di/rspriv.h b/src/coreclr/debug/di/rspriv.h index a34dd0e6a07288..5a89337f5a990d 100644 --- a/src/coreclr/debug/di/rspriv.h +++ b/src/coreclr/debug/di/rspriv.h @@ -10838,7 +10838,7 @@ class CorpubProcess : public CordbCommonBase, public ICorPublishProcess class CorpubAppDomain : public CordbCommonBase, public ICorPublishAppDomain { public: - CorpubAppDomain (__in LPWSTR szAppDomainName, ULONG Id); + CorpubAppDomain (_In_ LPWSTR szAppDomainName, ULONG Id); virtual ~CorpubAppDomain(); #ifdef _DEBUG diff --git a/src/coreclr/debug/di/shimcallback.cpp b/src/coreclr/debug/di/shimcallback.cpp index ba5f0771fca49a..4e8f029209def7 100644 --- a/src/coreclr/debug/di/shimcallback.cpp +++ b/src/coreclr/debug/di/shimcallback.cpp @@ -659,7 +659,7 @@ HRESULT ShimProxyCallback::DebuggerError(ICorDebugProcess * pProcess, HRESULT er // Implementation of ICorDebugManagedCallback::LogMessage -HRESULT ShimProxyCallback::LogMessage(ICorDebugAppDomain * pAppDomain, ICorDebugThread * pThread, LONG lLevel, __in LPWSTR pLogSwitchName, __in LPWSTR pMessage) +HRESULT ShimProxyCallback::LogMessage(ICorDebugAppDomain * pAppDomain, ICorDebugThread * pThread, LONG lLevel, _In_ LPWSTR pLogSwitchName, _In_ LPWSTR pMessage) { m_pShim->PreDispatchEvent(); class LogMessageEvent : public ManagedEvent @@ -695,7 +695,7 @@ HRESULT ShimProxyCallback::LogMessage(ICorDebugAppDomain * pAppDomain, ICorDebug // Implementation of ICorDebugManagedCallback::LogSwitch -HRESULT ShimProxyCallback::LogSwitch(ICorDebugAppDomain * pAppDomain, ICorDebugThread * pThread, LONG lLevel, ULONG ulReason, __in LPWSTR pLogSwitchName, __in LPWSTR pParentName) +HRESULT ShimProxyCallback::LogSwitch(ICorDebugAppDomain * pAppDomain, ICorDebugThread * pThread, LONG lLevel, ULONG ulReason, _In_ LPWSTR pLogSwitchName, _In_ LPWSTR pParentName) { m_pShim->PreDispatchEvent(); class LogSwitchEvent : public ManagedEvent @@ -1060,7 +1060,7 @@ HRESULT ShimProxyCallback::FunctionRemapOpportunity(ICorDebugAppDomain * pAppDom // Implementation of ICorDebugManagedCallback2::CreateConnection -HRESULT ShimProxyCallback::CreateConnection(ICorDebugProcess * pProcess, CONNID dwConnectionId, __in LPWSTR pConnectionName) +HRESULT ShimProxyCallback::CreateConnection(ICorDebugProcess * pProcess, CONNID dwConnectionId, _In_ LPWSTR pConnectionName) { m_pShim->PreDispatchEvent(); class CreateConnectionEvent : public ManagedEvent diff --git a/src/coreclr/debug/di/shimpriv.h b/src/coreclr/debug/di/shimpriv.h index 89a0c0d0c79374..56365229c8a766 100644 --- a/src/coreclr/debug/di/shimpriv.h +++ b/src/coreclr/debug/di/shimpriv.h @@ -128,15 +128,15 @@ class ShimProxyCallback : COM_METHOD LogMessage( ICorDebugAppDomain *pAppDomain, ICorDebugThread *pThread, LONG lLevel, - __in LPWSTR pLogSwitchName, - __in LPWSTR pMessage); + _In_ LPWSTR pLogSwitchName, + _In_ LPWSTR pMessage); COM_METHOD LogSwitch( ICorDebugAppDomain *pAppDomain, ICorDebugThread *pThread, LONG lLevel, ULONG ulReason, - __in LPWSTR pLogSwitchName, - __in LPWSTR pParentName); + _In_ LPWSTR pLogSwitchName, + _In_ LPWSTR pParentName); COM_METHOD CreateAppDomain(ICorDebugProcess *pProcess, ICorDebugAppDomain *pAppDomain); @@ -178,7 +178,7 @@ class ShimProxyCallback : ICorDebugFunction *pNewFunction, ULONG32 oldILOffset); - COM_METHOD CreateConnection(ICorDebugProcess *pProcess, CONNID dwConnectionId, __in LPWSTR pConnName); + COM_METHOD CreateConnection(ICorDebugProcess *pProcess, CONNID dwConnectionId, _In_ LPWSTR pConnName); COM_METHOD ChangeConnection(ICorDebugProcess *pProcess, CONNID dwConnectionId ); diff --git a/src/coreclr/dlls/dbgshim/dbgshim.cpp b/src/coreclr/dlls/dbgshim/dbgshim.cpp index ac1e2d7fe189ac..0372a3591d7317 100644 --- a/src/coreclr/dlls/dbgshim/dbgshim.cpp +++ b/src/coreclr/dlls/dbgshim/dbgshim.cpp @@ -79,12 +79,12 @@ if it exists, it will: DLLEXPORT HRESULT CreateProcessForLaunch( - __in LPWSTR lpCommandLine, - __in BOOL bSuspendProcess, - __in LPVOID lpEnvironment, - __in LPCWSTR lpCurrentDirectory, - __out PDWORD pProcessId, - __out HANDLE *pResumeHandle) + _In_ LPWSTR lpCommandLine, + _In_ BOOL bSuspendProcess, + _In_ LPVOID lpEnvironment, + _In_ LPCWSTR lpCurrentDirectory, + _Out_ PDWORD pProcessId, + _Out_ HANDLE *pResumeHandle) { PUBLIC_CONTRACT; @@ -140,7 +140,7 @@ CreateProcessForLaunch( DLLEXPORT HRESULT ResumeProcess( - __in HANDLE hResumeHandle) + _In_ HANDLE hResumeHandle) { PUBLIC_CONTRACT; if (ResumeThread(hResumeHandle) == (DWORD)-1) @@ -159,7 +159,7 @@ ResumeProcess( DLLEXPORT HRESULT CloseResumeHandle( - __in HANDLE hResumeHandle) + _In_ HANDLE hResumeHandle) { PUBLIC_CONTRACT; if (!CloseHandle(hResumeHandle)) @@ -190,7 +190,7 @@ HRESULT GetContinueStartupEvent( DWORD debuggeePID, LPCWSTR szTelestoFullPath, - __out HANDLE *phContinueStartupEvent); + _Out_ HANDLE *phContinueStartupEvent); #endif // TARGET_UNIX @@ -697,10 +697,10 @@ StartupHelperThread(LPVOID p) DLLEXPORT HRESULT RegisterForRuntimeStartup( - __in DWORD dwProcessId, - __in PSTARTUP_CALLBACK pfnCallback, - __in PVOID parameter, - __out PVOID *ppUnregisterToken) + _In_ DWORD dwProcessId, + _In_ PSTARTUP_CALLBACK pfnCallback, + _In_ PVOID parameter, + _Out_ PVOID *ppUnregisterToken) { return RegisterForRuntimeStartupEx(dwProcessId, NULL, pfnCallback, parameter, ppUnregisterToken); } @@ -738,11 +738,11 @@ RegisterForRuntimeStartup( DLLEXPORT HRESULT RegisterForRuntimeStartupEx( - __in DWORD dwProcessId, - __in LPCWSTR lpApplicationGroupId, - __in PSTARTUP_CALLBACK pfnCallback, - __in PVOID parameter, - __out PVOID *ppUnregisterToken) + _In_ DWORD dwProcessId, + _In_ LPCWSTR lpApplicationGroupId, + _In_ PSTARTUP_CALLBACK pfnCallback, + _In_ PVOID parameter, + _Out_ PVOID *ppUnregisterToken) { PUBLIC_CONTRACT; @@ -787,7 +787,7 @@ RegisterForRuntimeStartupEx( DLLEXPORT HRESULT UnregisterForRuntimeStartup( - __in PVOID pUnregisterToken) + _In_ PVOID pUnregisterToken) { PUBLIC_CONTRACT; @@ -824,8 +824,8 @@ const int cchEventNameBufferSize = (sizeof(StartupNotifyEventNamePrefix) + sizeo DLLEXPORT HRESULT GetStartupNotificationEvent( - __in DWORD debuggeePID, - __out HANDLE* phStartupEvent) + _In_ DWORD debuggeePID, + _Out_ HANDLE* phStartupEvent) { PUBLIC_CONTRACT; @@ -1220,9 +1220,9 @@ DLLEXPORT HRESULT EnumerateCLRs( DWORD debuggeePID, - __out HANDLE** ppHandleArrayOut, - __out LPWSTR** ppStringArrayOut, - __out DWORD* pdwArrayLengthOut) + _Out_ HANDLE** ppHandleArrayOut, + _Out_ LPWSTR** ppStringArrayOut, + _Out_ DWORD* pdwArrayLengthOut) { PUBLIC_CONTRACT; @@ -1357,9 +1357,9 @@ EnumerateCLRs( DLLEXPORT HRESULT CloseCLREnumeration( - __in HANDLE* pHandleArray, - __in LPWSTR* pStringArray, - __in DWORD dwArrayLength) + _In_ HANDLE* pHandleArray, + _In_ LPWSTR* pStringArray, + _In_ DWORD dwArrayLength) { PUBLIC_CONTRACT; @@ -1484,11 +1484,11 @@ const WCHAR *c_versionStrFormat = W("%08x;%08x;%p"); DLLEXPORT HRESULT CreateVersionStringFromModule( - __in DWORD pidDebuggee, - __in LPCWSTR szModuleName, + _In_ DWORD pidDebuggee, + _In_ LPCWSTR szModuleName, __out_ecount_part(cchBuffer, *pdwLength) LPWSTR pBuffer, - __in DWORD cchBuffer, - __out DWORD* pdwLength) + _In_ DWORD cchBuffer, + _Out_ DWORD* pdwLength) { PUBLIC_CONTRACT; @@ -1719,9 +1719,9 @@ CheckDbiAndRuntimeVersion( DLLEXPORT HRESULT CreateDebuggingInterfaceFromVersionEx( - __in int iDebuggerVersion, - __in LPCWSTR szDebuggeeVersion, - __out IUnknown ** ppCordb) + _In_ int iDebuggerVersion, + _In_ LPCWSTR szDebuggeeVersion, + _Out_ IUnknown ** ppCordb) { return CreateDebuggingInterfaceFromVersion2(iDebuggerVersion, szDebuggeeVersion, NULL, ppCordb); } @@ -1748,10 +1748,10 @@ CreateDebuggingInterfaceFromVersionEx( DLLEXPORT HRESULT CreateDebuggingInterfaceFromVersion2( - __in int iDebuggerVersion, - __in LPCWSTR szDebuggeeVersion, - __in LPCWSTR szApplicationGroupId, - __out IUnknown ** ppCordb) + _In_ int iDebuggerVersion, + _In_ LPCWSTR szDebuggeeVersion, + _In_ LPCWSTR szApplicationGroupId, + _Out_ IUnknown ** ppCordb) { PUBLIC_CONTRACT; @@ -1880,8 +1880,8 @@ CreateDebuggingInterfaceFromVersion2( DLLEXPORT HRESULT CreateDebuggingInterfaceFromVersion( - __in LPCWSTR szDebuggeeVersion, - __out IUnknown ** ppCordb + _In_ LPCWSTR szDebuggeeVersion, + _Out_ IUnknown ** ppCordb ) { PUBLIC_CONTRACT; @@ -1907,7 +1907,7 @@ HRESULT GetContinueStartupEvent( DWORD debuggeePID, LPCWSTR szTelestoFullPath, - __out HANDLE* phContinueStartupEvent) + _Out_ HANDLE* phContinueStartupEvent) { if ((phContinueStartupEvent == NULL) || (szTelestoFullPath == NULL)) return E_INVALIDARG; diff --git a/src/coreclr/dlls/dbgshim/dbgshim.h b/src/coreclr/dlls/dbgshim/dbgshim.h index 392cd7b9286a85..56841663d7d462 100644 --- a/src/coreclr/dlls/dbgshim/dbgshim.h +++ b/src/coreclr/dlls/dbgshim/dbgshim.h @@ -11,81 +11,81 @@ typedef VOID (*PSTARTUP_CALLBACK)(IUnknown *pCordb, PVOID parameter, HRESULT hr) EXTERN_C HRESULT CreateProcessForLaunch( - __in LPWSTR lpCommandLine, - __in BOOL bSuspendProcess, - __in LPVOID lpEnvironment, - __in LPCWSTR lpCurrentDirectory, - __out PDWORD pProcessId, - __out HANDLE *pResumeHandle); + _In_ LPWSTR lpCommandLine, + _In_ BOOL bSuspendProcess, + _In_ LPVOID lpEnvironment, + _In_ LPCWSTR lpCurrentDirectory, + _Out_ PDWORD pProcessId, + _Out_ HANDLE *pResumeHandle); EXTERN_C HRESULT ResumeProcess( - __in HANDLE hResumeHandle); + _In_ HANDLE hResumeHandle); EXTERN_C HRESULT CloseResumeHandle( - __in HANDLE hResumeHandle); + _In_ HANDLE hResumeHandle); EXTERN_C HRESULT RegisterForRuntimeStartup( - __in DWORD dwProcessId, - __in PSTARTUP_CALLBACK pfnCallback, - __in PVOID parameter, - __out PVOID *ppUnregisterToken); + _In_ DWORD dwProcessId, + _In_ PSTARTUP_CALLBACK pfnCallback, + _In_ PVOID parameter, + _Out_ PVOID *ppUnregisterToken); EXTERN_C HRESULT RegisterForRuntimeStartupEx( - __in DWORD dwProcessId, - __in LPCWSTR szApplicationGroupId, - __in PSTARTUP_CALLBACK pfnCallback, - __in PVOID parameter, - __out PVOID *ppUnregisterToken); + _In_ DWORD dwProcessId, + _In_ LPCWSTR szApplicationGroupId, + _In_ PSTARTUP_CALLBACK pfnCallback, + _In_ PVOID parameter, + _Out_ PVOID *ppUnregisterToken); EXTERN_C HRESULT UnregisterForRuntimeStartup( - __in PVOID pUnregisterToken); + _In_ PVOID pUnregisterToken); EXTERN_C HRESULT GetStartupNotificationEvent( - __in DWORD debuggeePID, - __out HANDLE* phStartupEvent); + _In_ DWORD debuggeePID, + _Out_ HANDLE* phStartupEvent); EXTERN_C HRESULT EnumerateCLRs(DWORD debuggeePID, - __out HANDLE** ppHandleArrayOut, - __out LPWSTR** ppStringArrayOut, - __out DWORD* pdwArrayLengthOut); + _Out_ HANDLE** ppHandleArrayOut, + _Out_ LPWSTR** ppStringArrayOut, + _Out_ DWORD* pdwArrayLengthOut); EXTERN_C HRESULT CloseCLREnumeration( - __in HANDLE* pHandleArray, - __in LPWSTR* pStringArray, - __in DWORD dwArrayLength); + _In_ HANDLE* pHandleArray, + _In_ LPWSTR* pStringArray, + _In_ DWORD dwArrayLength); EXTERN_C HRESULT CreateVersionStringFromModule( - __in DWORD pidDebuggee, - __in LPCWSTR szModuleName, + _In_ DWORD pidDebuggee, + _In_ LPCWSTR szModuleName, __out_ecount_part(cchBuffer, *pdwLength) LPWSTR pBuffer, - __in DWORD cchBuffer, - __out DWORD* pdwLength); + _In_ DWORD cchBuffer, + _Out_ DWORD* pdwLength); EXTERN_C HRESULT CreateDebuggingInterfaceFromVersionEx( - __in int iDebuggerVersion, - __in LPCWSTR szDebuggeeVersion, - __out IUnknown ** ppCordb); + _In_ int iDebuggerVersion, + _In_ LPCWSTR szDebuggeeVersion, + _Out_ IUnknown ** ppCordb); EXTERN_C DLLEXPORT HRESULT CreateDebuggingInterfaceFromVersion2( - __in int iDebuggerVersion, - __in LPCWSTR szDebuggeeVersion, - __in LPCWSTR szApplicationGroupId, - __out IUnknown ** ppCordb); + _In_ int iDebuggerVersion, + _In_ LPCWSTR szDebuggeeVersion, + _In_ LPCWSTR szApplicationGroupId, + _Out_ IUnknown ** ppCordb); EXTERN_C HRESULT CreateDebuggingInterfaceFromVersion( - __in LPCWSTR szDebuggeeVersion, - __out IUnknown ** ppCordb); + _In_ LPCWSTR szDebuggeeVersion, + _Out_ IUnknown ** ppCordb); diff --git a/src/coreclr/dlls/mscoree/mscoree.cpp b/src/coreclr/dlls/mscoree/mscoree.cpp index 4e2d87906ad309..54b2b665dd80ef 100644 --- a/src/coreclr/dlls/mscoree/mscoree.cpp +++ b/src/coreclr/dlls/mscoree/mscoree.cpp @@ -252,7 +252,7 @@ HRESULT GetInternalSystemDirectory(__out_ecount_part_opt(*pdwLength,*pdwLength) } -LPCWSTR GetInternalSystemDirectory(__out DWORD* pdwLength) +LPCWSTR GetInternalSystemDirectory(_Out_ DWORD* pdwLength) { LIMITED_METHOD_CONTRACT; diff --git a/src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp b/src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp index 6a0ba5a2499475..623f0087d400c0 100644 --- a/src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp +++ b/src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp @@ -487,7 +487,7 @@ HRESULT CeeFileGenWriter::generateImage(void **ppImage) return hr; } // HRESULT CeeFileGenWriter::generateImage() -HRESULT CeeFileGenWriter::setOutputFileName(__in LPWSTR fileName) +HRESULT CeeFileGenWriter::setOutputFileName(_In_ LPWSTR fileName) { if (m_outputFileName) delete[] m_outputFileName; @@ -498,7 +498,7 @@ HRESULT CeeFileGenWriter::setOutputFileName(__in LPWSTR fileName) return S_OK; } // HRESULT CeeFileGenWriter::setOutputFileName() -HRESULT CeeFileGenWriter::setResourceFileName(__in LPWSTR fileName) +HRESULT CeeFileGenWriter::setResourceFileName(_In_ LPWSTR fileName) { if (m_resourceFileName) delete[] m_resourceFileName; @@ -1294,7 +1294,7 @@ HRESULT CeeFileGenWriter::setVTableEntry(ULONG size, ULONG offset) return setVTableEntry64(size,(void*)(ULONG_PTR)offset); } // HRESULT CeeFileGenWriter::setVTableEntry() -HRESULT CeeFileGenWriter::computeSectionOffset(CeeSection §ion, __in char *ptr, +HRESULT CeeFileGenWriter::computeSectionOffset(CeeSection §ion, _In_ char *ptr, unsigned *offset) { *offset = section.computeOffset(ptr); @@ -1302,7 +1302,7 @@ HRESULT CeeFileGenWriter::computeSectionOffset(CeeSection §ion, __in char *p return S_OK; } // HRESULT CeeFileGenWriter::computeSectionOffset() -HRESULT CeeFileGenWriter::computeOffset(__in char *ptr, +HRESULT CeeFileGenWriter::computeOffset(_In_ char *ptr, CeeSection **pSection, unsigned *offset) { TESTANDRETURNPOINTER(pSection); diff --git a/src/coreclr/dlls/mscorpe/iceefilegen.cpp b/src/coreclr/dlls/mscorpe/iceefilegen.cpp index 6714d355d0bfc3..6c40d9699fce91 100644 --- a/src/coreclr/dlls/mscorpe/iceefilegen.cpp +++ b/src/coreclr/dlls/mscorpe/iceefilegen.cpp @@ -183,7 +183,7 @@ HRESULT ICeeFileGen::AddSectionReloc (HCEESECTION section, ULONG offset, HCEESEC } } -HRESULT ICeeFileGen::SetOutputFileName (HCEEFILE ceeFile, __in LPWSTR outputFileName) +HRESULT ICeeFileGen::SetOutputFileName (HCEEFILE ceeFile, _In_ LPWSTR outputFileName) { TESTANDRETURNPOINTER(ceeFile); TESTANDRETURNPOINTER(outputFileName); @@ -192,7 +192,7 @@ HRESULT ICeeFileGen::SetOutputFileName (HCEEFILE ceeFile, __in LPWSTR outputFile return(gen->setOutputFileName(outputFileName)); } -__success(return == S_OK) HRESULT ICeeFileGen::GetOutputFileName (HCEEFILE ceeFile, __out LPWSTR *outputFileName) +__success(return == S_OK) HRESULT ICeeFileGen::GetOutputFileName (HCEEFILE ceeFile, _Out_ LPWSTR *outputFileName) { TESTANDRETURNPOINTER(ceeFile); TESTANDRETURNPOINTER(outputFileName); @@ -204,7 +204,7 @@ __success(return == S_OK) HRESULT ICeeFileGen::GetOutputFileName (HCEEFILE ceeFi } -HRESULT ICeeFileGen::SetResourceFileName (HCEEFILE ceeFile, __in LPWSTR resourceFileName) +HRESULT ICeeFileGen::SetResourceFileName (HCEEFILE ceeFile, _In_ LPWSTR resourceFileName) { TESTANDRETURNPOINTER(ceeFile); TESTANDRETURNPOINTER(resourceFileName); @@ -214,7 +214,7 @@ HRESULT ICeeFileGen::SetResourceFileName (HCEEFILE ceeFile, __in LPWSTR resource } __success(return == S_OK) -HRESULT ICeeFileGen::GetResourceFileName (HCEEFILE ceeFile, __out LPWSTR *resourceFileName) +HRESULT ICeeFileGen::GetResourceFileName (HCEEFILE ceeFile, _Out_ LPWSTR *resourceFileName) { TESTANDRETURNPOINTER(ceeFile); TESTANDRETURNPOINTER(resourceFileName); @@ -277,7 +277,7 @@ HRESULT ICeeFileGen::GetMethodRVA(HCEEFILE ceeFile, ULONG codeOffset, ULONG *cod return S_OK; } -HRESULT ICeeFileGen::EmitString(HCEEFILE ceeFile, __in LPWSTR strValue, ULONG *strRef) +HRESULT ICeeFileGen::EmitString(HCEEFILE ceeFile, _In_ LPWSTR strValue, ULONG *strRef) { TESTANDRETURNPOINTER(ceeFile); @@ -429,7 +429,7 @@ HRESULT ICeeFileGen::SetStrongNameEntry(HCEEFILE ceeFile, ULONG size, ULONG offs return gen->setStrongNameEntry(size, offset); } -HRESULT ICeeFileGen::ComputeSectionOffset(HCEESECTION section, __in char *ptr, +HRESULT ICeeFileGen::ComputeSectionOffset(HCEESECTION section, _In_ char *ptr, unsigned *offset) { TESTANDRETURNPOINTER(section); @@ -443,7 +443,7 @@ HRESULT ICeeFileGen::ComputeSectionOffset(HCEESECTION section, __in char *ptr, __success(return == S_OK) HRESULT ICeeFileGen::ComputeSectionPointer(HCEESECTION section, ULONG offset, - __out char **ptr) + _Out_ char **ptr) { TESTANDRETURNPOINTER(section); @@ -454,7 +454,7 @@ HRESULT ICeeFileGen::ComputeSectionPointer(HCEESECTION section, ULONG offset, return S_OK; } -HRESULT ICeeFileGen::ComputeOffset(HCEEFILE ceeFile, __in char *ptr, +HRESULT ICeeFileGen::ComputeOffset(HCEEFILE ceeFile, _In_ char *ptr, HCEESECTION *pSection, unsigned *offset) { TESTANDRETURNPOINTER(pSection); diff --git a/src/coreclr/dlls/mscorpe/pewriter.cpp b/src/coreclr/dlls/mscorpe/pewriter.cpp index 9add4b56d13b80..b78b00c2853ffb 100644 --- a/src/coreclr/dlls/mscorpe/pewriter.cpp +++ b/src/coreclr/dlls/mscorpe/pewriter.cpp @@ -1829,7 +1829,7 @@ HRESULT PEWriter::fixup(CeeGenTokenMapper *pMapper) return(S_OK); // SUCCESS } -HRESULT PEWriter::Open(__in LPCWSTR fileName) +HRESULT PEWriter::Open(_In_ LPCWSTR fileName) { _ASSERTE(m_file == INVALID_HANDLE_VALUE); HRESULT hr = NOERROR; @@ -1913,7 +1913,7 @@ HRESULT PEWriter::Close() } /******************************************************************/ -HRESULT PEWriter::write(__in LPCWSTR fileName) { +HRESULT PEWriter::write(_In_ LPCWSTR fileName) { HRESULT hr; diff --git a/src/coreclr/dlls/mscorpe/pewriter.h b/src/coreclr/dlls/mscorpe/pewriter.h index 21817b1d5efc45..84ec61f9275eca 100644 --- a/src/coreclr/dlls/mscorpe/pewriter.h +++ b/src/coreclr/dlls/mscorpe/pewriter.h @@ -41,7 +41,7 @@ class PEWriter : public PESectionMan HRESULT link(); HRESULT fixup(CeeGenTokenMapper *pMapper); - HRESULT write(__in LPCWSTR fileName); + HRESULT write(_In_ LPCWSTR fileName); HRESULT write(void **ppImage); // calling these functions is optional @@ -174,7 +174,7 @@ class PEWriter : public PESectionMan HRESULT linkPlaceSections(entry * entries, unsigned iEntries); void setSectionIndex(IMAGE_SECTION_HEADER * h, unsigned sectionIndex); - HRESULT Open(__in LPCWSTR fileName); + HRESULT Open(_In_ LPCWSTR fileName); HRESULT Write(const void *data, int size); HRESULT Seek(int offset); HRESULT Pad(int align); @@ -257,8 +257,8 @@ class PESeedSection : public PEWriterSection { int getDirEntry() { _ASSERTE(!"PESeedSection"); return 0; } HRESULT directoryEntry(unsigned num) { _ASSERTE(!"PESeedSection"); return E_FAIL; } char * computePointer(unsigned offset) const { _ASSERTE(!"PESeedSection"); return NULL; } - BOOL containsPointer(__in char *ptr) const { _ASSERTE(!"PESeedSection"); return FALSE; } - unsigned computeOffset(__in char *ptr) const { _ASSERTE(!"PESeedSection"); return 0; } + BOOL containsPointer(_In_ char *ptr) const { _ASSERTE(!"PESeedSection"); return FALSE; } + unsigned computeOffset(_In_ char *ptr) const { _ASSERTE(!"PESeedSection"); return 0; } HRESULT cloneInstance(PESection *destination) { _ASSERTE(!"PESeedSection"); return E_FAIL; } // PEWriterSection diff --git a/src/coreclr/ilasm/asmman.cpp b/src/coreclr/ilasm/asmman.cpp index 7b5fd474b65157..2d76b20a371c63 100644 --- a/src/coreclr/ilasm/asmman.cpp +++ b/src/coreclr/ilasm/asmman.cpp @@ -49,7 +49,7 @@ BinStr* BinStrToUnicode(BinStr* pSource, bool Swap) return NULL; } -AsmManFile* AsmMan::GetFileByName(__in __nullterminated char* szFileName) +AsmManFile* AsmMan::GetFileByName(_In_ __nullterminated char* szFileName) { AsmManFile* ret = NULL; if(szFileName) @@ -63,7 +63,7 @@ AsmManFile* AsmMan::GetFileByName(__in __nullterminated char* szFileName return ret; } -mdToken AsmMan::GetFileTokByName(__in __nullterminated char* szFileName) +mdToken AsmMan::GetFileTokByName(_In_ __nullterminated char* szFileName) { AsmManFile* tmp = GetFileByName(szFileName); return(tmp ? tmp->tkTok : mdFileNil); @@ -109,7 +109,7 @@ mdToken AsmMan::GetComTypeTokByName( return(tmp ? tmp->tkTok : mdExportedTypeNil); } -AsmManAssembly* AsmMan::GetAsmRefByName(__in __nullterminated const char* szAsmRefName) +AsmManAssembly* AsmMan::GetAsmRefByName(_In_ __nullterminated const char* szAsmRefName) { AsmManAssembly* ret = NULL; if(szAsmRefName) @@ -124,12 +124,12 @@ AsmManAssembly* AsmMan::GetAsmRefByName(__in __nullterminated const char* sz } return ret; } -mdToken AsmMan::GetAsmRefTokByName(__in __nullterminated const char* szAsmRefName) +mdToken AsmMan::GetAsmRefTokByName(_In_ __nullterminated const char* szAsmRefName) { AsmManAssembly* tmp = GetAsmRefByName(szAsmRefName); return(tmp ? tmp->tkTok : mdAssemblyRefNil); } -AsmManAssembly* AsmMan::GetAsmRefByAsmName(__in __nullterminated const char* szAsmName) +AsmManAssembly* AsmMan::GetAsmRefByAsmName(_In_ __nullterminated const char* szAsmName) { AsmManAssembly* ret = NULL; if(szAsmName) @@ -160,7 +160,7 @@ void AsmMan::SetModuleName(__inout_opt __nullterminated char* szName) } //============================================================================================================== -void AsmMan::AddFile(__in __nullterminated char* szName, DWORD dwAttr, BinStr* pHashBlob) +void AsmMan::AddFile(_In_ __nullterminated char* szName, DWORD dwAttr, BinStr* pHashBlob) { AsmManFile* tmp = GetFileByName(szName); Assembler* pAsm = (Assembler*)m_pAssembler; @@ -244,7 +244,7 @@ void AsmMan::EmitFiles() } //end for(i = 0; tmp=m_FileLst.PEEK(i); i++) } -void AsmMan::StartAssembly(__in __nullterminated char* szName, __in_opt __nullterminated char* szAlias, DWORD dwAttr, BOOL isRef) +void AsmMan::StartAssembly(_In_ __nullterminated char* szName, __in_opt __nullterminated char* szAlias, DWORD dwAttr, BOOL isRef) { if(!isRef && (0==strcmp(szName, "mscorlib"))) ((Assembler*)m_pAssembler)->m_fIsMscorlib = TRUE; if(!isRef && (m_pAssembly != NULL)) @@ -674,7 +674,7 @@ void AsmMan::SetAssemblyAutodetect() } } -void AsmMan::StartComType(__in __nullterminated char* szName, DWORD dwAttr) +void AsmMan::StartComType(_In_ __nullterminated char* szName, DWORD dwAttr) { if((m_pCurComType = new AsmManComType)) { @@ -732,7 +732,7 @@ void AsmMan::EndComType() } } -void AsmMan::SetComTypeFile(__in __nullterminated char* szFileName) +void AsmMan::SetComTypeFile(_In_ __nullterminated char* szFileName) { if(m_pCurComType) { @@ -740,7 +740,7 @@ void AsmMan::SetComTypeFile(__in __nullterminated char* szFileName) } } -void AsmMan::SetComTypeAsmRef(__in __nullterminated char* szAsmRefName) +void AsmMan::SetComTypeAsmRef(_In_ __nullterminated char* szAsmRefName) { if(m_pCurComType) { @@ -748,7 +748,7 @@ void AsmMan::SetComTypeAsmRef(__in __nullterminated char* szAsmRefName) } } -void AsmMan::SetComTypeComType(__in __nullterminated char* szComTypeName) +void AsmMan::SetComTypeComType(_In_ __nullterminated char* szComTypeName) { if(m_pCurComType) { @@ -780,7 +780,7 @@ BOOL AsmMan::SetComTypeClassTok(mdToken tkClass) return FALSE; } -void AsmMan::StartManifestRes(__in __nullterminated char* szName, __in __nullterminated char* szAlias, DWORD dwAttr) +void AsmMan::StartManifestRes(_In_ __nullterminated char* szName, _In_ __nullterminated char* szAlias, DWORD dwAttr) { if((m_pCurManRes = new AsmManRes)) { @@ -808,7 +808,7 @@ void AsmMan::EndManifestRes() } -void AsmMan::SetManifestResFile(__in __nullterminated char* szFileName, ULONG ulOffset) +void AsmMan::SetManifestResFile(_In_ __nullterminated char* szFileName, ULONG ulOffset) { if(m_pCurManRes) { @@ -817,7 +817,7 @@ void AsmMan::SetManifestResFile(__in __nullterminated char* szFileName, ULONG } } -void AsmMan::SetManifestResAsmRef(__in __nullterminated char* szAsmRefName) +void AsmMan::SetManifestResAsmRef(_In_ __nullterminated char* szAsmRefName) { if(m_pCurManRes) { diff --git a/src/coreclr/ilasm/asmman.hpp b/src/coreclr/ilasm/asmman.hpp index 1290c9b2707c8a..4663a88e4e5f52 100644 --- a/src/coreclr/ilasm/asmman.hpp +++ b/src/coreclr/ilasm/asmman.hpp @@ -193,8 +193,8 @@ class AsmMan ErrorReporter* report; void* m_pAssembler; - AsmManFile* GetFileByName(__in __nullterminated char* szFileName); - AsmManAssembly* GetAsmRefByName(__in __nullterminated const char* szAsmRefName); + AsmManFile* GetFileByName(_In_ __nullterminated char* szFileName); + AsmManAssembly* GetAsmRefByName(_In_ __nullterminated const char* szAsmRefName); AsmManComType* GetComTypeByName(__in_opt __nullterminated char* szComTypeName, __in_opt __nullterminated char* szComEnclosingTypeName = NULL); mdToken GetComTypeTokByName(__in_opt __nullterminated char* szComTypeName, @@ -241,11 +241,11 @@ class AsmMan void SetModuleName(__inout_opt __nullterminated char* szName); - void AddFile(__in __nullterminated char* szName, DWORD dwAttr, BinStr* pHashBlob); + void AddFile(_In_ __nullterminated char* szName, DWORD dwAttr, BinStr* pHashBlob); void EmitFiles(); void EmitDebuggableAttribute(mdToken tkOwner); - void StartAssembly(__in __nullterminated char* szName, __in_opt __nullterminated char* szAlias, DWORD dwAttr, BOOL isRef); + void StartAssembly(_In_ __nullterminated char* szName, __in_opt __nullterminated char* szAlias, DWORD dwAttr, BOOL isRef); void EndAssembly(); void EmitAssemblyRefs(); void EmitAssembly(); @@ -257,27 +257,27 @@ class AsmMan void SetAssemblyHashBlob(BinStr* pHashBlob); void SetAssemblyAutodetect(); - void StartComType(__in __nullterminated char* szName, DWORD dwAttr); + void StartComType(_In_ __nullterminated char* szName, DWORD dwAttr); void EndComType(); - void SetComTypeFile(__in __nullterminated char* szFileName); - void SetComTypeAsmRef(__in __nullterminated char* szAsmRefName); - void SetComTypeComType(__in __nullterminated char* szComTypeName); + void SetComTypeFile(_In_ __nullterminated char* szFileName); + void SetComTypeAsmRef(_In_ __nullterminated char* szAsmRefName); + void SetComTypeComType(_In_ __nullterminated char* szComTypeName); BOOL SetComTypeImplementationTok(mdToken tk); BOOL SetComTypeClassTok(mdToken tkClass); - void StartManifestRes(__in __nullterminated char* szName, __in __nullterminated char* szAlias, DWORD dwAttr); + void StartManifestRes(_In_ __nullterminated char* szName, _In_ __nullterminated char* szAlias, DWORD dwAttr); void EndManifestRes(); - void SetManifestResFile(__in __nullterminated char* szFileName, ULONG ulOffset); - void SetManifestResAsmRef(__in __nullterminated char* szAsmRefName); + void SetManifestResFile(_In_ __nullterminated char* szFileName, ULONG ulOffset); + void SetManifestResAsmRef(_In_ __nullterminated char* szAsmRefName); - AsmManAssembly* GetAsmRefByAsmName(__in __nullterminated const char* szAsmName); + AsmManAssembly* GetAsmRefByAsmName(_In_ __nullterminated const char* szAsmName); - mdToken GetFileTokByName(__in __nullterminated char* szFileName); - mdToken GetAsmRefTokByName(__in __nullterminated const char* szAsmRefName); - mdToken GetAsmTokByName(__in __nullterminated const char* szAsmName) + mdToken GetFileTokByName(_In_ __nullterminated char* szFileName); + mdToken GetAsmRefTokByName(_In_ __nullterminated const char* szAsmRefName); + mdToken GetAsmTokByName(_In_ __nullterminated const char* szAsmName) { return (m_pAssembly && (strcmp(m_pAssembly->szName,szAsmName)==0)) ? m_pAssembly->tkTok : 0; }; - mdToken GetModuleRefTokByName(__in __nullterminated char* szName) + mdToken GetModuleRefTokByName(_In_ __nullterminated char* szName) { if(szName && *szName) { diff --git a/src/coreclr/ilasm/asmparse.h b/src/coreclr/ilasm/asmparse.h index ef377b5e430d7c..6299719edd3b3a 100644 --- a/src/coreclr/ilasm/asmparse.h +++ b/src/coreclr/ilasm/asmparse.h @@ -20,7 +20,7 @@ class ReadStream { virtual ~ReadStream() = default; - virtual unsigned getAll(__out char** ppch) = 0; + virtual unsigned getAll(_Out_ char** ppch) = 0; // read at most 'buffLen' bytes into 'buff', Return the // number of characters read. On EOF return 0 @@ -49,7 +49,7 @@ class BinStrStream : public ReadStream { //if(m_pBS) // delete m_pBS; }; - unsigned getAll(__out char **ppbuff) + unsigned getAll(_Out_ char **ppbuff) { *ppbuff = m_pStart; return m_pBS->length(); @@ -95,7 +95,7 @@ class BinStrStream : public ReadStream { /**************************************************************************/ class MappedFileStream : public ReadStream { public: - MappedFileStream(__in __nullterminated WCHAR* wFileName) + MappedFileStream(_In_ __nullterminated WCHAR* wFileName) { fileNameW = wFileName; m_hFile = INVALID_HANDLE_VALUE; @@ -124,7 +124,7 @@ class MappedFileStream : public ReadStream { fileNameW = NULL; } } - unsigned getAll(__out char** pbuff) + unsigned getAll(_Out_ char** pbuff) { *pbuff = m_pStart; return m_FileSize; @@ -214,14 +214,14 @@ typedef LIFO ARG_NAME_LIST_STACK; /*--------------------------------------------------------------------------*/ typedef char*(*PFN_NEXTCHAR)(char*); -char* nextcharU(__in __nullterminated char* pos); -char* nextcharW(__in __nullterminated char* pos); +char* nextcharU(_In_ __nullterminated char* pos); +char* nextcharW(_In_ __nullterminated char* pos); /*--------------------------------------------------------------------------*/ typedef unsigned(*PFN_SYM)(char*); -unsigned SymAU(__in __nullterminated char* curPos); -unsigned SymW(__in __nullterminated char* curPos); +unsigned SymAU(_In_ __nullterminated char* curPos); +unsigned SymW(_In_ __nullterminated char* curPos); /*--------------------------------------------------------------------------*/ typedef char*(*PFN_NEWSTRFROMTOKEN)(char*,size_t); @@ -235,8 +235,8 @@ char* NewStaticStrFromTokenW(__in_ecount(tokLen) char* curTok, size_t tokLen, __ /*--------------------------------------------------------------------------*/ typedef unsigned(*PFN_GETDOUBLE)(char*,unsigned,double**); -unsigned GetDoubleAU(__in __nullterminated char* begNum, unsigned L, double** ppRes); -unsigned GetDoubleW(__in __nullterminated char* begNum, unsigned L, double** ppRes); +unsigned GetDoubleAU(_In_ __nullterminated char* begNum, unsigned L, double** ppRes); +unsigned GetDoubleW(_In_ __nullterminated char* begNum, unsigned L, double** ppRes); /*--------------------------------------------------------------------------*/ struct PARSING_ENVIRONMENT { @@ -284,9 +284,9 @@ class AsmParse : public ErrorReporter virtual void warn(const char* fmt, ...); virtual void msg(const char* fmt, ...); char *getLine(int lineNum) { return penv->in->getLine(lineNum); }; - unsigned getAll(__out char** pbuff) { return penv->in->getAll(pbuff); }; + unsigned getAll(_Out_ char** pbuff) { return penv->in->getAll(pbuff); }; bool Success() {return success; }; - void SetIncludePath(__in WCHAR* wz) { wzIncludePath = wz; }; + void SetIncludePath(_In_ WCHAR* wz) { wzIncludePath = wz; }; ARG_NAME_LIST_STACK m_ANSFirst; ARG_NAME_LIST_STACK m_ANSLast; @@ -303,15 +303,15 @@ class AsmParse : public ErrorReporter HANDLE hstderr; private: - friend void yyerror(__in __nullterminated const char* str); + friend void yyerror(_In_ __nullterminated const char* str); friend int parse_literal(unsigned curSym, __inout __nullterminated char* &curPos, BOOL translate_escapes); friend int yyparse(); friend int yylex(); friend Instr* SetupInstr(unsigned short opcode); friend int findKeyword(const char* name, size_t nameLen, unsigned short* opcode); friend TypeDefDescr* findTypedef(__in_ecount(nameLen) char* name, size_t nameLen); - friend char* skipBlanks(__in __nullterminated char*,unsigned*); - friend char* nextBlank(__in __nullterminated char*); + friend char* skipBlanks(_In_ __nullterminated char*,unsigned*); + friend char* nextBlank(_In_ __nullterminated char*); friend int ProcessEOF(); friend unsigned __int8* skipType(unsigned __int8* ptr, BOOL fFixupType); friend void FixupConstraints(); diff --git a/src/coreclr/ilasm/assem.cpp b/src/coreclr/ilasm/assem.cpp index e8044d16ab2b7f..6ab3fcb1099697 100644 --- a/src/coreclr/ilasm/assem.cpp +++ b/src/coreclr/ilasm/assem.cpp @@ -1039,7 +1039,7 @@ BOOL Assembler::EmitProp(PropDescriptor* pPD) return TRUE; } -Class *Assembler::FindCreateClass(__in __nullterminated const char *pszFQN) +Class *Assembler::FindCreateClass(_In_ __nullterminated const char *pszFQN) { Class *pSearch = NULL; @@ -1186,7 +1186,7 @@ BOOL Assembler::DoGlobalFixups() return TRUE; } -state_t Assembler::AddGlobalLabel(__in __nullterminated char *pszName, HCEESECTION section) +state_t Assembler::AddGlobalLabel(_In_ __nullterminated char *pszName, HCEESECTION section) { if (FindGlobalLabel(pszName) != NULL) { @@ -1213,7 +1213,7 @@ state_t Assembler::AddGlobalLabel(__in __nullterminated char *pszName, HCEESECTI return m_State; } -void Assembler::AddLabel(DWORD CurPC, __in __nullterminated char *pszName) +void Assembler::AddLabel(DWORD CurPC, _In_ __nullterminated char *pszName) { if (m_pCurMethod->FindLabel(pszName) != NULL) { diff --git a/src/coreclr/ilasm/assembler.cpp b/src/coreclr/ilasm/assembler.cpp index 48f9487656f7cf..3063a48c1d798c 100644 --- a/src/coreclr/ilasm/assembler.cpp +++ b/src/coreclr/ilasm/assembler.cpp @@ -15,7 +15,7 @@ #define FAIL_UNLESS(x, y) if (!(x)) { report->error y; return; } /**************************************************************************/ -void Assembler::StartNameSpace(__in __nullterminated char* name) +void Assembler::StartNameSpace(_In_ __nullterminated char* name) { m_NSstack.PUSH(m_szNamespace); m_szNamespace = name; @@ -91,7 +91,7 @@ void Assembler::ClearBoundList(void) m_TyParList = NULL; } /**************************************************************************/ -mdToken Assembler::ResolveClassRef(mdToken tkResScope, __in __nullterminated const char *pszFullClassName, Class** ppClass) +mdToken Assembler::ResolveClassRef(mdToken tkResScope, _In_ __nullterminated const char *pszFullClassName, Class** ppClass) { Class *pClass = NULL; mdToken tkRet = mdTokenNil; @@ -239,7 +239,7 @@ mdToken Assembler::ResolveTypeSpec(BinStr* typeSpec) } /**************************************************************************/ -mdToken Assembler::GetAsmRef(__in __nullterminated const char* szName) +mdToken Assembler::GetAsmRef(_In_ __nullterminated const char* szName) { mdToken tkResScope = 0; if(strcmp(szName,"*")==0) tkResScope = mdTokenNil; @@ -330,7 +330,7 @@ mdToken Assembler::GetInterfaceImpl(mdToken tsClass, mdToken tsInterface) } /**************************************************************************/ -mdToken Assembler::GetModRef(__in __nullterminated char* szName) +mdToken Assembler::GetModRef(_In_ __nullterminated char* szName) { mdToken tkResScope = 0; if(!strcmp(szName,m_szScopeName)) @@ -417,7 +417,7 @@ DWORD Assembler::CheckClassFlagsIfNested(Class* pEncloser, DWORD attr) /**************************************************************************/ -void Assembler::StartClass(__in __nullterminated char* name, DWORD attr, TyParList *typars) +void Assembler::StartClass(_In_ __nullterminated char* name, DWORD attr, TyParList *typars) { Class *pEnclosingClass = m_pCurClass; char *szFQN; @@ -607,7 +607,7 @@ void Assembler::SetPinvoke(BinStr* DllName, int Ordinal, BinStr* Alias, int Attr } /**************************************************************************/ -void Assembler::StartMethod(__in __nullterminated char* name, BinStr* sig, CorMethodAttr flags, BinStr* retMarshal, DWORD retAttr, TyParList *typars) +void Assembler::StartMethod(_In_ __nullterminated char* name, BinStr* sig, CorMethodAttr flags, BinStr* retMarshal, DWORD retAttr, TyParList *typars) { if (m_pCurMethod != NULL) { @@ -801,7 +801,7 @@ void Assembler::EndMethod() } /**************************************************************************/ /* rvaLabel is the optional label that indicates this field points at a particular RVA */ -void Assembler::AddField(__inout_z __inout char* name, BinStr* sig, CorFieldAttr flags, __in __nullterminated char* rvaLabel, BinStr* pVal, ULONG ulOffset) +void Assembler::AddField(__inout_z __inout char* name, BinStr* sig, CorFieldAttr flags, _In_ __nullterminated char* rvaLabel, BinStr* pVal, ULONG ulOffset) { FieldDescriptor* pFD; ULONG i,n; @@ -1030,7 +1030,7 @@ void Assembler::NewSEHDescriptor(void) //sets m_SEHD if(m_SEHD == NULL) report->error("Failed to allocate SEH descriptor\n"); } /**************************************************************************/ -void Assembler::SetTryLabels(__in __nullterminated char * szFrom, __in __nullterminated char *szTo) +void Assembler::SetTryLabels(_In_ __nullterminated char * szFrom, _In_ __nullterminated char *szTo) { if(!m_SEHD) return; Label *pLbl = m_pCurMethod->FindLabel(szFrom); @@ -1043,7 +1043,7 @@ void Assembler::SetTryLabels(__in __nullterminated char * szFrom, __in __nullter else report->error("Undefined 1st label in 'try