diff --git a/Docs/03_Advanced/02_Kernels.md b/Docs/03_Advanced/02_Kernels.md index 7f03a5b741..8ae99f55bd 100644 --- a/Docs/03_Advanced/02_Kernels.md +++ b/Docs/03_Advanced/02_Kernels.md @@ -29,6 +29,17 @@ a `while (true)` loop without a `return` or `break`, is rejected with the error Such a kernel could only be stopped by resetting the device. Loops like `while (true)` that are left through a `return` or `break` are supported. +Arrays created in kernels, such as `new int[4]`, can be `null` (e.g. `c ? new int[4] : null` or `a ?? b`) and can be +tested for `null` like in .NET. +Arrays are compared by their buffers, and every allocation site has a single buffer per thread: two arrays allocated by +the same `new` expression, such as in a loop or in a helper method called twice, are equal. +`Array.Empty()` returns the same array for the same `T` and different arrays for different types, also for `int` and +`uint`, as in .NET. +Unlike in .NET, the `Length` of a `null` array is 0, and accessing an element of a `null` array is undefined behavior on +GPUs (the CPU accelerator throws a `NullReferenceException`). +Accesses to the elements of arrays created in kernels are not bounds-checked: accessing an element outside of an array +is undefined behavior on every accelerator. + The type of the first parameter must always be a supported index type in the case of implicitly grouped kernels (see below). In the case of explicitly grouped kernels, the first parameter is manually defined by the programmer (see below) @@ -48,6 +59,22 @@ Arrays created in kernels, such as `new int[4]`, can be pinned with `fixed` stat `fixed (int* p = array)`; the pointer of an empty array is `null`, as in .NET. Leaving such a `fixed` statement through `break`, `continue` or `goto` is not supported. +Some Metal devices, such as the Apple Paravirtual device of macOS virtual machines, place the first thread-private +object of a kernel at address 0, where an array created in the kernel or the address of a local would compare equal +to `null`. +Metal kernels therefore start such arrays and locals one element into a longer array by default. +To save this element, turn it off with `--metal-null-safe-locals false`, for instance in the project file: + +```xml + + --metal-null-safe-locals false + +``` + +or with `EnableMetalNullSafeLocals = false` in the `CompilationProperties` passed to the compiler. +The Metal runtime then writes a warning to `System.Diagnostics.Trace` when it loads such a kernel on the Apple +Paravirtual device. + ## Lambdas and Delegates Kernel code can use delegates (e.g. `Func`) whose target is known at compile time. diff --git a/Src/ILGPU/Runtime/Metal/MetalCompiledKernel.cs b/Src/ILGPU/Runtime/Metal/MetalCompiledKernel.cs index aa4d31400d..cc7ef65d74 100644 --- a/Src/ILGPU/Runtime/Metal/MetalCompiledKernel.cs +++ b/Src/ILGPU/Runtime/Metal/MetalCompiledKernel.cs @@ -51,7 +51,8 @@ public class MetalCompiledKernel( MetalTargetOS targetOS, MetalGPUFamily gpuFamily, string? source = null, - bool fastMath = false) : + bool fastMath = false, + bool nullSafeLocals = true) : CompiledKernel(guid, kernelName, kernelType, sharedMemoryMode), ICompiledKernelKind { @@ -81,6 +82,13 @@ public class MetalCompiledKernel( /// public bool FastMath { get; } = fastMath; + /// + /// Returns true if the kernel keeps local arrays and the locals it takes the + /// address of away from address 0, which some devices give to the first + /// thread-private object of a kernel and which compares equal to null. + /// + public bool NullSafeLocals { get; } = nullSafeLocals; + /// public override AcceleratorCapabilities RequiredCapabilities => MetalAcceleratorCapabilities.FromGPUFamily(GPUFamily); diff --git a/Src/ILGPU/Runtime/Metal/MetalKernel.cs b/Src/ILGPU/Runtime/Metal/MetalKernel.cs index 884d1fad8d..29cc7aaafe 100644 --- a/Src/ILGPU/Runtime/Metal/MetalKernel.cs +++ b/Src/ILGPU/Runtime/Metal/MetalKernel.cs @@ -34,6 +34,12 @@ internal MetalKernel( { var deviceHandle = accelerator.DeviceHandle; + if (GetNullSafeLocalsWarning(compiledKernel, accelerator.Name) is + string warning) + { + Trace.WriteLine(warning); + } + // Load the Metal library — prefer pre-compiled binary, fall back // to runtime source compilation. LibraryPtr = LoadLibrary(compiledKernel, deviceHandle); @@ -73,6 +79,29 @@ internal MetalKernel( PipelineState = pipelineState; } + /// + /// The name of the virtual Metal device of macOS virtual machines, which + /// places the first thread-private object of a kernel at address 0. + /// + private const string ParavirtualDeviceName = "Apple Paravirtual device"; + + /// + /// Returns a warning if the kernel may place a local at address 0 on the + /// given device, where it compares equal to null, or null otherwise. + /// + /// The compiled kernel to load. + /// The name of the Metal device. + private static string? GetNullSafeLocalsWarning( + MetalCompiledKernel compiledKernel, + string deviceName) => + !compiledKernel.NullSafeLocals && deviceName == ParavirtualDeviceName + ? $"Kernel '{compiledKernel.KernelName}' was compiled with " + + "--metal-null-safe-locals false, but the Metal device " + + $"'{deviceName}' places the first thread-private object of " + + "a kernel at address 0, so a local array or the address of a " + + "local may compare equal to null" + : null; + /// /// Loads a Metal library from binary data or source code. /// diff --git a/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs b/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs index 9fcd85a347..eb1a125c32 100644 --- a/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs +++ b/Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs @@ -11,10 +11,12 @@ using ILGPU; using ILGPU.Runtime; +using ILGPU.Runtime.Metal; using ILGPUC.Backends; using ILGPUC.Tests.Framework; using ILGPUC.Tests.Kernels; using System; +using System.CommandLine; using System.Reflection; using System.Threading.Tasks; using Xunit; @@ -23,8 +25,9 @@ namespace ILGPUC.Tests.BackendTests; /// /// Checks that the Metal backend rejects what Metal cannot express with a -/// clear compile-time error instead of emitting invalid source, and that it -/// selects precise or fast math and fusion as requested. +/// clear compile-time error instead of emitting invalid source, that it +/// selects precise or fast math and fusion as requested and that it keeps +/// thread storage away from address 0. /// public sealed class MetalSourceTests { @@ -166,6 +169,139 @@ public async Task MathMode_SelectsCompileOptions( Assert.Equal(fastMath, wrapper.Contains("fastMath: true")); } + /// + /// Holds four integers in thread memory. + /// + internal unsafe struct LocalBuffer + { + public fixed int Data[4]; + } + + /// + /// Stores into a local array and into a fixed buffer of a local. + /// + internal static unsafe void LocalStorageKernel( + Index1D index, + ArrayView1D data) + { + var values = new int[4]; + values[index & 3] = data[index]; + LocalBuffer buffer; + buffer.Data[index & 3] = values[(index + 1) & 3]; + data[index] = buffer.Data[(index + 2) & 3]; + } + + private static readonly MethodInfo LocalStorage = typeof(MetalSourceTests) + .GetMethod( + nameof(LocalStorageKernel), + BindingFlags.NonPublic | BindingFlags.Static)!; + + /// + /// Some Metal devices place the first thread-private object of a kernel at + /// address 0, where a local array or local compares equal to null. Local + /// arrays and allocations start one element into a longer array instead, + /// unless null-safe locals are turned off, which the compiled kernel then + /// tells the runtime. + /// + [Theory] + [InlineData(OptimizationLevel.O0, true)] + [InlineData(OptimizationLevel.O1, true)] + [InlineData(OptimizationLevel.O2, true)] + [InlineData(OptimizationLevel.O0, false)] + [InlineData(OptimizationLevel.O2, false)] + public void LocalStorage_StartsAfterAddressZero( + OptimizationLevel level, + bool nullSafeLocals) + { + var properties = new CompilationProperties( + OptimizationLevel: level, + EnableMetalNullSafeLocals: nullSafeLocals); + using var helper = new CompilationHelper(BackendType.Metal); + var source = helper.GenerateBackendCode( + LocalStorage, + BackendType.Metal, + properties).SourceCode; + + if (nullSafeLocals) + { + Assert.Matches(@"thread int (\w+)_storage\[5\] = \{0\};", source); + Assert.Matches(@"thread int\* (\w+) = \1_storage \+ 1;", source); + Assert.Matches(@"thread (\w+) (\w+)_storage_base\[2\] = \{\};", source); + Assert.Matches(@"thread \w+\* (\w+)_storage = \1_storage_base \+ 1;", source); + } + else + { + Assert.Matches(@"thread int \w+\[4\] = \{0\}\s*;", source); + Assert.Matches(@"thread \w+ \w+_storage\[1\];", source); + Assert.DoesNotContain("_storage_base", source); + Assert.DoesNotContain(" + 1;", source); + } + + var (_, wrapper) = helper.GenerateLauncher( + LocalStorage, + BackendType.Metal, + props: properties); + Assert.Equal(!nullSafeLocals, wrapper.Contains("nullSafeLocals: false")); + } + + /// + /// Null-safe locals are the default of the compilation properties and of the + /// command line, which turns them off with false. + /// + [Theory] + [InlineData(new string[0], true)] + [InlineData(new[] { "--metal-null-safe-locals" }, true)] + [InlineData(new[] { "--metal-null-safe-locals", "false" }, false)] + [InlineData(new[] { "--metal-null-safe-locals=false" }, false)] + public void CommandLine_SelectsNullSafeLocals(string[] args, bool expected) + { + Assert.True(new CompilationProperties().EnableMetalNullSafeLocals); + + var command = new Command("compile"); + var options = new Program.CompilationPropertiesOptions(command); + var result = command.Parse(args); + + Assert.Empty(result.Errors); + Assert.Equal( + expected, + options.GetProperties(result).EnableMetalNullSafeLocals); + } + + /// + /// The Metal runtime warns when it loads a kernel without null-safe locals + /// on the Apple Paravirtual device of macOS virtual machines, which places + /// the first thread-private object of a kernel at address 0. + /// + [Theory] + [InlineData(false, "Apple Paravirtual device", true)] + [InlineData(true, "Apple Paravirtual device", false)] + [InlineData(false, "Apple M4 Max", false)] + public void NullSafeLocals_WarnsOnParavirtualDevice( + bool nullSafeLocals, + string deviceName, + bool warns) + { + var kernel = new MetalCompiledKernel( + Guid.NewGuid(), + "LocalStorageKernel", + CompiledKernelType.Auto, + CompiledKernelSharedMemoryMode.Static, + MetalTargetOS.macOS, + MetalGPUFamily.Apple7, + nullSafeLocals: nullSafeLocals); + var getWarning = typeof(MetalKernel).GetMethod( + "GetNullSafeLocalsWarning", + BindingFlags.NonPublic | BindingFlags.Static)!; + + var warning = (string?)getWarning.Invoke(null, [kernel, deviceName]); + Assert.Equal(warns, warning is not null); + if (warning is not null) + { + Assert.Contains("'LocalStorageKernel'", warning); + Assert.Contains("--metal-null-safe-locals", warning); + } + } + private static string Flatten(Exception exception) { var message = string.Empty; diff --git a/Src/ILGPUC.Tests/BackendTests/StructuredControlFlowSourceTests.cs b/Src/ILGPUC.Tests/BackendTests/StructuredControlFlowSourceTests.cs index 61d9dc3b93..4ffd550060 100644 --- a/Src/ILGPUC.Tests/BackendTests/StructuredControlFlowSourceTests.cs +++ b/Src/ILGPUC.Tests/BackendTests/StructuredControlFlowSourceTests.cs @@ -199,7 +199,8 @@ private static int Count(string source, string pattern) => private const string EndlessLoop = @"while\s*\(\s*true\s*\)"; private const string JumpVariable = @"\b_jump\d+\b"; - private const string StorageDeclaration = @"\b\w+_storage\s*\[\s*\d+\s*\]\s*;"; + private const string StorageDeclaration = + @"\b\w+_storage(_base)?\s*\[\s*\d+\s*\]\s*(=\s*\{\s*\}\s*)?;"; [Theory] [InlineData(BackendType.Cuda)] diff --git a/Src/ILGPUC.Tests/ExecutionTests/ArrayExecutionTests.cs b/Src/ILGPUC.Tests/ExecutionTests/ArrayExecutionTests.cs index 4f5b3c313e..3c35a895ba 100644 --- a/Src/ILGPUC.Tests/ExecutionTests/ArrayExecutionTests.cs +++ b/Src/ILGPUC.Tests/ExecutionTests/ArrayExecutionTests.cs @@ -14,6 +14,7 @@ using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; +using RoslynOptimizationLevel = Microsoft.CodeAnalysis.OptimizationLevel; namespace ILGPUC.Tests.ExecutionTests; @@ -39,4 +40,74 @@ await VerifyProgramOutputAsync( ["Kernels.ArrayBoundsKernel"], ["0", "1", "-1", "-1"]); } + + /// + /// Null arrays and their null tests, compiled in Debug and in Release: null + /// arrays are distinct from empty arrays, also in helpers that are not + /// inlined, and Array.Empty returns the same array for the same element + /// type, which is not null, and different arrays for int, uint, an int enum + /// and a structure of one int, whose IR type is the same. + /// + [SkippableTheory] + [InlineData(RoslynOptimizationLevel.Release, OptimizationLevel.O0)] + [InlineData(RoslynOptimizationLevel.Release, OptimizationLevel.O1)] + [InlineData(RoslynOptimizationLevel.Release, OptimizationLevel.O2)] + [InlineData(RoslynOptimizationLevel.Debug, OptimizationLevel.O0)] + [InlineData(RoslynOptimizationLevel.Debug, OptimizationLevel.O1)] + [InlineData(RoslynOptimizationLevel.Debug, OptimizationLevel.O2)] + public async Task NullArrays_ProducesCorrectOutput( + RoslynOptimizationLevel programOptimization, + OptimizationLevel level) + { + await VerifyProgramOutputAsync( + "TestPrograms/Array/NullArrays.cs", + [ + "Kernels.NullArrayKernel", + "Kernels.NullReferenceKernel", + "Kernels.EmptyArrayKernel", + ], + [ + "1", "3", "3", "-1", "-1", "1", "0", "-2", + "-1", "5", "-2", "-1", "-1", "0", "0", "-2", + "3", "3", "3", "0", "-1", "11", "11", "-2", + "-1", "5", "-2", "0", "4", "10", "11", "3", + "1", "-1", "1", "3", "31", "0", + "1", "-1", "1", "3", "31", "0", + "0", "4", "0", "2", "41", "1", + "0", "4", "0", "2", "41", "1", + "1111", "1011", "1111", "1011", + ], + new CompilationProperties { OptimizationLevel = level }, + programOptimization); + } + + /// + /// Null arrays on the IL stack across branches, such as a ?? b of two + /// conditional null arrays in Release builds, null phis in loop bodies, the + /// length 0 of null arrays, also of ldnull; ldlen, and a null local that a + /// loop replaces with a new array. + /// + [SkippableTheory] + [InlineData(RoslynOptimizationLevel.Release, OptimizationLevel.O0)] + [InlineData(RoslynOptimizationLevel.Release, OptimizationLevel.O1)] + [InlineData(RoslynOptimizationLevel.Release, OptimizationLevel.O2)] + [InlineData(RoslynOptimizationLevel.Debug, OptimizationLevel.O0)] + [InlineData(RoslynOptimizationLevel.Debug, OptimizationLevel.O1)] + [InlineData(RoslynOptimizationLevel.Debug, OptimizationLevel.O2)] + public async Task NullArrayStackValues_ProducesCorrectOutput( + RoslynOptimizationLevel programOptimization, + OptimizationLevel level) + { + await VerifyProgramOutputAsync( + "TestPrograms/Array/NullArrayStackValues.cs", + ["Kernels.NullArrayStackKernel"], + [ + "1", "1", "1", "1", "575", "333", "0", "1", "0", "902", + "-1", "-1", "-1", "11", "757", "133", "0", "0", "0", "903", + "1", "2", "1", "11", "575", "113", "0", "2", "0", "904", + "1", "2", "1", "11", "757", "111", "0", "2", "0", "905", + ], + new CompilationProperties { OptimizationLevel = level }, + programOptimization); + } } diff --git a/Src/ILGPUC.Tests/ExecutionTests/LocalArrayExecutionTests.cs b/Src/ILGPUC.Tests/ExecutionTests/LocalArrayExecutionTests.cs index fb9f466dcd..7a09ffc1fd 100644 --- a/Src/ILGPUC.Tests/ExecutionTests/LocalArrayExecutionTests.cs +++ b/Src/ILGPUC.Tests/ExecutionTests/LocalArrayExecutionTests.cs @@ -32,6 +32,20 @@ await VerifyProgramOutputAsync( ["10", "20", "30", "40"]); } + /// + /// Kernels whose thread storage may start at address 0 still run, on Metal + /// through a compiled kernel that tells the runtime. + /// + [SkippableFact] + public async Task WriteReadWithoutNullSafeLocals_ProducesCorrectOutput() + { + await VerifyProgramOutputAsync( + "TestPrograms/LocalArray/WriteRead.cs", + ["Kernels.WriteReadKernel"], + ["10", "20", "30", "40"], + new CompilationProperties { EnableMetalNullSafeLocals = false }); + } + [SkippableFact] public async Task Length_ProducesCorrectOutput() { diff --git a/Src/ILGPUC.Tests/IRTests/NullArrayIRTests.cs b/Src/ILGPUC.Tests/IRTests/NullArrayIRTests.cs new file mode 100644 index 0000000000..a8a5d69c60 --- /dev/null +++ b/Src/ILGPUC.Tests/IRTests/NullArrayIRTests.cs @@ -0,0 +1,96 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: NullArrayIRTests.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + + +// disable: max_line_length +using ILGPUC.Backends; +using ILGPUC.Tests.Framework; +using ILGPUC.Tests.Kernels; +using Xunit; +using Xunit.Abstractions; + +namespace ILGPUC.Tests.IRTests; + +public sealed class NullArrayIRTests : CompilationTestBase +{ + public NullArrayIRTests(ITestOutputHelper output) : base(output) { } + + // --- AfterFrontend --- + + [Fact] + public void ConditionalNull_AfterFrontend() => + VerifyAfterFrontend(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.ConditionalNullKernel))); + + [Fact] + public void NullArgument_AfterFrontend() => + VerifyAfterFrontend(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.NullArgumentKernel))); + + [Fact] + public void EmptyNotNull_AfterFrontend() => + VerifyAfterFrontend(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.EmptyNotNullKernel))); + + [Fact] + public void EmptyArray_AfterFrontend() => + VerifyAfterFrontend(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.EmptyArrayKernel))); + + // --- AfterGlobalOpt --- + + [Theory] + [MemberData(nameof(TestTypes.OptLevelsAndModes), MemberType = typeof(TestTypes))] + public void ConditionalNull_AfterGlobalOpt(OptimizationLevel opt, CompilationMode mode) => + VerifyAfterGlobalOpt(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.ConditionalNullKernel)), opt, mode); + + [Theory] + [MemberData(nameof(TestTypes.OptLevelsAndModes), MemberType = typeof(TestTypes))] + public void NullArgument_AfterGlobalOpt(OptimizationLevel opt, CompilationMode mode) => + VerifyAfterGlobalOpt(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.NullArgumentKernel)), opt, mode); + + [Theory] + [MemberData(nameof(TestTypes.OptLevelsAndModes), MemberType = typeof(TestTypes))] + public void EmptyNotNull_AfterGlobalOpt(OptimizationLevel opt, CompilationMode mode) => + VerifyAfterGlobalOpt(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.EmptyNotNullKernel)), opt, mode); + + [Theory] + [MemberData(nameof(TestTypes.OptLevelsAndModes), MemberType = typeof(TestTypes))] + public void EmptyArray_AfterGlobalOpt(OptimizationLevel opt, CompilationMode mode) => + VerifyAfterGlobalOpt(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.EmptyArrayKernel)), opt, mode); + + // --- AfterBackendTransforms --- + + [Theory] + [MemberData(nameof(TestTypes.BackendTypesAndOptLevelsAndModes), MemberType = typeof(TestTypes))] + public void ConditionalNull_AfterBackendTransforms(BackendType backend, OptimizationLevel opt, CompilationMode mode) => + VerifyAfterBackendTransforms(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.ConditionalNullKernel)), + backend, opt, mode); + + [Theory] + [MemberData(nameof(TestTypes.BackendTypesAndOptLevelsAndModes), MemberType = typeof(TestTypes))] + public void NullArgument_AfterBackendTransforms(BackendType backend, OptimizationLevel opt, CompilationMode mode) => + VerifyAfterBackendTransforms(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.NullArgumentKernel)), + backend, opt, mode); + + [Theory] + [MemberData(nameof(TestTypes.BackendTypesAndOptLevelsAndModes), MemberType = typeof(TestTypes))] + public void EmptyNotNull_AfterBackendTransforms(BackendType backend, OptimizationLevel opt, CompilationMode mode) => + VerifyAfterBackendTransforms(GetKernel( + typeof(NullArrayKernels), nameof(NullArrayKernels.EmptyNotNullKernel)), + backend, opt, mode); +} diff --git a/Src/ILGPUC.Tests/Kernels/NullArrayKernels.cs b/Src/ILGPUC.Tests/Kernels/NullArrayKernels.cs new file mode 100644 index 0000000000..f67eb5dd0b --- /dev/null +++ b/Src/ILGPUC.Tests/Kernels/NullArrayKernels.cs @@ -0,0 +1,253 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: NullArrayKernels.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + +using ILGPU; +using ILGPU.Runtime; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace ILGPUC.Tests.Kernels; + +/// +/// Kernel definitions for null arrays and their null tests. +/// +static class NullArrayKernels +{ + private struct ArrayHolder + { + public int[]? Values; + } + + private enum IntEnum + { + Zero, + } + + // Only the element type of its empty array is used +#pragma warning disable CS0649 + private struct IntBox + { + public int Value; + } +#pragma warning restore CS0649 + + private static int LengthOrMinusOne(int[]? values) => + values == null ? -1 : values.Length; + + private static bool IsNotNull(int[]? values) => values != null; + + private static int[]? AllocateOrNull(int x) => x > 1 ? new int[4] : null; + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool IsEmptyArray(int[] values) => values == Array.Empty(); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool IsEmptyUIntArray(int[] values) => + (object?)values == Array.Empty(); + + private static void Ensure([NotNull] ref int[]? values) + { + values ??= new int[3]; + values[0] = 1; + } + + /// + /// Merge an allocated array with null and test the result for null. + /// + public static void ConditionalNullKernel( + Index1D index, ArrayView1D output) + { + int[]? a = (index.X & 1) == 0 ? new int[3] : null; + output[index] = a == null ? -1 : a.Length; + } + + /// + /// Assign null to a local array and test it with ==, !=, is and is not. + /// + public static void NullCheckKernel( + Index1D index, ArrayView1D output) + { + int[]? a = null; + if (index.X > 1) + a = new int[2]; + int r = 0; + if (a != null) r += 1; + if (a is null) r += 10; + if (a is not null) r += 100; + output[index] = r; + } + + /// + /// Replace a null array with ??. + /// + public static void CoalesceKernel( + Index1D index, ArrayView1D output) + { + int[]? a = index.X > 1 ? new int[2] : null; + int[] b = a ?? new int[5]; + output[index] = b.Length; + } + + /// + /// Read the length of an array that may be null with ?.Length. + /// + public static void ConditionalLengthKernel( + Index1D index, ArrayView1D output) + { + int[]? a = index.X > 1 ? new int[2] : null; + output[index] = a?.Length ?? -1; + } + + /// + /// Pass null, an empty array and an allocated array to helpers that test + /// their argument for null, by a branch and by cgt.un. + /// + public static void NullArgumentKernel( + Index1D index, ArrayView1D output) + { + output[index] = LengthOrMinusOne(null) * 100 + + LengthOrMinusOne(new int[0]) * 10 + + LengthOrMinusOne(new int[3]) + + (IsNotNull(new int[2]) ? 1000 : 0) + + (IsNotNull(null) ? 10000 : 0); + } + + /// + /// Test the unassigned (null) array field of a default structure. + /// + public static void DefaultFieldKernel( + Index1D index, ArrayView1D output) + { + ArrayHolder holder = default; + if (index.X > 1) + holder.Values = new int[4]; + output[index] = holder.Values is null ? -1 : holder.Values.Length; + } + + /// + /// Merge an empty array with null: empty arrays are not null. + /// + public static void EmptyNotNullKernel( + Index1D index, ArrayView1D output) + { + int[]? a = index.X > 1 ? new int[0] : null; + output[index] = a == null ? -1 : a.Length; + } + + /// + /// Compare arrays by reference, also as objects of different types. + /// + public static void ReferenceEqualsKernel( + Index1D index, ArrayView1D output) + { + int[] a = new int[2]; + int[] b = new int[2]; + int[] c = index.X > 1 ? a : b; + float[]? f = index.X > 2 ? new float[2] : null; + output[index] = (c == a ? 1 : 0) + (c == b ? 10 : 0) + + (ReferenceEquals(c, null) ? 100 : 0) + + ((object?)c == f ? 1000 : 0); + } + + /// + /// Return null from a helper and test the result with a property pattern + /// and ?[]. + /// + public static void ReturnNullKernel( + Index1D index, ArrayView1D output) + { + int[]? a = AllocateOrNull(index.X & 3); + output[index] = a is { Length: > 2 } ? 1 : a?[0] ?? -1; + } + + /// + /// Replace null arrays with ??= in a structure field and through a ref + /// parameter, and store null to a field. + /// + public static void CoalesceAssignKernel( + Index1D index, ArrayView1D output) + { + ArrayHolder holder = default; + if (index.X > 1) + holder.Values = new int[2]; + holder.Values ??= new int[3]; + int[] b = holder.Values; + holder.Values = null; + int[]? c = index.X > 2 ? b : null; + Ensure(ref c); + output[index] = b.Length + (holder.Values == null ? 10 : 0) + + c.Length * 100 + c[0]; + } + + /// + /// Compare the arrays of Array.Empty, which are not null and are the same + /// array for the same element type, also in a NoInlining helper, but not a + /// new empty array or an empty array of another type, also not of uint (also + /// in a NoInlining helper), an int enum or a structure of one int, whose IR + /// type is the same as int. + /// + public static void EmptyArrayKernel( + Index1D index, ArrayView1D output) + { + int[] a = Array.Empty(); + int[] b = Array.Empty(); + float[] f = Array.Empty(); + int[] c = (index.X & 1) == 0 ? Array.Empty() : new int[0]; + output[index] = a.Length * 100000 + (a is not null ? 1 : 0) + + (a == b ? 10 : 0) + (c == a ? 100 : 0) + + (IsEmptyArray(b) ? 1000 : 0) + (new int[0] == a ? 10000 : 0) + + ((object?)a == f ? 1000000 : 0) + + ((object?)a == Array.Empty() ? 10000000 : 0) + + ((object?)a == Array.Empty() ? 10000000 : 0) + + ((object?)a == Array.Empty() ? 10000000 : 0) + + (IsEmptyUIntArray(b) ? 10000000 : 0); + } + + /// + /// Replace a conditional null array with ?? while another conditional null + /// array stays on the IL stack, and test the result for null. + /// + public static void CoalesceOnStackKernel( + Index1D index, ArrayView1D output) + { + output[index] = ((index.X > 1 ? new int[2] : null) ?? + (index.X < 1 ? new int[1] : null)) == null ? -1 : 1; + } + + /// + /// Read the length of null itself (ldnull; ldlen), which is 0 in kernels. + /// + public static void NullLengthKernel( + Index1D index, ArrayView1D output) + { + output[index] = ((int[]?)null)!.Length + index.X; + } + + /// + /// Replace a null local with a new array in the first iteration of a loop, + /// which joins the null array and the new array in the loop header. + /// + public static void AssignInLoopKernel( + Index1D index, ArrayView1D output) + { + int[]? a = null; + int s = 0; + for (int k = 0; k < 3; ++k) + { + if (a == null) + a = new int[3]; + a[k] = k + index.X; + s += a.Length; + } + output[index] = s * 100 + a![2]; + } +} diff --git a/Src/ILGPUC.Tests/Snapshots b/Src/ILGPUC.Tests/Snapshots index 2e46bff036..ae0154de8d 160000 --- a/Src/ILGPUC.Tests/Snapshots +++ b/Src/ILGPUC.Tests/Snapshots @@ -1 +1 @@ -Subproject commit 2e46bff03600400e0348e99997d46fc8a28e6d55 +Subproject commit ae0154de8d6fed9cba1388264dc7a245edbecd96 diff --git a/Src/ILGPUC.Tests/TestPrograms/Array/NullArrayStackValues.cs b/Src/ILGPUC.Tests/TestPrograms/Array/NullArrayStackValues.cs new file mode 100644 index 0000000000..d177d2dc86 --- /dev/null +++ b/Src/ILGPUC.Tests/TestPrograms/Array/NullArrayStackValues.cs @@ -0,0 +1,163 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: NullArrayStackValues.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + + +// disable: max_line_length +// Test program: NullArrayStackValues +// Null arrays that stay on the IL stack across branches, as in Release builds: +// ?? of two conditional null arrays (the first one stays on the stack while the +// second one is selected), null locals compared with each other, conditional +// null arrays in loop bodies, the length of null arrays, which is 0 in +// kernels, also of a null local (ldnull; ldlen), and a null local that a loop +// replaces with a new array. Every thread writes ten results. +// Expected output (per thread): +// 0: 1 1 1 1 575 333 0 1 0 902 +// 1: -1 -1 -1 11 757 133 0 0 0 903 +// 2: 1 2 1 11 575 113 0 2 0 904 +// 3: 1 2 1 11 757 111 0 2 0 905 + +using System; +using ILGPU; +using ILGPU.Runtime; + +static class Kernels +{ + static int Coalesce(int i) + { + int[] a = i > 1 ? new int[2] : null; + int[] b = i < 1 ? new int[1] : null; + return (a ?? b) == null ? -1 : 1; + } + + static int CoalesceLength(int i) + { + int[] a = i > 1 ? new int[2] : null; + int[] b = i < 1 ? new int[1] : null; + int[] c = a ?? b; + return c == null ? -1 : c.Length; + } + + static int CoalesceSelected(int i) + { + int[] x = new int[3]; + int[] a = i > 1 ? x : null; + int[] b = i < 1 ? new int[1] : null; + return (a ?? b) == null ? -1 : 1; + } + + static int CompareNullLocals(int i) + { + int[] a = null; + int[] b = null; + int[] c = new int[1]; + int[] d = i > 0 ? c : null; + return (a == b ? 1 : 0) + (d == c ? 10 : 0); + } + + static int SelectInLoop(int i) + { + int r = 0; + int[] x = new int[5]; + for (int k = 0; k < 3; ++k) + { + int[] a = ((k + i) & 1) == 0 ? x : null; + r = r * 10 + (a?.Length ?? 7); + } + return r; + } + + static int CoalesceInLoop(int i) + { + int r = 0; + for (int k = 0; k < 3; ++k) + { + int[] a = k == i ? new int[4] : null; + int[] b = k > i ? new int[2] : null; + int t = (a ?? b) == null ? 1 : 3; + r = r * 10 + t; + } + return r; + } + + // The length of a null array is 0 in kernels + static int NullLength(int i) + { + int[] a = i > 9 ? new int[3] : null; + return a.Length; + } + + // A null local of a Release build is ldnull; ldlen + static int NullLocalLength() + { + int[] a = null; + return a.Length; + } + + static int CoalesceLengthOfNull(int i) + { + int[] a = i > 1 ? new int[2] : null; + int[] b = i < 1 ? new int[1] : null; + int[] c = a ?? b; + return c.Length; + } + + // A null local that the first loop iteration replaces with a new array + static int AssignInLoop(int i) + { + int[] a = null; + int s = 0; + for (int k = 0; k < 3; ++k) + { + if (a == null) + a = new int[3]; + a[k] = k + i; + s += a.Length; + } + return s * 100 + a[2]; + } + + public static void NullArrayStackKernel( + Index1D index, ArrayView1D output) + { + int i = index.X; + int o = i * 10; + output[o + 0] = Coalesce(i); + output[o + 1] = CoalesceLength(i); + output[o + 2] = CoalesceSelected(i); + output[o + 3] = CompareNullLocals(i); + output[o + 4] = SelectInLoop(i); + output[o + 5] = CoalesceInLoop(i); + output[o + 6] = NullLength(i); + output[o + 7] = CoalesceLengthOfNull(i); + output[o + 8] = NullLocalLength(); + output[o + 9] = AssignInLoop(i); + } +} + +static class Program +{ + static void Main() + { + using var context = Context.Create(b => b.Default()); + using var accelerator = context.GetPreferredDevice(preferCPU: true) + .CreateAccelerator(context); + var stream = accelerator.DefaultStream; + + using var output = stream.Allocate1D(40); + stream.Launch( + (Index1D)4, + index => Kernels.NullArrayStackKernel(index, output.View)); + stream.Synchronize(); + + foreach (var v in output.GetAsArray1D()) + Console.WriteLine(v); + } +} diff --git a/Src/ILGPUC.Tests/TestPrograms/Array/NullArrays.cs b/Src/ILGPUC.Tests/TestPrograms/Array/NullArrays.cs new file mode 100644 index 0000000000..6e1984983c --- /dev/null +++ b/Src/ILGPUC.Tests/TestPrograms/Array/NullArrays.cs @@ -0,0 +1,176 @@ +// --------------------------------------------------------------------------------------- +// ILGPU +// Copyright (c) 2026 ILGPU Project +// www.ilgpu.net +// +// File: NullArrays.cs +// +// This file is part of ILGPU and is distributed under the University of Illinois Open +// Source License. See LICENSE.txt for details. +// --------------------------------------------------------------------------------------- + + +// disable: max_line_length +// Test program: NullArrays +// Every thread selects null or allocated arrays depending on its index and +// tests them for null: conditional null arrays, ??, ?.Length, null arguments of +// inlined and of NoInlining helpers, the unassigned array field of a default +// structure, empty arrays (which are not null) and reference equality. Every +// thread writes eight results. +// Expected output (per thread): +// 0: 1 3 3 -1 -1 1 0 -2 +// 1: -1 5 -2 -1 -1 0 0 -2 +// 2: 3 3 3 0 -1 11 11 -2 +// 3: -1 5 -2 0 4 10 11 3 +// A second kernel tests ReferenceEquals, null arrays returned from helpers, +// ?[], property patterns, arrays compared as objects, ??= on a field and on a +// ref parameter, and writes six results per thread: +// 0: 1 -1 1 3 31 0 +// 1: 1 -1 1 3 31 0 +// 2: 0 4 0 2 41 1 +// 3: 0 4 0 2 41 1 +// A third kernel tests Array.Empty, whose arrays are not null and are the same +// array for the same element type, also in a NoInlining helper, but not a new +// empty array or an empty array of another type, also not of uint (also in a +// NoInlining helper), an int enum or a structure of one int, whose IR type is +// the same as int. It writes 1111 for even threads, which select Array.Empty, +// and 1011 for odd threads, which select a new empty array. + +using System; +using System.Runtime.CompilerServices; +using ILGPU; +using ILGPU.Runtime; + +static class Kernels +{ + struct Holder + { + public int[] Values; + } + + enum IntEnum + { + Zero, + } + + struct IntBox + { + public int Value; + } + + static int LengthOrMinusOne(int[] values) => + values == null ? -1 : values.Length; + + [MethodImpl(MethodImplOptions.NoInlining)] + static int CountNotNull(int[] first, int[] second) => + (first != null ? 1 : 0) + (second is not null ? 10 : 0); + + public static void NullArrayKernel( + Index1D index, ArrayView1D output) + { + int i = index.X; + int[] a = (i & 1) == 0 ? new int[3] : null; + if (a != null) + a[i % 3] = i + 1; + int[] b = a ?? new int[5]; + int[] empty = i > 1 ? new int[0] : null; + Holder holder = default; + if (i == 3) + holder.Values = new int[4]; + int[] x = new int[2]; + int[] y = new int[2]; + int[] z = i > 1 ? x : y; + + int o = i * 8; + output[o + 0] = a == null ? -1 : a[i % 3]; + output[o + 1] = b.Length; + output[o + 2] = a?.Length ?? -2; + output[o + 3] = LengthOrMinusOne(empty); + output[o + 4] = holder.Values is null ? -1 : holder.Values.Length; + output[o + 5] = CountNotNull(a, empty); + output[o + 6] = (z == x ? 1 : 0) + (z != y ? 10 : 0); + output[o + 7] = LengthOrMinusOne(null) + LengthOrMinusOne(holder.Values); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static bool IsEmptyArray(int[] values) => values == Array.Empty(); + + [MethodImpl(MethodImplOptions.NoInlining)] + static bool IsEmptyUIntArray(int[] values) => + (object)values == Array.Empty(); + + public static void EmptyArrayKernel( + Index1D index, ArrayView1D output) + { + int[] a = Array.Empty(); + int[] b = Array.Empty(); + float[] f = Array.Empty(); + int[] c = (index.X & 1) == 0 ? Array.Empty() : new int[0]; + output[index] = a.Length * 100000 + (a is not null ? 1 : 0) + + (a == b ? 10 : 0) + (c == a ? 100 : 0) + + (IsEmptyArray(b) ? 1000 : 0) + (new int[0] == a ? 10000 : 0) + + ((object)a == f ? 1000000 : 0) + + ((object)a == Array.Empty() ? 10000000 : 0) + + ((object)a == Array.Empty() ? 10000000 : 0) + + ((object)a == Array.Empty() ? 10000000 : 0) + + (IsEmptyUIntArray(b) ? 10000000 : 0); + } + + static int[] Make(int x) => x > 1 ? new int[4] : null; + + static void Ensure(ref int[] values) + { + values ??= new int[3]; + values[0] += 1; + } + + public static void NullReferenceKernel( + Index1D index, ArrayView1D output) + { + int i = index.X; + int[] a = Make(i); + float[] f = i > 2 ? new float[2] : null; + Holder holder = default; + if (i > 1) + holder.Values = new int[2]; + holder.Values ??= new int[3]; + int[] r = i == 1 ? null : a; + Ensure(ref r); + + int o = i * 6; + output[o + 0] = ReferenceEquals(a, null) ? 1 : 0; + output[o + 1] = a is { Length: > 2 } ? a.Length : a?[0] ?? -1; + output[o + 2] = (object)a == f ? 1 : 0; + output[o + 3] = holder.Values.Length; + output[o + 4] = r.Length * 10 + r[0]; + output[o + 5] = r == a ? 1 : 0; + } +} + +static class Program +{ + static void Main() + { + using var context = Context.Create(b => b.Default()); + using var accelerator = context.GetPreferredDevice(preferCPU: true) + .CreateAccelerator(context); + var stream = accelerator.DefaultStream; + + using var output = stream.Allocate1D(32); + stream.Launch((Index1D)4, index => Kernels.NullArrayKernel(index, output.View)); + using var references = stream.Allocate1D(24); + stream.Launch( + (Index1D)4, + index => Kernels.NullReferenceKernel(index, references.View)); + using var empty = stream.Allocate1D(4); + stream.Launch((Index1D)4, index => Kernels.EmptyArrayKernel(index, empty.View)); + stream.Synchronize(); + + foreach (var v in output.GetAsArray1D()) + Console.WriteLine(v); + foreach (var v in references.GetAsArray1D()) + Console.WriteLine(v); + foreach (var v in empty.GetAsArray1D()) + Console.WriteLine(v); + } +} diff --git a/Src/ILGPUC/Backends/CodeGenerator.cs b/Src/ILGPUC/Backends/CodeGenerator.cs index b1696045a8..e9c09dd9b1 100644 --- a/Src/ILGPUC/Backends/CodeGenerator.cs +++ b/Src/ILGPUC/Backends/CodeGenerator.cs @@ -173,6 +173,20 @@ internal static void EmitGlobalDeclaration( // Emit with address space qualifier var qualifiedTypeName = context.LanguageConfig.GetQualifiedTypeName( typeName, addressSpaceKeyword); + + if (addressSpace == MemoryAddressSpace.Local && + global.ArrayLength.HasValue && + context.OffsetsLocalArrays) + { + // Start the array one element into a longer zeroed array, which + // keeps it away from address 0, the null pointer + var length = global.ArrayLength.Value.Int32Value + 1; + context.WriteLine( + $"{qualifiedTypeName} {globalName}_storage[{length}] = {{0}};"); + context.WriteLine( + $"{qualifiedTypeName}* {globalName} = {globalName}_storage + 1;"); + return; + } context.Write($"{qualifiedTypeName} {globalName}"); // Handle array allocations diff --git a/Src/ILGPUC/Backends/CompiledKernelGenerator.cs b/Src/ILGPUC/Backends/CompiledKernelGenerator.cs index c9337941c5..ca35bc37b3 100644 --- a/Src/ILGPUC/Backends/CompiledKernelGenerator.cs +++ b/Src/ILGPUC/Backends/CompiledKernelGenerator.cs @@ -1059,6 +1059,7 @@ private LauncherEmissionContext CreateEmissionContext() => BufferPool = _compiled.BufferPool, ActiveEmbedMode = _effectiveEmbedMode, MathMode = _module.MathMode, + NullSafeLocals = _module.EnableMetalNullSafeLocals, KernelSourceCode = _compiled.SourceCode, }; diff --git a/Src/ILGPUC/Backends/ExpressionEmitter.cs b/Src/ILGPUC/Backends/ExpressionEmitter.cs index 518fde6f90..50aa6f91c0 100644 --- a/Src/ILGPUC/Backends/ExpressionEmitter.cs +++ b/Src/ILGPUC/Backends/ExpressionEmitter.cs @@ -239,8 +239,7 @@ private Emitted EmitDirect(Value value) // NewView from a Global → resolve to the global's CPURuntimeView. // The global is declared as a CPURuntimeView backed by stackalloc // in CPUMethodEmitter.EmitGlobalDeclarations(). - NewView nv when nv.Pointer is Global g => new Emitted( - context.GetValueName(g), Prec.Atom), + NewView nv when nv.Pointer is Global g => EmitGlobalView(nv, g), // Basic block values PhiValue phi => new Emitted( @@ -332,7 +331,24 @@ internal string EmitAllocaDeclaration(Alloca alloca) // Emit the storage array var storageTypeName = context.LanguageConfig.GetQualifiedTypeName( elemTypeName, addrSpace); - sb.Append($"{storageTypeName} {storageName}[{GetAllocaLength(alloca)}];"); + int length = GetAllocaLength(alloca); + if (pointerType.AddressSpace == MemoryAddressSpace.Local && + context.OffsetsLocalArrays) + { + // Start the storage one element into a longer zeroed array, which + // keeps it away from address 0, the null pointer. Without zeroing + // the unused element, the Metal compiler read the first bytes of + // the storage through byte pointers as zero. + sb.Append($"{storageTypeName} {storageName}_base[{length + 1}] = {{}};"); + sb.Append('\n'); + sb.Append( + context.LanguageConfig.GetPointerTypeName(elemTypeName, addrSpace)); + sb.Append($" {storageName} = {storageName}_base + 1;"); + } + else + { + sb.Append($"{storageTypeName} {storageName}[{length}];"); + } // Emit the pointer variable. Build the pointer type via the // language config so backends that don't carry an address-space @@ -1317,6 +1333,23 @@ private Emitted EmitGetViewLength(GetViewLength viewLen) return new Emitted($"{inner}.{fieldName}", Prec.Atom); } + /// + /// Emits the view of a global: the declared view of the global, or a view + /// of its first elements if the view is shorter, such as the view of an + /// empty array, whose global has a single element. + /// + private Emitted EmitGlobalView(NewView view, Global global) + { + var name = context.GetValueName(global); + if (global.ArrayLength is not { } arrayLength || + view.Length is not PrimitiveValue length || + length.Int64Value == arrayLength.Int64Value) + { + return new Emitted(name, Prec.Atom); + } + return new Emitted($"{name}.SubView(0, {length.Int64Value})", Prec.Atom); + } + /// /// Emits a sub-view operation. For the CPU backend this produces /// view.SubView(offset, length); for GPU backends the view diff --git a/Src/ILGPUC/Backends/GenerationContext.cs b/Src/ILGPUC/Backends/GenerationContext.cs index 886921c1f7..fa5e4defa6 100644 --- a/Src/ILGPUC/Backends/GenerationContext.cs +++ b/Src/ILGPUC/Backends/GenerationContext.cs @@ -51,6 +51,13 @@ sealed partial class GenerationContext( /// public LanguageConfiguration LanguageConfig { get; } = languageConfig; + /// + /// Returns true if thread-local arrays and allocations start one element + /// into a longer array, which the language needs and the module allows. + /// + public bool OffsetsLocalArrays => + LanguageConfig.OffsetsLocalArrays && Module.EnableMetalNullSafeLocals; + /// /// Returns how the entry point is launched. /// diff --git a/Src/ILGPUC/Backends/LanguageConfiguration.cs b/Src/ILGPUC/Backends/LanguageConfiguration.cs index 3e720fa4bc..ff54da6fe0 100644 --- a/Src/ILGPUC/Backends/LanguageConfiguration.cs +++ b/Src/ILGPUC/Backends/LanguageConfiguration.cs @@ -150,6 +150,16 @@ public virtual string GetPointerTypeName( /// public virtual string? FormatGlobalAddress(Global global, string name) => null; + /// + /// Returns true if thread-local arrays and allocations must not start at + /// address 0, as on Metal devices that place the first thread-private + /// object of a kernel at address 0, where it compares equal to the null + /// pointer. They then start one element into a longer array, unless + /// is turned + /// off. + /// + public virtual bool OffsetsLocalArrays => false; + /// /// Formats a null literal of the given type. /// Default: a zero-initialized C-style compound literal. CPU override: diff --git a/Src/ILGPUC/Backends/LauncherEmitter.cs b/Src/ILGPUC/Backends/LauncherEmitter.cs index a740f2723f..dcb484f09c 100644 --- a/Src/ILGPUC/Backends/LauncherEmitter.cs +++ b/Src/ILGPUC/Backends/LauncherEmitter.cs @@ -227,6 +227,12 @@ sealed class LauncherEmissionContext /// public MathMode MathMode { get; init; } + /// + /// True if the kernel keeps its thread storage away from address 0, which + /// the Metal runtime checks when it loads the kernel. + /// + public bool NullSafeLocals { get; init; } = true; + /// /// Number of index dimensions (1 = scalar, 2 = Index2D, 3 = Index3D). /// Used by the CPU backend to decompose linear indices into multi-dim diff --git a/Src/ILGPUC/Backends/Metal/MetalCompiledKernelEmitter.cs b/Src/ILGPUC/Backends/Metal/MetalCompiledKernelEmitter.cs index f1a2d56893..dc82178889 100644 --- a/Src/ILGPUC/Backends/Metal/MetalCompiledKernelEmitter.cs +++ b/Src/ILGPUC/Backends/Metal/MetalCompiledKernelEmitter.cs @@ -13,6 +13,7 @@ // disable: max_line_length using ILGPU.Runtime; using ILGPU.Runtime.Metal; +using System.Collections.Generic; namespace ILGPUC.Backends.Metal; @@ -37,23 +38,29 @@ sealed class MetalCompiledKernelEmitter( public override void EmitPlatformConstructorArgs(LauncherEmissionContext ctx) { - ctx.WriteLine($"MetalTargetOS.{targetOS},"); - // In source fallback mode, pass KernelSource to the constructor - if (ctx.ActiveEmbedMode == KernelEmbedMode.Source) - ctx.WriteLine($"MetalGPUFamily.{gpuFamily},"); - else - ctx.WriteLine($"MetalGPUFamily.{gpuFamily})"); + List args = + [ + $"MetalTargetOS.{targetOS}", + $"MetalGPUFamily.{gpuFamily}", + ]; + // In source fallback mode, pass KernelSource to the constructor. // Source compiled at runtime defaults to strict math; the fast math // modes opt into the Metal compiler's fast math. if (ctx.ActiveEmbedMode == KernelEmbedMode.Source) { - ctx.WriteLine(ctx.MathMode == MathMode.Default - ? "KernelSource)" - : "KernelSource,"); + args.Add("KernelSource"); if (ctx.MathMode != MathMode.Default) - ctx.WriteLine("fastMath: true)"); + args.Add("fastMath: true"); } + + // Kernels whose thread storage may start at address 0 tell the + // runtime, which warns on devices that place it there + if (!ctx.NullSafeLocals) + args.Add("nullSafeLocals: false"); + + for (int i = 0; i < args.Count; i++) + ctx.WriteLine(args[i] + (i + 1 < args.Count ? "," : ")")); } public override void EmitRequiredCapabilitiesProperty(LauncherEmissionContext ctx) diff --git a/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs b/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs index eb47334b26..7b8dd152a0 100644 --- a/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs +++ b/Src/ILGPUC/Backends/Metal/MetalLanguageConfiguration.cs @@ -286,6 +286,8 @@ public override string EmitNonFlattenedKernelParam( return $" {typeName} {paramName} = ({typeName})thread_position_in_grid.x;"; } + public override bool OffsetsLocalArrays => true; + public override bool IsFileScopeAddressSpace(MemoryAddressSpace addressSpace) => addressSpace == MemoryAddressSpace.Constant; diff --git a/Src/ILGPUC/CompilationProperties.cs b/Src/ILGPUC/CompilationProperties.cs index ca51354141..05584ac804 100644 --- a/Src/ILGPUC/CompilationProperties.cs +++ b/Src/ILGPUC/CompilationProperties.cs @@ -213,6 +213,14 @@ public enum ArrayMode /// a helper predicate (such as IsFloat<T>()) at compile time. Calls /// that need more are compiled as calls. /// +/// +/// True if Metal kernels keep local arrays and the locals they take the address +/// of away from address 0, which some devices give to the first thread-private +/// object of a kernel and which compares equal to null. This is the default +/// setting (--metal-null-safe-locals); turning it off saves one element +/// per local array, and the Metal runtime warns when such a kernel is loaded on +/// a device known to place locals at address 0. +/// public sealed record class CompilationProperties( DebugSymbolsMode DebugSymbolsMode = DebugSymbolsMode.Default, bool EnableAssertions = true, @@ -224,7 +232,8 @@ public sealed record class CompilationProperties( FusedMultiplyAddMode FusedMultiplyAddMode = FusedMultiplyAddMode.Fast, StaticFieldMode StaticFieldMode = StaticFieldMode.Default, ArrayMode ArrayMode = ArrayMode.Default, - int ConstantEvaluationBudget = CompilationProperties.DefaultConstantEvaluationBudget) + int ConstantEvaluationBudget = CompilationProperties.DefaultConstantEvaluationBudget, + bool EnableMetalNullSafeLocals = true) { /// /// The default of . diff --git a/Src/ILGPUC/Frontend/Block.cs b/Src/ILGPUC/Frontend/Block.cs index c2a02a3b05..2369dd781d 100644 --- a/Src/ILGPUC/Frontend/Block.cs +++ b/Src/ILGPUC/Frontend/Block.cs @@ -301,7 +301,7 @@ public ValueBuilderList PopMethodArgs( /// /// Pops a value from the stack that can be used in the context of - /// compare operations. + /// compare operations. Arrays are compared as references. /// /// The current location. /// The conversion flags. @@ -309,7 +309,8 @@ public ValueBuilderList PopMethodArgs( /// The popped value from the stack that can be used in the /// context of compare and arithmetic operations. public Value PopCompareValue(Location location, ConvertFlags flags) => - PeekBasicValueType(location) == BasicValueType.Int1 + PeekBasicValueType(location) == BasicValueType.Int1 || + PeekType(location) is ArrayType ? Pop() : PopCompareOrArithmeticValue(location, flags); diff --git a/Src/ILGPUC/Frontend/CodeGenerator/Arrays.cs b/Src/ILGPUC/Frontend/CodeGenerator/Arrays.cs index 20687d02c3..7705995086 100644 --- a/Src/ILGPUC/Frontend/CodeGenerator/Arrays.cs +++ b/Src/ILGPUC/Frontend/CodeGenerator/Arrays.cs @@ -193,12 +193,81 @@ private void MakeStoreElement(Type elementType) elementType.ToTargetUnsignedFlags())); } + /// + /// Compares two array references, such as an array with null. Every array + /// has a buffer of its own, also an empty array, while the null array has + /// none: arrays are compared by the addresses of their first elements. + /// + /// The left operand. + /// The right operand. + /// The comparison kind. + /// The comparison flags. + private Value CreateArrayCompare( + Value left, + Value right, + CompareKind kind, + CompareFlags flags) + { + // The null reference of ldnull is the null array of the other operand + if (left.Type is not ArrayType) + left = CreateConversion(left, right.Type, ConvertFlags.None); + if (right.Type is not ArrayType) + right = CreateConversion(right, left.Type, ConvertFlags.None); + + // A reference is greater than null if it is not null (cgt.un) + bool unsigned = (flags & CompareFlags.UnsignedOrUnordered) == + CompareFlags.UnsignedOrUnordered; + if (unsigned && + (kind == CompareKind.GreaterThan && right is NullValue || + kind == CompareKind.LessThan && left is NullValue)) + { + kind = CompareKind.NotEqual; + } + + var leftAddress = CreateArrayAddress(left); + var rightAddress = CreateArrayAddress(right); + if (!leftAddress.Type.Equals(rightAddress.Type)) + { + rightAddress = Builder.CreatePointerCast( + Location, + rightAddress, + left.GetTypeAs().ElementType); + } + return Builder.CreateCompare( + Location, + leftAddress, + rightAddress, + kind, + flags).ThrowIfNull(); + } + + /// + /// Creates the address of the first element of the given array. + /// + /// The array instance. + private Value CreateArrayAddress(Value array) + { + var laeaBuilder = Builder.CreateLoadArrayElementAddress(Location, array); + for (int i = 0, e = laeaBuilder.ArrayType.NumDimensions; i < e; ++i) + laeaBuilder.Add(Builder.CreatePrimitiveValue(Location, 0)); + return laeaBuilder.Seal(); + } + /// /// Realizes an array length value. /// private void MakeLoadArrayLength() { var array = Block.Pop(); + + // The length of the null reference of ldnull, such as of a null local + // in a Release build, is the length 0 of the null array + if (array is NullValue && array.Type is not ArrayType) + { + Block.Push(Builder.CreatePrimitiveValue(Location, 0)); + return; + } + var length = Builder.CreateGetArrayLength( Location, array).AsNotNull(); diff --git a/Src/ILGPUC/Frontend/CodeGenerator/Compare.cs b/Src/ILGPUC/Frontend/CodeGenerator/Compare.cs index ad7170f828..900ecf7bb7 100644 --- a/Src/ILGPUC/Frontend/CodeGenerator/Compare.cs +++ b/Src/ILGPUC/Frontend/CodeGenerator/Compare.cs @@ -78,6 +78,8 @@ private Value CreateCompare( { if (TryFoldReferenceCompare(left, right, compareKind, out bool constant)) return Builder.CreatePrimitiveValue(Location, constant); + if (left.Type is ArrayType || right.Type is ArrayType) + return CreateArrayCompare(left, right, compareKind, flags); var convertFlags = ConvertFlags.None; if ((flags & CompareFlags.UnsignedOrUnordered) == diff --git a/Src/ILGPUC/Frontend/CodeGenerator/ControlFlow.cs b/Src/ILGPUC/Frontend/CodeGenerator/ControlFlow.cs index d57bec481e..c0ae8765f5 100644 --- a/Src/ILGPUC/Frontend/CodeGenerator/ControlFlow.cs +++ b/Src/ILGPUC/Frontend/CodeGenerator/ControlFlow.cs @@ -169,7 +169,8 @@ private void MakeIntrinsicBranch(CompareKind kind) // For pointer types, compare against a null of the same pointer type // instead of a primitive zero to avoid Int64 → ptr conversion failures. - var rightValue = comparisonValue.Type is AddressSpaceType + // Arrays are compared with the null array. + var rightValue = comparisonValue.Type is AddressSpaceType or ArrayType ? Builder.CreateNull(Location, comparisonValue.Type) : Builder.CreatePrimitiveValue( Location, diff --git a/Src/ILGPUC/Frontend/CodeGenerator/Convert.cs b/Src/ILGPUC/Frontend/CodeGenerator/Convert.cs index 3bbf766eca..cd0c647a7d 100644 --- a/Src/ILGPUC/Frontend/CodeGenerator/Convert.cs +++ b/Src/ILGPUC/Frontend/CodeGenerator/Convert.cs @@ -54,6 +54,11 @@ private void MakeConvert(Type targetType, ILInstructionFlags instructionFlags) /// public Value CreateConversion(Value value, TypeValue targetType, ConvertFlags flags) { + // The null reference of ldnull becomes the null array, such as a null + // array stored to a local or passed to a parameter + if (targetType is ArrayType && value is NullValue) + return Builder.CreateNull(Location, targetType); + if (value.Type is AddressSpaceType) { // Native integers are pointers: conversions to other primitive diff --git a/Src/ILGPUC/Frontend/CodeGenerator/Objects.cs b/Src/ILGPUC/Frontend/CodeGenerator/Objects.cs index bd2a4c3e8b..7e30c527c2 100644 --- a/Src/ILGPUC/Frontend/CodeGenerator/Objects.cs +++ b/Src/ILGPUC/Frontend/CodeGenerator/Objects.cs @@ -526,6 +526,15 @@ private void MakeLoadObject(Type type) return; } + // ldind.ref loads an array stored at the address, such as an array + // field updated with ??= + if (type == typeof(object) && + address.Type is PointerType { ElementType: ArrayType }) + { + Block.Push(Builder.CreateLoad(Location, address)); + return; + } + var targetElementType = ModuleBuilder.CreateType(type); Block.Push(CreateLoad( address, @@ -542,6 +551,22 @@ private void MakeLoadObject(Type type) /// The target type. private void MakeStoreObject(Type type) { + // stind.ref stores an array to the address, such as a null array or an + // array field updated with ??= + var addressRef = new VariableRef( + Block.StackCounter - 2, + VariableRefType.Stack); + if (type == typeof(object) && + Block.GetValue(addressRef).Type is PointerType + { + ElementType: ArrayType arrayType + }) + { + var array = Block.Pop(arrayType, ConvertFlags.None); + CreateStore(Block.Pop(), array); + return; + } + var typeNode = ModuleBuilder.CreateType(type); var value = Block.Pop(typeNode, ConvertFlags.None); var address = Block.Pop(); diff --git a/Src/ILGPUC/Frontend/Intrinsic/Arrays.cs b/Src/ILGPUC/Frontend/Intrinsic/Arrays.cs index 6adf374292..50415e7edc 100644 --- a/Src/ILGPUC/Frontend/Intrinsic/Arrays.cs +++ b/Src/ILGPUC/Frontend/Intrinsic/Arrays.cs @@ -55,7 +55,9 @@ private static ArrayValue Arrays_CreateNew(ref InvocationContext context) } /// - /// Creates a new empty 1D array instance. + /// Returns the empty 1D array of the element type, whose back buffer all + /// calls with the same element type share, as Array.Empty returns the + /// same array in .NET. /// /// The current invocation context. /// The resulting value. @@ -64,10 +66,16 @@ private static ArrayValue Arrays_CreateNew(ref InvocationContext context) var location = context.Location; var builder = context.Builder; - var elementType = context.ModuleBuilder.CreateType( - context.GetMethodGenericArguments()[0]); + var managedElementType = context.GetMethodGenericArguments()[0]; + var elementType = context.ModuleBuilder.CreateType(managedElementType); var arrayType = context.ModuleBuilder.CreateArrayType(elementType, 1); - return builder.CreateEmptyArray(location, arrayType); + return builder.CreateEmptyArray( + location, + arrayType, + context.ModuleBuilder.GetEmptyArrayBuffer( + location, + managedElementType, + elementType)); } /// diff --git a/Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs b/Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs index dc71b5894c..13dc87784a 100644 --- a/Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs +++ b/Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs @@ -66,6 +66,7 @@ private ref struct MethodVisitor(int capacity) : ITraversalVisitor private DelegateHandleType? _delegateHandleType; private InlineList _globals = InlineList.Create(32); + private readonly Dictionary _emptyArrayBuffers = []; private readonly Dictionary _methodMapping = new(32); private readonly Dictionary _methods = new(32); @@ -1146,6 +1147,35 @@ private T UnifyType(T type) where T : TypeValue rawArrayLength: new PrimitiveValueBox(BasicValueType.Int32, count), arrayScale: arrayScale); + /// + /// Returns the back buffer that all empty arrays of the given element type + /// returned by share, so that they are the + /// same array as in .NET. It has a single element, which is never accessed. + /// The buffers are keyed by the managed element type, since types such as + /// int, uint and int enums share an IR type but not their empty array. + /// + /// The current location. + /// The managed element type. + /// The IR element type. + /// The shared back buffer. + public Global GetEmptyArrayBuffer( + Location location, + Type managedElementType, + TypeValue elementType) + { + if (!_emptyArrayBuffers.TryGetValue(managedElementType, out var global)) + { + global = CreateGlobalDirect( + location, + elementType, + MemoryAddressSpace.Local, + rawArrayLength: new PrimitiveValueBox(BasicValueType.Int32, 1)) + .AsNotNull(); + _emptyArrayBuffers.Add(managedElementType, global); + } + return global; + } + #endregion #region Methods diff --git a/Src/ILGPUC/IR/ModuleValues/Module.cs b/Src/ILGPUC/IR/ModuleValues/Module.cs index e1331da697..b2775089b3 100644 --- a/Src/ILGPUC/IR/ModuleValues/Module.cs +++ b/Src/ILGPUC/IR/ModuleValues/Module.cs @@ -156,6 +156,7 @@ internal void Initialize(ModuleBuilder moduleBuilder) MathMode = moduleBuilder.Properties.MathMode; FusedMultiplyAddMode = moduleBuilder.Properties.FusedMultiplyAddMode; + EnableMetalNullSafeLocals = moduleBuilder.Properties.EnableMetalNullSafeLocals; TargetPlatform = moduleBuilder.TargetPlatform; IntPointerArithmeticType = moduleBuilder.IntPointerArithmeticType; @@ -192,6 +193,12 @@ internal void Initialize(ModuleBuilder moduleBuilder) /// public FusedMultiplyAddMode FusedMultiplyAddMode { get; private set; } + /// + /// Returns true if Metal kernels keep their thread storage away from + /// address 0. + /// + public bool EnableMetalNullSafeLocals { get; private set; } + /// /// Returns the main entry point handle. /// diff --git a/Src/ILGPUC/IR/PureValues/Construction/Compare.cs b/Src/ILGPUC/IR/PureValues/Construction/Compare.cs index 4135e6dd8b..c5c0f0e150 100644 --- a/Src/ILGPUC/IR/PureValues/Construction/Compare.cs +++ b/Src/ILGPUC/IR/PureValues/Construction/Compare.cs @@ -66,6 +66,9 @@ partial class PureValueBuilder flags); } + if (TryFoldArrayCompare(left, right, kind, out bool equal)) + return CreatePrimitiveValue(location, equal); + var leftValue = left as PrimitiveValue; var rightValue = right as PrimitiveValue; if (leftValue is not null && rightValue is not null) @@ -171,4 +174,73 @@ private Value CreateNativeInteger(Location location, Value value) _ => CreateConvert(location, value, nativeIntType), }; } + + /// + /// Folds comparisons of array references, which compare the addresses of + /// the first elements of the arrays: every array allocation has a buffer + /// of its own, also an empty one, while the null array has none. + /// + /// The left operand. + /// The right operand. + /// The operation kind. + /// The result, if folded. + /// True if the comparison was folded. + private static bool TryFoldArrayCompare( + Value left, + Value right, + CompareKind kind, + out bool result) + { + result = false; + if (kind is not (CompareKind.Equal or CompareKind.NotEqual) || + !TryGetArrayReference(left, out var leftArray) || + !TryGetArrayReference(right, out var rightArray)) + { + return false; + } + + bool equal; + switch (leftArray, rightArray) + { + case (NullValue, NullValue): + equal = true; + break; + case (NullValue, ArrayValue): + case (ArrayValue, NullValue): + equal = false; + break; + case (ArrayValue leftValue, ArrayValue rightValue): + equal = leftValue.BackBuffer == rightValue.BackBuffer; + break; + default: + return false; + } + result = equal == (kind == CompareKind.Equal); + return true; + } + + /// + /// Returns the array whose first element the given address points to, or + /// the null pointer, such as the lowered address of the null array. + /// + /// The address. + /// The array or the null pointer, if any. + /// True if the address points to the first element. + private static bool TryGetArrayReference(Value address, out Value array) + { + if (address is PointerCast cast) + address = cast.Source; + array = address; + if (address is NullValue) + return true; + if (address is not LoadArrayElementAddress laea) + return false; + foreach (var dimension in laea.Dimensions) + { + if (!dimension.IsPrimitiveValue(0)) + return false; + } + array = laea.ArrayValue; + return true; + } } diff --git a/Src/ILGPUC/IR/PureValues/Construction/Structures.cs b/Src/ILGPUC/IR/PureValues/Construction/Structures.cs index d3500e15d1..1607cfd791 100644 --- a/Src/ILGPUC/IR/PureValues/Construction/Structures.cs +++ b/Src/ILGPUC/IR/PureValues/Construction/Structures.cs @@ -442,17 +442,41 @@ public ArrayValue.Builder CreateNewArray(Location location, ArrayType arrayType) new(this, location, arrayType); /// - /// Creates a new empty array value. + /// Creates a new empty array value. An empty array has a back buffer of a + /// single element, which is never accessed: the address of its first + /// element is not null, which distinguishes it from the null array. /// /// The current location. /// The parent array type of this array. /// A reference to the requested value. - public ArrayValue CreateEmptyArray(Location location, ArrayType arrayType) + public ArrayValue CreateEmptyArray(Location location, ArrayType arrayType) => + CreateEmptyArray( + location, + arrayType, + ModuleBuilder.CreateGlobal( + location, + arrayType.ElementType, + MemoryAddressSpace.Local, + CreatePrimitiveValue(location, 1)).ThrowIfNull()); + + /// + /// Creates a new empty array value with the given back buffer of a single + /// element, such as the back buffer that all empty arrays of + /// with the same element type share. + /// + /// The current location. + /// The parent array type of this array. + /// The back buffer of the array. + /// A reference to the requested value. + public ArrayValue CreateEmptyArray( + Location location, + ArrayType arrayType, + Global backBuffer) { var combined = ValueBuilderList.Create( Generation, 1 + arrayType.NumDimensions); - combined.Add(ModuleBuilder.UndefinedValue); + combined.Add(backBuffer); for (int i = 0; i < arrayType.NumDimensions; ++i) combined.Add(CreatePrimitiveValue(location, 0)); return FinishArrayValueCombined(location, arrayType, ref combined); diff --git a/Src/ILGPUC/IR/PureValues/Construction/Views.cs b/Src/ILGPUC/IR/PureValues/Construction/Views.cs index 3d845478ab..9e5ad2e69a 100644 --- a/Src/ILGPUC/IR/PureValues/Construction/Views.cs +++ b/Src/ILGPUC/IR/PureValues/Construction/Views.cs @@ -165,6 +165,19 @@ source.Type is ViewType && elementIndex = convertValue.Value; } + // The first element of a null view, such as the view of the null array, + // is at the null address + if (source is NullValue && + addressSpaceType is ViewType && + elementIndex.IsPrimitiveValue(0)) + { + return CreateNull( + location, + ModuleBuilder.CreatePointerType( + addressSpaceType.ElementType, + addressSpaceType.AddressSpace)); + } + // Fold primitive pointer arithmetic that does not change anything return source.Type is PointerType && elementIndex.IsPrimitiveValue(0) ? source diff --git a/Src/ILGPUC/IR/Transformations/LowerArrays.cs b/Src/ILGPUC/IR/Transformations/LowerArrays.cs index 5d3e37aec2..f3c73b0fe3 100644 --- a/Src/ILGPUC/IR/Transformations/LowerArrays.cs +++ b/Src/ILGPUC/IR/Transformations/LowerArrays.cs @@ -84,12 +84,6 @@ protected override TypeValue TransformType( var backBuffer = transform.Rewrite(value.BackBuffer); int numDims = value.NumDimensions; - // Empty array: BackBuffer is UndefinedValue - if (value.BackBuffer is UndefinedValue) - { - return LowerEmptyArray(transform, value); - } - // Compute total length for the view Value totalLength = transform.CreatePrimitiveValue(location, 1); for (int i = 0; i < numDims; ++i) @@ -116,40 +110,6 @@ protected override TypeValue TransformType( return structBuilder.Seal(); } - /// - /// Lowers an empty array to a null view or struct. - /// - [MethodImpl(MethodImplOptions.AggressiveOptimization)] - private static Value? LowerEmptyArray( - PureValueTransform transform, - ArrayValue value) - { - var location = value.Location; - int numDims = value.NumDimensions; - var arrayType = value.Type; - - // Create null pointer for empty view - var elementType = transform.Rewrite(arrayType.ElementType); - var ptrType = transform.ModuleTransform.CreatePointerType( - elementType, - MemoryAddressSpace.Local); - var nullPtr = transform.CreateNull(location, ptrType); - var zeroLength = transform.CreatePrimitiveValue(location, 0); - var view = transform.CreateNewView(location, nullPtr, zeroLength); - - if (numDims == 1) - return view; - - // nD: struct { null view, 0, 0, ..., 0 } - var structBuilder = transform.CreateDynamicStructure( - location, - numDims + 1); - structBuilder.Add(view); - for (int i = 0; i < numDims; ++i) - structBuilder.Add(transform.CreatePrimitiveValue(location, 0)); - return structBuilder.Seal(); - } - /// /// Lowers a GetArrayLength operation. /// diff --git a/Src/ILGPUC/IR/Transformations/SSABuilder.cs b/Src/ILGPUC/IR/Transformations/SSABuilder.cs index 5b95039e95..af951e896d 100644 --- a/Src/ILGPUC/IR/Transformations/SSABuilder.cs +++ b/Src/ILGPUC/IR/Transformations/SSABuilder.cs @@ -290,6 +290,88 @@ public Value GetValue(TVariable var, ref MarkerProvider markerProvider) => } } + /// + /// Returns true if the given value is the null reference of ldnull: a null + /// pointer to void. Other null pointers, such as the handles of + /// non-capturing lambdas, stand for different targets and are kept apart. + /// + /// The value to test. + private static bool IsNullReference(Value value) => + value is NullValue { Type: PointerType { ElementType: VoidType } }; + + /// + /// Peeks the first reachable definition of the given variable that is not + /// the null reference of ldnull. Unlike , it searches all reachable definitions, as an IL stack slot can + /// hold ldnull on the first path to every predecessor, such as the first + /// operand of a ?? b while b is selected. Every block is + /// visited at most once. + /// + /// The variable reference. + /// The current marker to break cycles. + /// + /// Set to false if the search reached a block that has not been processed + /// yet or a block without predecessors that does not define the variable. + /// + /// + /// The definition, or null if all reachable definitions are null + /// references. + /// + private Value? PeekNonNullValue(TVariable var, int marker, ref bool complete) + { + var frames = Parent._peekFrames; + Block.Assert(frames.Count == 0); + try + { + ValueContainer? container = this; + while (container is not null) + { + // Visit the block once per marker + if (container.Mark(marker)) + { + if (!container.IsProcessed) + { + complete = false; + } + else if (container._values.TryGetValue(var, out Value? value)) + { + if (!IsNullReference(value)) + return value; + } + else + { + if (container.Block.Predecessors.Length == 0) + complete = false; + frames.Add((container, 0)); + } + } + + // Continue with the next predecessor of the innermost block + // that has not been searched yet + container = null; + while (frames.Count > 0 && container is null) + { + var (current, index) = frames[^1]; + var predecessors = current.Block.Predecessors; + if (index < predecessors.Length) + { + frames[^1] = (current, index + 1); + container = Parent[predecessors[index]]; + } + else + { + frames.RemoveAt(frames.Count - 1); + } + } + } + return null; + } + finally + { + frames.Clear(); + } + } + /// /// Returns the type of a new phi for the given variable: the type of the /// first value found in a predecessor. If that first value is a bool, the @@ -300,10 +382,34 @@ public Value GetValue(TVariable var, ref MarkerProvider markerProvider) => /// /// The variable reference. /// A provider of new marker values. + /// + /// The null reference of ldnull if all reachable definitions are null + /// references, such as for IL stack slots that hold ldnull on all paths. + /// /// The phi type. - private TypeValue GetPhiType(TVariable var, ref MarkerProvider markerProvider) + private TypeValue GetPhiType( + TVariable var, + ref MarkerProvider markerProvider, + out NullValue? nullValue) { - var type = PeekValue(var, markerProvider.CreateMarker()).AsNotNull().Type; + nullValue = null; + var first = PeekValue(var, markerProvider.CreateMarker()).AsNotNull(); + var type = first.Type; + if (IsNullReference(first)) + { + bool complete = true; + var value = PeekNonNullValue( + var, + markerProvider.CreateMarker(), + ref complete); + if (value?.Type is ArrayType arrayType) + return arrayType; + if (value is null && complete) + { + nullValue = (NullValue)first; + return type; + } + } if (type is PointerType) return GetPointerPhiType(var, type, ref markerProvider); if (type.BasicValueType != BasicValueType.Int1) @@ -413,8 +519,16 @@ private TypeValue GetPointerPhiType( return null; } + var phiType = GetPhiType(var, ref markerProvider, out var nullValue); + if (nullValue is not null && IsSealed) + { + // All definitions are null references: a phi of them would not + // be a null value that converts into a null array + SetValue(var, nullValue); + return nullValue; + } + // Insert the actual phi value - var phiType = GetPhiType(var, ref markerProvider); // Let the phi point to the beginning of the current block var phiBuilder = Builder.CreatePhi( Builder.BasicBlock.Location, @@ -521,6 +635,16 @@ private void AddPhiArgument( value, primitiveType).AsNotNull(); } + else if ( + phiBuilder.Type is ArrayType arrayType && + value is NullValue && + !value.Type.Equals(arrayType)) + { + // The null reference of ldnull becomes the null array + value = Parent[predecessor].Builder.CreateNull( + phiBuilder.PhiValue.Location, + arrayType); + } else if ( phiBuilder.Type is PointerType pointerType && value.Type is PointerType valueType && diff --git a/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs b/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs index b9fcfe1925..806784e3e4 100644 --- a/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs +++ b/Src/ILGPUC/ProgramOptions/Program.CompilationPropertiesOptions.cs @@ -73,6 +73,13 @@ internal sealed class CompilationPropertiesOptions DefaultValueFactory = static _ => FusedMultiplyAddMode.Fast }; + /// Keeps the thread storage of Metal kernels away from address 0. + readonly Option _metalNullSafeLocalsOption = new("--metal-null-safe-locals") + { + Description = "Keeps local arrays and the locals whose address is taken away from address 0 on Metal, where some devices place the first of them (true, the default) or not (false)", + DefaultValueFactory = static _ => true + }; + /// Forces floating-point math to flush denormal values to zero. readonly Option _mathFlushToZeroOption = new("--ftz") { @@ -145,6 +152,7 @@ public CompilationPropertiesOptions(Command command) command.Add(_staticFieldModeOption); command.Add(_arrayModeOption); command.Add(_constantEvaluationBudgetOption); + command.Add(_metalNullSafeLocalsOption); command.Add(_debugOption); command.Add(_releaseOption); @@ -172,6 +180,8 @@ public CompilationProperties GetProperties(ParseResult result) ArrayMode = result.GetValue(_arrayModeOption), ConstantEvaluationBudget = result.GetValue(_constantEvaluationBudgetOption), + EnableMetalNullSafeLocals = + result.GetValue(_metalNullSafeLocalsOption), }; if (result.GetValue(_debugOption))