Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Docs/03_Advanced/02_Kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>()` 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)
Expand All @@ -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
<PropertyGroup>
<ILGPUCompilationOptions>--metal-null-safe-locals false</ILGPUCompilationOptions>
</PropertyGroup>
```

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<int, int>`) whose target is known at compile time.
Expand Down
10 changes: 9 additions & 1 deletion Src/ILGPU/Runtime/Metal/MetalCompiledKernel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -81,6 +82,13 @@ public class MetalCompiledKernel(
/// </summary>
public bool FastMath { get; } = fastMath;

/// <summary>
/// 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.
/// </summary>
public bool NullSafeLocals { get; } = nullSafeLocals;

/// <inheritdoc/>
public override AcceleratorCapabilities RequiredCapabilities =>
MetalAcceleratorCapabilities.FromGPUFamily(GPUFamily);
Expand Down
29 changes: 29 additions & 0 deletions Src/ILGPU/Runtime/Metal/MetalKernel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -73,6 +79,29 @@ internal MetalKernel(
PipelineState = pipelineState;
}

/// <summary>
/// The name of the virtual Metal device of macOS virtual machines, which
/// places the first thread-private object of a kernel at address 0.
/// </summary>
private const string ParavirtualDeviceName = "Apple Paravirtual device";

/// <summary>
/// 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.
/// </summary>
/// <param name="compiledKernel">The compiled kernel to load.</param>
/// <param name="deviceName">The name of the Metal device.</param>
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;

/// <summary>
/// Loads a Metal library from binary data or source code.
/// </summary>
Expand Down
140 changes: 138 additions & 2 deletions Src/ILGPUC.Tests/BackendTests/MetalSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -23,8 +25,9 @@ namespace ILGPUC.Tests.BackendTests;

/// <summary>
/// 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.
/// </summary>
public sealed class MetalSourceTests
{
Expand Down Expand Up @@ -166,6 +169,139 @@ public async Task MathMode_SelectsCompileOptions(
Assert.Equal(fastMath, wrapper.Contains("fastMath: true"));
}

/// <summary>
/// Holds four integers in thread memory.
/// </summary>
internal unsafe struct LocalBuffer
{
public fixed int Data[4];
}

/// <summary>
/// Stores into a local array and into a fixed buffer of a local.
/// </summary>
internal static unsafe void LocalStorageKernel(
Index1D index,
ArrayView1D<int, Stride1D.Dense> 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)!;

/// <summary>
/// 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.
/// </summary>
[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"));
}

/// <summary>
/// Null-safe locals are the default of the compilation properties and of the
/// command line, which turns them off with false.
/// </summary>
[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);
}

/// <summary>
/// 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.
/// </summary>
[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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
71 changes: 71 additions & 0 deletions Src/ILGPUC.Tests/ExecutionTests/ArrayExecutionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using RoslynOptimizationLevel = Microsoft.CodeAnalysis.OptimizationLevel;

namespace ILGPUC.Tests.ExecutionTests;

Expand All @@ -39,4 +40,74 @@ await VerifyProgramOutputAsync(
["Kernels.ArrayBoundsKernel"],
["0", "1", "-1", "-1"]);
}

/// <summary>
/// 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.
/// </summary>
[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);
}

/// <summary>
/// Null arrays on the IL stack across branches, such as <c>a ?? b</c> 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.
/// </summary>
[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);
}
}
14 changes: 14 additions & 0 deletions Src/ILGPUC.Tests/ExecutionTests/LocalArrayExecutionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ await VerifyProgramOutputAsync(
["10", "20", "30", "40"]);
}

/// <summary>
/// Kernels whose thread storage may start at address 0 still run, on Metal
/// through a compiled kernel that tells the runtime.
/// </summary>
[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()
{
Expand Down
Loading
Loading