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
1 change: 1 addition & 0 deletions Docs/03_Advanced/02_Kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ line in the form `File.cs(line,column): error ILGPU12xx: message`:
| `ILGPU1211` | Methods that call themselves, directly or through other methods, on the Metal and OpenCL backends |
| `ILGPU1212` | Kernels that call themselves, directly or through other methods |
| `ILGPU1213` | Calls of methods whose type arguments are nested more than 32 levels deep, such as a generic method `F<T>` calling `F<Wrap<T>>`, which would create new instantiations without end |
| `ILGPU1214` | Views, pointers and structures or arrays containing them loaded from static fields, including `static readonly` fields, whose values are read at compile time and do not refer to device memory; pass the view as a kernel parameter or capture it instead. Static fields of strings, classes and interfaces, and structures in static fields that hold arrays, strings or class instances, such as `struct H { public int V; public int[] A; }`, are rejected the same way, even if they hold null; pass the data in an `ArrayView` instead. A helper method that loads such a field is only an error if a call to it remains after optimization, such as a call on a path that constant arguments rule out |

Invoking a delegate variable that is still `null` on some path, without a null test, is undefined behavior in kernels.
To call an optional operation, pass a separate flag instead of testing the delegate for null.
Expand Down
27 changes: 27 additions & 0 deletions Src/ILGPU/Resources/ErrorMessages.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions Src/ILGPU/Resources/ErrorMessages.resx
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,18 @@
<value>Static field '{0}' holds a delegate, which kernels cannot load. Pass a lambda expression or a static method as an argument instead.</value>
<comment/>
</data>
<data name="KernelDiagnosticStaticManagedReferenceField" xml:space="preserve">
<value>Static field '{0}' of type '{1}' contains the field '{2}' of type '{3}', which holds a reference that kernels cannot load, even if it is null: arrays, strings and class instances inside a static value do not exist on the device. Pass the data to the kernel in an ArrayView instead, or keep only primitive, enum and structure fields in the value.</value>
<comment/>
</data>
<data name="KernelDiagnosticStaticMemoryReferenceField" xml:space="preserve">
<value>Static field '{0}' of type '{1}' holds a view or a pointer, which kernels cannot load: its value is read when the kernel is compiled and does not refer to memory of the device. Pass the view to the kernel as a parameter or capture it in an inline kernel instead.</value>
<comment/>
</data>
<data name="KernelDiagnosticStaticObjectField" xml:space="preserve">
<value>Static field '{0}' has the reference type '{1}', which kernels cannot load, even if the field is null: strings, class instances and other objects, such as Type objects, do not exist on the device. Pass the data to the kernel in an ArrayView or as a parameter instead, or keep it in a static field of a primitive, enum or structure type.</value>
<comment/>
</data>
<data name="KernelDiagnosticStructMethodGroup" xml:space="preserve">
<value>Delegate created from the instance method '{0}' of a struct value is not supported. Use a lambda expression that captures the value instead.</value>
<comment/>
Expand Down
215 changes: 197 additions & 18 deletions Src/ILGPUC.Tests/NonKernelTests/KernelDiagnosticTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using ILGPUC.IR;
using ILGPUC.Roslyn.Generation;
using ILGPUC.Tests.Framework;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using System;
using System.IO;
Expand All @@ -23,6 +24,7 @@
using System.Threading.Tasks;
using Xunit;
using RoslynLocation = Microsoft.CodeAnalysis.Location;
using RoslynOptimizationLevel = Microsoft.CodeAnalysis.OptimizationLevel;

namespace ILGPUC.Tests.NonKernelTests;

Expand Down Expand Up @@ -266,6 +268,16 @@ public static void DelegateStaticFieldKernel(
data[index] = StaticOperation(data[index]); // DelegateStaticField
}

private static readonly ArrayView<int> StaticView = default;

// A static readonly view compiled to a load from a null pointer
public static void StaticViewFieldKernel(
Index1D index,
ArrayView1D<int, Stride1D.Dense> data)
{
data[index] = StaticView[index]; // StaticViewField
}

private struct Adder
{
public int K;
Expand Down Expand Up @@ -459,7 +471,54 @@ private static void AssertDiagnostic(
private static async Task AssertBuildErrorAsync(
string kernelClass,
string id,
string message)
string message,
RoslynOptimizationLevel optimizationLevel = RoslynOptimizationLevel.Release)
{
var (source, compilation, analysis) = AnalyzeBuild(
kernelClass,
optimizationLevel);
var exception = await Assert.ThrowsAsync<KernelDiagnosticException>(() =>
MainKernelProvider.CreateAsync(
compilation,
analysis,
[CompilationHelper.CreateBackend(BackendType.CPU)],
new KernelCompiler()));
int line = Array.FindIndex(
source.Split('\n'),
l => l.TrimEnd().EndsWith("// error", StringComparison.Ordinal)) + 1;
Assert.True(line > 0, "Marker '// error' not found");
var diagnostic = exception.Diagnostic.ToString();
Assert.StartsWith($"source0.cs({line},", diagnostic, StringComparison.Ordinal);
Assert.Contains($"): error {id}: ", diagnostic, StringComparison.Ordinal);
Assert.Contains(message, diagnostic, StringComparison.Ordinal);
}

/// <summary>
/// Builds the given kernel class <c>K</c> like
/// <see cref="AssertBuildErrorAsync"/> and asserts that the build succeeds.
/// </summary>
private static async Task AssertBuildSucceedsAsync(
string kernelClass,
RoslynOptimizationLevel optimizationLevel)
{
var (_, compilation, analysis) = AnalyzeBuild(kernelClass, optimizationLevel);
await MainKernelProvider.CreateAsync(
compilation,
analysis,
[CompilationHelper.CreateBackend(BackendType.CPU)],
new KernelCompiler());
}

/// <summary>
/// Creates and analyzes the program launching <c>K.Kern</c> on four
/// elements.
/// </summary>
private static (
string Source,
CSharpCompilation Compilation,
AnalysisResult Analysis) AnalyzeBuild(
string kernelClass,
RoslynOptimizationLevel optimizationLevel)
{
var source = $$"""
using System;
Expand All @@ -485,24 +544,11 @@ static void Main()
""";
var compilation = RoslynCompiler.CreateCompilation(
[source],
"KernelDiagnosticTest");
"KernelDiagnosticTest",
optimizationLevel: optimizationLevel);
var analysis = CompilationRewriter.Analyze(compilation);
Assert.Empty(analysis.Diagnostics);

var exception = await Assert.ThrowsAsync<KernelDiagnosticException>(() =>
MainKernelProvider.CreateAsync(
compilation,
analysis,
[CompilationHelper.CreateBackend(BackendType.CPU)],
new KernelCompiler()));
int line = Array.FindIndex(
source.Split('\n'),
l => l.TrimEnd().EndsWith("// error", StringComparison.Ordinal)) + 1;
Assert.True(line > 0, "Marker '// error' not found");
var diagnostic = exception.Diagnostic.ToString();
Assert.StartsWith($"source0.cs({line},", diagnostic, StringComparison.Ordinal);
Assert.Contains($"): error {id}: ", diagnostic, StringComparison.Ordinal);
Assert.Contains(message, diagnostic, StringComparison.Ordinal);
return (source, compilation, analysis);
}

/// <summary>
Expand Down Expand Up @@ -878,7 +924,7 @@ public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d)

#endregion

#region Delegate Storage and Other Frontend Diagnostics (ILGPU1205-1209, 1200)
#region Delegate Storage and Other Frontend Diagnostics (ILGPU1205-1209, 1214, 1200)

[Fact]
public void ClosureCapturesDelegate_Reports1205() =>
Expand Down Expand Up @@ -958,6 +1004,139 @@ public void DelegateRecursion_Reports1209() =>
"Method 'SumOver' calls itself while passing delegates",
"DelegateRecursion");

[Fact]
public void StaticViewField_Reports1214() =>
AssertDiagnostic(
Compile(nameof(Kernels.StaticViewFieldKernel)),
"ILGPU1214",
"Static field 'Kernels.StaticView' of type 'ArrayView<int>' holds a " +
"view or a pointer, which kernels cannot load",
"StaticViewField");

// A static readonly view compiled to a load from a null pointer
[Fact]
public Task StaticViewField_FailsBuild() =>
AssertBuildErrorAsync(
"""
static class K
{
static readonly ArrayView1D<int, Stride1D.Dense> Table;
public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d) =>
d[i] = Table[i]; // error
}
""",
"ILGPU1214",
"Static field 'K.Table' of type 'ArrayView1D<int, Dense>' holds a " +
"view or a pointer, which kernels cannot load");

// An internal compiler error while inlining the array in the structure
[Fact]
public Task StaticArrayHolder_FailsBuild() =>
AssertBuildErrorAsync(
"""
struct H { public int V; public int[] A; }
static class K
{
static readonly H Holder = new() { V = 1, A = [1, 2] };
public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d) =>
d[i] = Holder.V; // error
}
""",
"ILGPU1214",
"Static field 'K.Holder' of type 'H' contains the field 'H.A' of type " +
"'int[]', which holds a reference that kernels cannot load, even if it " +
"is null");

// An unnamed error that the class type String is not supported
[Theory]
[InlineData(RoslynOptimizationLevel.Debug)]
[InlineData(RoslynOptimizationLevel.Release)]
public Task StaticString_FailsBuild(RoslynOptimizationLevel optimizationLevel) =>
AssertBuildErrorAsync(
"""
static class K
{
static readonly string Name = "abc";
public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d) =>
d[i] = Name.Length; // error
}
""",
"ILGPU1214",
"Static field 'K.Name' has the reference type 'string', which " +
"kernels cannot load, even if the field is null",
optimizationLevel);

// A call to a getter that could not be compiled, since the class type C
// is not supported. The error points at the call, as the location of the
// generated getter is the declaration of the property.
[Theory]
[InlineData(RoslynOptimizationLevel.Debug)]
[InlineData(RoslynOptimizationLevel.Release)]
public Task StaticClassProperty_FailsBuild(
RoslynOptimizationLevel optimizationLevel) =>
AssertBuildErrorAsync(
"""
sealed class C { public int V = 2; }
static class K
{
static C Box { get; } = new();
public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d) =>
d[i] = Box.V; // error
}
""",
"ILGPU1214",
"Static field 'K.Box' has the reference type 'C', which kernels " +
"cannot load, even if the field is null",
optimizationLevel);

// Failed with ILGPU1214 although optimization removes the calls to Fail and
// Bad, as it removes calls to helpers failing with other errors. Only the IR
// optimizer folds the tuple elements, not the constant evaluator of the
// frontend, so the helpers are generated.
[Theory]
[InlineData(RoslynOptimizationLevel.Debug)]
[InlineData(RoslynOptimizationLevel.Release)]
public Task StaticStringInRemovedHelper_Compiles(
RoslynOptimizationLevel optimizationLevel) =>
AssertBuildSucceedsAsync(
"""
sealed class C { public int V = 2; }
static class K
{
static readonly string Name = "abc";
static readonly C Box = new();
static int Fail() => throw new InvalidOperationException(Name);
static int CheckedArg(int m) => m >= 0 ? m : Fail();
static int Bad() => Name.Length + Box.V;
static int Pick(int m) => m == 0 ? 1 : Bad();
public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d) =>
d[i] = CheckedArg((((int a, int b))(5, i.X)).a) +
Pick((((int a, int b))(0, i.X)).a);
}
""",
optimizationLevel);

[Theory]
[InlineData(RoslynOptimizationLevel.Debug)]
[InlineData(RoslynOptimizationLevel.Release)]
public Task StaticStringInSurvivingHelper_FailsBuild(
RoslynOptimizationLevel optimizationLevel) =>
AssertBuildErrorAsync(
"""
static class K
{
static readonly string Name = "abc";
static int Bad() => Name.Length; // error
static int Pick(int m) => m == 0 ? 1 : Bad();
public static void Kern(Index1D i, ArrayView1D<int, Stride1D.Dense> d) =>
d[i] = Pick(i);
}
""",
"ILGPU1214",
"Static field 'K.Name' has the reference type 'string', which " +
"kernels cannot load, even if the field is null",
optimizationLevel);

[Fact]
public void Expression_ReportsUnsupportedConstruct()
{
Expand Down
41 changes: 34 additions & 7 deletions Src/ILGPUC.Tests/NonKernelTests/RecursiveTypeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,19 @@ private static void AssertRecursiveType(
Assert.Equal(
"Kernel code uses an unsupported construct: " + message,
diagnostic.Message);
AssertLocation(exception.SourceLocation, marker, sourcePath);
}

var location = Assert.IsAssignableFrom<FileLocation>(exception.SourceLocation);
/// <summary>
/// Asserts that the given location is the line of the given source file
/// marked with the given comment.
/// </summary>
private static void AssertLocation(
Location? sourceLocation,
string marker,
string sourcePath)
{
var location = Assert.IsAssignableFrom<FileLocation>(sourceLocation);
Assert.Equal(
Path.GetFileName(sourcePath),
Path.GetFileName(location.FileName));
Expand All @@ -389,13 +400,29 @@ private static void AssertRecursiveType(
Assert.Equal(line, location.StartLine);
}

/// <summary>
/// A static field holding a structure with an array of itself is rejected
/// for the array it holds before the recursive type is created.
/// </summary>
[Fact]
public void StaticTree_ReportsRecursiveType() =>
AssertRecursiveType(
nameof(Kernels.StaticTreeKernel),
"Recursive type 'TreeNode' is not supported in GPU kernels: " +
"it refers to itself through 'TreeNode.Children'.",
"StaticTree");
public void StaticTree_ReportsHeldArray()
{
using var helper = new CompilationHelper(BackendType.CPU);
var kernel = typeof(Kernels).GetMethod(nameof(Kernels.StaticTreeKernel))!;
var exception = Assert.Throws<KernelCompilationException>(() =>
helper.GetNormalizedIR(kernel, IRDumpPoint.AfterBackendTransforms));
Assert.Equal("ILGPU1214", exception.Id);
Assert.Contains(
"Static field 'Kernels.Tree' of type 'TreeNode' contains the field " +
"'TreeNode.Children' of type 'TreeNode[]', which holds a reference that " +
"kernels cannot load",
exception.Message,
StringComparison.Ordinal);
AssertLocation(exception.Location, "StaticTree", GetSourcePath());
}

private static string GetSourcePath([CallerFilePath] string sourcePath = "") =>
sourcePath;

[Fact]
public void CapturedClass_ReportsRecursiveType() =>
Expand Down
Loading
Loading