diff --git a/LICENSE-3RD-PARTY.txt b/LICENSE-3RD-PARTY.txt
index 2323141ca..03d07731b 100644
--- a/LICENSE-3RD-PARTY.txt
+++ b/LICENSE-3RD-PARTY.txt
@@ -9,6 +9,8 @@ ILGPU Dependencies:
(https://www.nuget.org/packages/System.Reflection.Metadata)
- System.Runtime.CompilerServices.Unsafe
(https://www.nuget.org/packages/system.runtime.CompilerServices.Unsafe/)
+ - .NET Runtime
+ (https://github.com/dotnet/runtime/)
********************************************************************************
********************************************************************************
@@ -38,3 +40,11 @@ http://go.microsoft.com/fwlink/?LinkId=329770
System.Runtime.CompilerServices.Unsafe license can be found via:
http://go.microsoft.com/fwlink/?LinkId=329770
+
+********************************************************************************
+ ILGPU Compiler Dependency: .NET Runtime
+
+For compatibility with older frameworks, parts of ILGPU makes use of source
+code for Nullable Attributes from the .NET runtime. This code is licensed
+under the MIT license, and can be found via:
+https://raw.githubusercontent.com/dotnet/runtime/v7.0.0/LICENSE.TXT
diff --git a/Src/Directory.Build.props b/Src/Directory.Build.props
index 9f2832a31..b319281b3 100644
--- a/Src/Directory.Build.props
+++ b/Src/Directory.Build.props
@@ -2,6 +2,7 @@
net7.0
+ $(LibraryTargetFrameworks)
$(LibraryTargetFrameworks);net471;netstandard2.1;net5.0;net6.0
@@ -18,6 +19,7 @@
net7.0
+ $(LibraryUnitTestTargetFrameworks)
$(LibraryUnitTestTargetFrameworks);net471;netcoreapp3.1;net5.0;net6.0
diff --git a/Src/ILGPU.Algorithms.Tests/Generic/AlgorithmsTestData.tt b/Src/ILGPU.Algorithms.Tests/Generic/AlgorithmsTestData.tt
index dcc6fcbf0..0f9129dcf 100644
--- a/Src/ILGPU.Algorithms.Tests/Generic/AlgorithmsTestData.tt
+++ b/Src/ILGPU.Algorithms.Tests/Generic/AlgorithmsTestData.tt
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: AlgorithmsTestData.tt/AlgorithmsTestData.cs
@@ -16,6 +16,7 @@
using ILGPU.Algorithms.RadixSortOperations;
using ILGPU.Algorithms.ScanReduceOperations;
+using ILGPU.Util;
using System.Numerics;
using System.Runtime.CompilerServices;
using Xunit.Abstractions;
@@ -30,7 +31,10 @@ namespace ILGPU.Algorithms.Tests
public class AlgorithmsTestData : IXunitSerializable
{
- public AlgorithmsTestData() { }
+ public AlgorithmsTestData()
+ {
+ Value = Utilities.InitNotNullable();
+ }
public AlgorithmsTestData(T value)
{
@@ -48,7 +52,7 @@ namespace ILGPU.Algorithms.Tests
info.AddValue(nameof(Value), Value);
}
- public override string ToString() => Value.ToString();
+ public override string ToString() => $"{Value}";
}
#region Xunit Sequencer Structures
diff --git a/Src/ILGPU.Algorithms.Tests/ILGPU.Algorithms.Tests.csproj b/Src/ILGPU.Algorithms.Tests/ILGPU.Algorithms.Tests.csproj
index 71621a973..c2ad09328 100644
--- a/Src/ILGPU.Algorithms.Tests/ILGPU.Algorithms.Tests.csproj
+++ b/Src/ILGPU.Algorithms.Tests/ILGPU.Algorithms.Tests.csproj
@@ -6,6 +6,14 @@
latest
+
+
+ enable
+
+
+ $(NoWarn);nullable
+
+
$(MSBuildProjectDirectory)\..\ILGPU.Tests\.test.runsettings
diff --git a/Src/ILGPU.Algorithms/CL/CLContext.cs b/Src/ILGPU.Algorithms/CL/CLContext.cs
index eb03072ee..5f9c7222a 100644
--- a/Src/ILGPU.Algorithms/CL/CLContext.cs
+++ b/Src/ILGPU.Algorithms/CL/CLContext.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLContext.cs
@@ -40,7 +40,8 @@ static partial class CLContext
private static readonly MethodInfo MathCodeGenerator =
CLMathType.GetMethod(
nameof(CLMath.GenerateMathIntrinsic),
- AlgorithmContext.IntrinsicBindingFlags);
+ AlgorithmContext.IntrinsicBindingFlags)
+ .ThrowIfNull();
///
/// Represents the intrinsic representation of the
@@ -49,7 +50,8 @@ static partial class CLContext
private static readonly CLIntrinsic MathCodeGeneratorIntrinsic =
new CLIntrinsic(
MathCodeGenerator,
- IntrinsicImplementationMode.GenerateCode);
+ IntrinsicImplementationMode.GenerateCode)
+ .ThrowIfNull();
///
/// The type.
@@ -74,7 +76,8 @@ private static CLIntrinsic GetMathIntrinsic(string name, params Type[] types)
AlgorithmContext.IntrinsicBindingFlags,
null,
types,
- null);
+ null)
+ .ThrowIfNull();
return new CLIntrinsic(targetMethod, IntrinsicImplementationMode.Redirect);
}
@@ -93,7 +96,8 @@ private static void RegisterIntrinsicMapping(
{
var sourceMethod = sourceType.GetMethod(
name,
- AlgorithmContext.IntrinsicBindingFlags);
+ AlgorithmContext.IntrinsicBindingFlags)
+ .ThrowIfNull();
manager.RegisterMethod(
sourceMethod,
new CLIntrinsic(targetType, name, IntrinsicImplementationMode.Redirect));
@@ -118,7 +122,8 @@ private static void RegisterIntrinsicCodeGenerator(
{
var sourceMethod = sourceType.GetMethod(
name,
- AlgorithmContext.IntrinsicBindingFlags);
+ AlgorithmContext.IntrinsicBindingFlags)
+ .ThrowIfNull();
manager.RegisterMethod(
sourceMethod,
new CLIntrinsic(
@@ -150,7 +155,8 @@ private static void RegisterXMathCodeGenerator(
AlgorithmContext.IntrinsicBindingFlags,
null,
types,
- null),
+ null)
+ .ThrowIfNull(),
new CLIntrinsic(
targetType,
codeGeneratorName,
@@ -176,7 +182,7 @@ internal static void GenerateScanReduce(
where TScanReduce : struct, IScanReduceOperation
{
// Allocate target and load source argument
- var reduce = value as MethodCall;
+ var reduce = value.AsNotNullCast();
var sourceValue = codeGenerator.Load(reduce[0]);
var target = codeGenerator.Allocate(value);
diff --git a/Src/ILGPU.Algorithms/CL/CLMath.cs b/Src/ILGPU.Algorithms/CL/CLMath.cs
index 75d45723c..de2acbe53 100644
--- a/Src/ILGPU.Algorithms/CL/CLMath.cs
+++ b/Src/ILGPU.Algorithms/CL/CLMath.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLMath.cs
@@ -35,7 +35,7 @@ public static void GenerateMathIntrinsic(
Value value)
{
// Manually generate code for "1.0 / argument"
- var arithmeticValue = value as UnaryArithmeticValue;
+ var arithmeticValue = value.AsNotNullCast();
var argument = codeGenerator.Load(arithmeticValue.Value);
var target = codeGenerator.Allocate(arithmeticValue);
var operation = CLInstructions.GetArithmeticOperation(
diff --git a/Src/ILGPU.Algorithms/ConcurrentStreamProcessor.cs b/Src/ILGPU.Algorithms/ConcurrentStreamProcessor.cs
index f3c67fe57..ffcc6eab4 100644
--- a/Src/ILGPU.Algorithms/ConcurrentStreamProcessor.cs
+++ b/Src/ILGPU.Algorithms/ConcurrentStreamProcessor.cs
@@ -38,7 +38,7 @@ public class ConcurrentStreamProcessor : DisposeBase
public ConcurrentStreamProcessor(
Accelerator accelerator,
int maxNumConcurrentStreams = 0,
- Func streamProvider = null)
+ Func? streamProvider = null)
{
maxNumConcurrentStreams = Math.Max(
Math.Max(maxNumConcurrentStreams, 1),
@@ -93,7 +93,7 @@ public void ProcessConcurrently(
/// The action to invoke on each stream to submit work.
///
public void ProcessConcurrently(
- AcceleratorStream stream,
+ AcceleratorStream? stream,
int numActions,
Action action)
{
diff --git a/Src/ILGPU.Algorithms/HistogramExtensions.cs b/Src/ILGPU.Algorithms/HistogramExtensions.cs
index ca494654c..669030d0d 100644
--- a/Src/ILGPU.Algorithms/HistogramExtensions.cs
+++ b/Src/ILGPU.Algorithms/HistogramExtensions.cs
@@ -12,6 +12,7 @@
using ILGPU.Algorithms.HistogramOperations;
using ILGPU.Algorithms.Resources;
using ILGPU.Runtime;
+using ILGPU.Util;
using System;
using System.Reflection;
@@ -145,12 +146,14 @@ private delegate void HistogramUncheckedDelegate<
private static readonly MethodInfo HistogramKernelMethod =
typeof(HistogramExtensions).GetMethod(
nameof(HistogramKernel),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
private static readonly MethodInfo HistogramUncheckedKernelMethod =
typeof(HistogramExtensions).GetMethod(
nameof(HistogramUncheckedKernel),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
///
/// The actual histogram kernel implementation.
diff --git a/Src/ILGPU.Algorithms/IL/ILContext.cs b/Src/ILGPU.Algorithms/IL/ILContext.cs
index 5be5c274d..a3532ba7d 100644
--- a/Src/ILGPU.Algorithms/IL/ILContext.cs
+++ b/Src/ILGPU.Algorithms/IL/ILContext.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: ILContext.cs
@@ -12,6 +12,7 @@
using ILGPU.Backends;
using ILGPU.Backends.IL;
using ILGPU.IR.Intrinsics;
+using ILGPU.Util;
using System;
namespace ILGPU.Algorithms.IL
@@ -63,7 +64,8 @@ private static void RegisterIntrinsicMapping(
{
var sourceMethod = sourceType.GetMethod(
name,
- AlgorithmContext.IntrinsicBindingFlags);
+ AlgorithmContext.IntrinsicBindingFlags)
+ .ThrowIfNull();
manager.RegisterMethod(
sourceMethod,
new ILIntrinsic(targetType, name, IntrinsicImplementationMode.Redirect));
diff --git a/Src/ILGPU.Algorithms/ILGPU.Algorithms.csproj b/Src/ILGPU.Algorithms/ILGPU.Algorithms.csproj
index 20d86661e..a312c8fd6 100644
--- a/Src/ILGPU.Algorithms/ILGPU.Algorithms.csproj
+++ b/Src/ILGPU.Algorithms/ILGPU.Algorithms.csproj
@@ -10,6 +10,14 @@
$(LibraryFileVersion)
+
+
+ enable
+
+
+ $(NoWarn);nullable
+
+
true
en-US
@@ -23,6 +31,10 @@
Debug;Release
+
+
+
+
True
diff --git a/Src/ILGPU.Algorithms/MatrixOperations/MaskedMatrixProcessor.cs b/Src/ILGPU.Algorithms/MatrixOperations/MaskedMatrixProcessor.cs
index 0ecb86e9f..8e072743e 100644
--- a/Src/ILGPU.Algorithms/MatrixOperations/MaskedMatrixProcessor.cs
+++ b/Src/ILGPU.Algorithms/MatrixOperations/MaskedMatrixProcessor.cs
@@ -48,7 +48,7 @@ private readonly MaskedSparseMatrixMultiplier
public MaskedMatrixProcessor(
Accelerator accelerator,
int maxNumConcurrentStreams = 0,
- Func streamProvider = null)
+ Func? streamProvider = null)
: base(accelerator, maxNumConcurrentStreams, streamProvider)
{
matrixMultiplier = accelerator.CreateSparseTransposedMatrixMultiplierMasked<
diff --git a/Src/ILGPU.Algorithms/PTX/PTXContext.cs b/Src/ILGPU.Algorithms/PTX/PTXContext.cs
index 98e869ac2..61a268508 100644
--- a/Src/ILGPU.Algorithms/PTX/PTXContext.cs
+++ b/Src/ILGPU.Algorithms/PTX/PTXContext.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXContext.cs
@@ -12,6 +12,7 @@
using ILGPU.Backends.PTX;
using ILGPU.IR.Intrinsics;
using ILGPU.Runtime.Cuda;
+using ILGPU.Util;
using System;
using System.Reflection;
@@ -35,7 +36,8 @@ static partial class PTXContext
private static readonly MethodInfo MathCodeGenerator =
PTXMathType.GetMethod(
nameof(PTXMath.GenerateMathIntrinsic),
- AlgorithmContext.IntrinsicBindingFlags);
+ AlgorithmContext.IntrinsicBindingFlags)
+ .ThrowIfNull();
///
/// Represents the intrinsic representation of the
@@ -44,7 +46,8 @@ static partial class PTXContext
private static readonly PTXIntrinsic MathCodeGeneratorIntrinsic =
new PTXIntrinsic(
MathCodeGenerator,
- IntrinsicImplementationMode.GenerateCode);
+ IntrinsicImplementationMode.GenerateCode)
+ .ThrowIfNull();
///
/// The type.
@@ -82,7 +85,8 @@ private static PTXIntrinsic GetMathIntrinsic(string name, params Type[] types)
AlgorithmContext.IntrinsicBindingFlags,
null,
types,
- null);
+ null)
+ .ThrowIfNull();
return new PTXIntrinsic(targetMethod, IntrinsicImplementationMode.Redirect);
}
@@ -101,7 +105,8 @@ private static void RegisterIntrinsicMapping(
{
var sourceMethod = sourceType.GetMethod(
name,
- AlgorithmContext.IntrinsicBindingFlags);
+ AlgorithmContext.IntrinsicBindingFlags)
+ .ThrowIfNull();
manager.RegisterMethod(
sourceMethod,
new PTXIntrinsic(targetType, name, IntrinsicImplementationMode.Redirect));
@@ -130,14 +135,16 @@ private static void RegisterXMathRedirect(
AlgorithmContext.IntrinsicBindingFlags,
null,
types,
- null),
+ null)
+ .ThrowIfNull(),
new PTXIntrinsic(
targetType.GetMethod(
replacementName,
AlgorithmContext.IntrinsicBindingFlags,
null,
types,
- null),
+ null)
+ .ThrowIfNull(),
IntrinsicImplementationMode.Redirect));
}
}
diff --git a/Src/ILGPU.Algorithms/PTX/PTXMath.cs b/Src/ILGPU.Algorithms/PTX/PTXMath.cs
index 487231f8c..3c55fc7b2 100644
--- a/Src/ILGPU.Algorithms/PTX/PTXMath.cs
+++ b/Src/ILGPU.Algorithms/PTX/PTXMath.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXMath.cs
@@ -39,7 +39,7 @@ public static void GenerateMathIntrinsic(
PTXCodeGenerator codeGenerator,
Value value)
{
- var arithmeticValue = value as UnaryArithmeticValue;
+ var arithmeticValue = value.AsNotNullCast();
var instruction = PTXInstructions.GetArithmeticOperation(
arithmeticValue.Kind,
arithmeticValue.ArithmeticBasicValueType,
diff --git a/Src/ILGPU.Algorithms/PTX/PTXWarpExtensions.cs b/Src/ILGPU.Algorithms/PTX/PTXWarpExtensions.cs
index 58d30361f..5f88d8045 100644
--- a/Src/ILGPU.Algorithms/PTX/PTXWarpExtensions.cs
+++ b/Src/ILGPU.Algorithms/PTX/PTXWarpExtensions.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXWarpExtensions.cs
@@ -25,7 +25,7 @@ static class PTXWarpExtensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Reduce(T value)
where T : unmanaged
- where TReduction : IScanReduceOperation
+ where TReduction : struct, IScanReduceOperation
{
TReduction reduction = default;
for (int laneOffset = Warp.WarpSize / 2; laneOffset > 0; laneOffset >>= 1)
@@ -40,7 +40,7 @@ public static T Reduce(T value)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T AllReduce(T value)
where T : unmanaged
- where TReduction : IScanReduceOperation
+ where TReduction : struct, IScanReduceOperation
{
TReduction reduction = default;
for (int laneMask = Warp.WarpSize / 2; laneMask > 0; laneMask >>= 1)
diff --git a/Src/ILGPU.Algorithms/RadixSortExtensions.cs b/Src/ILGPU.Algorithms/RadixSortExtensions.cs
index 9d2d03dc1..7669b07ad 100644
--- a/Src/ILGPU.Algorithms/RadixSortExtensions.cs
+++ b/Src/ILGPU.Algorithms/RadixSortExtensions.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2019-2022 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: RadixSortExtensions.cs
@@ -541,22 +541,26 @@ public readonly int ExtractRadixBits(
private static readonly MethodInfo CPURadixSortKernel1Method =
typeof(RadixSortExtensions).GetMethod(
nameof(CPURadixSortKernel1),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
private static readonly MethodInfo CPURadixSortKernel2Method =
typeof(RadixSortExtensions).GetMethod(
nameof(CPURadixSortKernel2),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
private static readonly MethodInfo RadixSortKernel1Method =
typeof(RadixSortExtensions).GetMethod(
nameof(RadixSortKernel1),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
private static readonly MethodInfo RadixSortKernel2Method =
typeof(RadixSortExtensions).GetMethod(
nameof(RadixSortKernel2),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
///
/// Represents a single specialization.
diff --git a/Src/ILGPU.Algorithms/Random/XorShift128.cs b/Src/ILGPU.Algorithms/Random/XorShift128.cs
index 9d1a6b7c7..71e1a7c03 100644
--- a/Src/ILGPU.Algorithms/Random/XorShift128.cs
+++ b/Src/ILGPU.Algorithms/Random/XorShift128.cs
@@ -193,7 +193,7 @@ public readonly override int GetHashCode() =>
///
/// The other rng to test.
/// True, if the given object is equal to the current rng.
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is XorShift128 shift && Equals(shift);
///
diff --git a/Src/ILGPU.Algorithms/Random/XorShift128Plus.cs b/Src/ILGPU.Algorithms/Random/XorShift128Plus.cs
index bcd14a6e4..89ecb7106 100644
--- a/Src/ILGPU.Algorithms/Random/XorShift128Plus.cs
+++ b/Src/ILGPU.Algorithms/Random/XorShift128Plus.cs
@@ -173,7 +173,7 @@ public readonly XorShift128Plus CreateProvider(
///
/// The other rng to test.
/// True, if the given object is equal to the current rng.
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is XorShift128Plus shift && Equals(shift);
///
diff --git a/Src/ILGPU.Algorithms/Random/XorShift32.cs b/Src/ILGPU.Algorithms/Random/XorShift32.cs
index 6f6cad70b..72730de71 100644
--- a/Src/ILGPU.Algorithms/Random/XorShift32.cs
+++ b/Src/ILGPU.Algorithms/Random/XorShift32.cs
@@ -143,7 +143,7 @@ public readonly XorShift32 CreateProvider(ref TProvider random)
///
/// The other rng to test.
/// True, if the given object is equal to the current rng.
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is XorShift32 shift && Equals(shift);
///
diff --git a/Src/ILGPU.Algorithms/Random/XorShift64Star.cs b/Src/ILGPU.Algorithms/Random/XorShift64Star.cs
index 211036b67..d1df63694 100644
--- a/Src/ILGPU.Algorithms/Random/XorShift64Star.cs
+++ b/Src/ILGPU.Algorithms/Random/XorShift64Star.cs
@@ -147,7 +147,7 @@ public readonly XorShift64Star CreateProvider(
///
/// The other rng to test.
/// True, if the given object is equal to the current rng.
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is XorShift64Star shift && Equals(shift);
///
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuBlasAPI.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuBlasAPI.cs
index 2cf438ff7..bb7c6b756 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuBlasAPI.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuBlasAPI.cs
@@ -28,6 +28,7 @@ internal abstract unsafe partial class CuBlasAPI
public static CuBlasAPI Create(CuBlasAPIVersion? version) =>
version.HasValue
? CreateInternal(version.Value)
+ ?? throw new DllNotFoundException(nameof(CuBlasAPI))
: CreateLatest();
///
@@ -36,12 +37,15 @@ public static CuBlasAPI Create(CuBlasAPIVersion? version) =>
/// The created API wrapper.
private static CuBlasAPI CreateLatest()
{
- Exception firstException = null;
- var versions = Enum.GetValues(typeof(CuBlasAPIVersion));
-
+ Exception? firstException = null;
+#if NET5_0_OR_GREATER
+ var versions = Enum.GetValues();
+#else
+ var versions = (CuBlasAPIVersion[])Enum.GetValues(typeof(CuBlasAPIVersion));
+#endif
for (var i = versions.Length - 1; i >= 0; i--)
{
- var version = (CuBlasAPIVersion)versions.GetValue(i);
+ var version = versions[i];
var api = CreateInternal(version);
if (api is null)
continue;
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTAPI.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTAPI.cs
index e9e1da9fd..dd6a6e176 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTAPI.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTAPI.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: CuFFTAPI.cs
@@ -31,6 +31,7 @@ public abstract partial class CuFFTAPI
public static CuFFTAPI Create(CuFFTAPIVersion? version) =>
version.HasValue
? CreateInternal(version.Value)
+ ?? throw new DllNotFoundException(nameof(CuFFTAPI))
: CreateLatest();
///
@@ -39,12 +40,15 @@ public static CuFFTAPI Create(CuFFTAPIVersion? version) =>
/// The created API wrapper.
private static CuFFTAPI CreateLatest()
{
- Exception firstException = null;
- var versions = Enum.GetValues(typeof(CuFFTAPIVersion));
-
+ Exception? firstException = null;
+#if NET5_0_OR_GREATER
+ var versions = Enum.GetValues();
+#else
+ var versions = (CuFFTAPIVersion[])Enum.GetValues(typeof(CuFFTAPIVersion));
+#endif
for (var i = versions.Length - 1; i >= 0; i--)
{
- var version = (CuFFTAPIVersion)versions.GetValue(i);
+ var version = versions[i];
var api = CreateInternal(version);
if (api is null)
continue;
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTWAPI.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTWAPI.cs
index 8a47023f5..a61d03323 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTWAPI.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuFFTWAPI.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: CuFFTWAPI.cs
@@ -29,6 +29,7 @@ public abstract partial class CuFFTWAPI
public static CuFFTWAPI Create(CuFFTWAPIVersion? version) =>
version.HasValue
? CreateInternal(version.Value)
+ ?? throw new DllNotFoundException(nameof(CuFFTWAPI))
: CreateLatest();
///
@@ -37,12 +38,15 @@ public static CuFFTWAPI Create(CuFFTWAPIVersion? version) =>
/// The created API wrapper.
private static CuFFTWAPI CreateLatest()
{
- Exception firstException = null;
- var versions = Enum.GetValues(typeof(CuFFTWAPIVersion));
-
+ Exception? firstException = null;
+#if NET5_0_OR_GREATER
+ var versions = Enum.GetValues();
+#else
+ var versions = (CuFFTWAPIVersion[])Enum.GetValues(typeof(CuFFTWAPIVersion));
+#endif
for (var i = versions.Length - 1; i >= 0; i--)
{
- var version = (CuFFTWAPIVersion)versions.GetValue(i);
+ var version = versions[i];
var api = CreateInternal(version);
if (api is null)
continue;
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuRandAPI.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuRandAPI.cs
index 83f04fec3..372d15e8d 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuRandAPI.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/API/CuRandAPI.cs
@@ -28,6 +28,7 @@ public abstract partial class CuRandAPI
public static CuRandAPI Create(CuRandAPIVersion? version) =>
version.HasValue
? CreateInternal(version.Value)
+ ?? throw new DllNotFoundException(nameof(CuRandAPI))
: CreateLatest();
///
@@ -36,12 +37,15 @@ public static CuRandAPI Create(CuRandAPIVersion? version) =>
/// The created API wrapper.
private static CuRandAPI CreateLatest()
{
- Exception firstException = null;
- var versions = Enum.GetValues(typeof(CuRandAPIVersion));
-
+ Exception? firstException = null;
+#if NET5_0_OR_GREATER
+ var versions = Enum.GetValues();
+#else
+ var versions = (CuRandAPIVersion[])Enum.GetValues(typeof(CuRandAPIVersion));
+#endif
for (var i = versions.Length - 1; i >= 0; i--)
{
- var version = (CuRandAPIVersion)versions.GetValue(i);
+ var version = versions[i];
var api = CreateInternal(version);
if (api != null)
{
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvJpegAPI.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvJpegAPI.cs
index d6c3c74b7..58548450b 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvJpegAPI.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvJpegAPI.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: NvJpegAPI.cs
@@ -29,6 +29,7 @@ public abstract partial class NvJpegAPI
public static NvJpegAPI Create(NvJpegAPIVersion? version) =>
version.HasValue
? CreateInternal(version.Value)
+ ?? throw new DllNotFoundException(nameof(NvJpegAPI))
: CreateLatest();
///
@@ -37,12 +38,15 @@ public static NvJpegAPI Create(NvJpegAPIVersion? version) =>
/// The created API wrapper.
private static NvJpegAPI CreateLatest()
{
- Exception firstException = null;
- var versions = Enum.GetValues(typeof(CuFFTAPIVersion));
-
+ Exception? firstException = null;
+#if NET5_0_OR_GREATER
+ var versions = Enum.GetValues();
+#else
+ var versions = (NvJpegAPIVersion[])Enum.GetValues(typeof(NvJpegAPIVersion));
+#endif
for (var i = versions.Length - 1; i >= 0; i--)
{
- var version = (NvJpegAPIVersion)versions.GetValue(i);
+ var version = versions[i];
var api = CreateInternal(version);
if (api is null)
continue;
@@ -122,7 +126,7 @@ public unsafe NvJpegStatus Decode(
ReadOnlySpan imageBytes,
NvJpegOutputFormat outputFormat,
in NvJpegImage destination,
- CudaStream stream)
+ CudaStream? stream)
{
var imageInterop = destination.ToInterop();
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvmlAPI.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvmlAPI.cs
index 4c197c734..e85b9956d 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvmlAPI.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/API/NvmlAPI.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: NvmlAPI.cs
@@ -9,6 +9,7 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
using System.Text;
@@ -32,6 +33,7 @@ public abstract partial class NvmlAPI
public static NvmlAPI Create(NvmlAPIVersion? version) =>
version.HasValue
? CreateInternal(version.Value)
+ ?? throw new DllNotFoundException(nameof(NvmlAPI))
: CreateLatest();
///
@@ -40,12 +42,15 @@ public static NvmlAPI Create(NvmlAPIVersion? version) =>
/// The created API wrapper.
private static NvmlAPI CreateLatest()
{
- Exception firstException = null;
- var versions = Enum.GetValues(typeof(NvmlAPIVersion));
-
+ Exception? firstException = null;
+#if NET5_0_OR_GREATER
+ var versions = Enum.GetValues();
+#else
+ var versions = (NvmlAPIVersion[])Enum.GetValues(typeof(NvmlAPIVersion));
+#endif
for (var i = versions.Length - 1; i >= 0; i--)
{
- var version = (NvmlAPIVersion)versions.GetValue(i);
+ var version = versions[i];
var api = CreateInternal(version);
if (api is null)
continue;
@@ -80,7 +85,7 @@ ex is DllNotFoundException ||
internal unsafe static NvmlReturn GetNvmlString(
Func interopFunc,
uint length,
- out string nvmlString)
+ out string? nvmlString)
{
NvmlReturn result;
ReadOnlySpan buffer =
@@ -120,7 +125,7 @@ internal unsafe delegate NvmlReturn GetNvmlArrayInterop(
/// The interop status code.
internal unsafe static NvmlReturn GetNvmlArray(
GetNvmlArrayInterop interopFunc,
- out T[] nvmlArray)
+ out T[]? nvmlArray)
where T : unmanaged
{
// Query the length of data available.
@@ -176,8 +181,8 @@ internal unsafe delegate NvmlReturn GetNvmlArrayInterop(
/// The interop status code.
internal unsafe static NvmlReturn GetNvmlArray(
GetNvmlArrayInterop interopFunc,
- out T1[] nvmlArray1,
- out T2[] nvmlArray2)
+ out T1[]? nvmlArray1,
+ out T2[]? nvmlArray2)
where T1 : unmanaged
where T2 : unmanaged
{
@@ -242,7 +247,7 @@ internal unsafe delegate NvmlReturn FillNvmlArrayInterop(
internal unsafe static NvmlReturn FillNvmlArray(
FillNvmlArrayInterop interopFunc,
uint length,
- out T[] nvmlArray)
+ out T[]? nvmlArray)
where T : unmanaged
{
// Allocate enough space for the requested length.
@@ -266,7 +271,7 @@ internal unsafe static NvmlReturn FillNvmlArray(
///
public unsafe NvmlReturn DeviceGetBoardPartNumber(
IntPtr device,
- out string partNumber) =>
+ out string? partNumber) =>
GetNvmlString(
(str, len) => DeviceGetBoardPartNumber_Interop(device, str, len),
NvmlConstants.NVML_DEVICE_PART_NUMBER_BUFFER_SIZE,
@@ -307,7 +312,7 @@ public unsafe NvmlReturn DeviceGetBridgeChipInfo(
///
public unsafe NvmlReturn DeviceGetComputeRunningProcesses(
IntPtr device,
- out NvmlProcessInfo[] infos)
+ out NvmlProcessInfo[]? infos)
{
NvmlReturn Interop(ref uint len, NvmlProcessInfo* ptr) =>
DeviceGetComputeRunningProcesses_v2_Interop(device, ref len, ptr);
@@ -320,7 +325,7 @@ NvmlReturn Interop(ref uint len, NvmlProcessInfo* ptr) =>
///
public unsafe NvmlReturn DeviceGetEncoderSessions(
IntPtr device,
- out NvmlEncoderSessionInfo[] sessionInfos)
+ out NvmlEncoderSessionInfo[]? sessionInfos)
{
NvmlReturn Interop(ref uint len, NvmlEncoderSessionInfo* ptr) =>
DeviceGetEncoderSessions_Interop(device, ref len, ptr);
@@ -333,7 +338,7 @@ NvmlReturn Interop(ref uint len, NvmlEncoderSessionInfo* ptr) =>
///
public unsafe NvmlReturn DeviceGetInforomImageVersion(
IntPtr device,
- out string version) =>
+ out string? version) =>
GetNvmlString(
(str, len) => DeviceGetInforomImageVersion_Interop(device, str, len),
NvmlConstants.NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE,
@@ -346,7 +351,7 @@ public unsafe NvmlReturn DeviceGetInforomImageVersion(
public unsafe NvmlReturn DeviceGetInforomVersion(
IntPtr device,
NvmlInforomObject inforomObject,
- out string version) =>
+ out string? version) =>
GetNvmlString(
(str, len) =>
{
@@ -365,7 +370,7 @@ public unsafe NvmlReturn DeviceGetInforomVersion(
///
public unsafe NvmlReturn DeviceGetGraphicsRunningProcesses(
IntPtr device,
- out NvmlProcessInfo[] infos)
+ out NvmlProcessInfo[]? infos)
{
NvmlReturn Interop(ref uint len, NvmlProcessInfo* ptr) =>
DeviceGetGraphicsRunningProcesses_v2_Interop(device, ref len, ptr);
@@ -378,7 +383,7 @@ NvmlReturn Interop(ref uint len, NvmlProcessInfo* ptr) =>
///
public unsafe NvmlReturn DeviceGetName(
IntPtr device,
- out string name) =>
+ out string? name) =>
GetNvmlString(
(str, len) => DeviceGetName_Interop(device, str, len),
NvmlConstants.NVML_DEVICE_NAME_V2_BUFFER_SIZE,
@@ -438,7 +443,7 @@ public unsafe NvmlReturn DeviceGetPciInfo(
public unsafe NvmlReturn DeviceGetRetiredPages(
IntPtr device,
NvmlPageRetirementCause cause,
- out ulong[] addresses)
+ out ulong[]? addresses)
{
NvmlReturn Interop(ref uint len, ulong* ptr) =>
DeviceGetRetiredPages_Interop(device, cause, ref len, ptr);
@@ -452,8 +457,8 @@ NvmlReturn Interop(ref uint len, ulong* ptr) =>
public unsafe NvmlReturn DeviceGetRetiredPages_v2(
IntPtr device,
NvmlPageRetirementCause cause,
- out ulong[] addresses,
- out ulong[] timestamps)
+ out ulong[]? addresses,
+ out ulong[]? timestamps)
{
NvmlReturn Interop(ref uint len, ulong* ptr1, ulong* ptr2) =>
DeviceGetRetiredPages_v2_Interop(device, cause, ref len, ptr1, ptr2);
@@ -470,7 +475,7 @@ public unsafe NvmlReturn DeviceGetSamples(
ulong lastSeenTimeStamp,
out NvmlValueType sampleValType,
uint sampleCount,
- out NvmlSample[] samples)
+ out NvmlSample[]? samples)
{
// Allocate enough space for sampleCount.
uint length = sampleCount;
@@ -507,7 +512,7 @@ public unsafe NvmlReturn DeviceGetSamples(
///
public unsafe NvmlReturn DeviceGetSerial(
IntPtr device,
- out string serial) =>
+ out string? serial) =>
GetNvmlString(
(str, len) => DeviceGetSerial_Interop(device, str, len),
NvmlConstants.NVML_DEVICE_SERIAL_BUFFER_SIZE,
@@ -520,7 +525,7 @@ public unsafe NvmlReturn DeviceGetSerial(
public unsafe NvmlReturn DeviceGetSupportedGraphicsClocks(
IntPtr device,
uint memoryClockMHz,
- out uint[] clocksMHz)
+ out uint[]? clocksMHz)
{
NvmlReturn Interop(ref uint len, uint* ptr) =>
DeviceGetSupportedGraphicsClocks_Interop(
@@ -537,7 +542,7 @@ NvmlReturn Interop(ref uint len, uint* ptr) =>
///
public unsafe NvmlReturn DeviceGetSupportedMemoryClocks(
IntPtr device,
- out uint[] clocksMHz)
+ out uint[]? clocksMHz)
{
NvmlReturn Interop(ref uint len, uint* ptr) =>
DeviceGetSupportedMemoryClocks_Interop(device, ref len, ptr);
@@ -551,7 +556,7 @@ NvmlReturn Interop(ref uint len, uint* ptr) =>
public unsafe NvmlReturn DeviceGetTopologyNearestGpus(
IntPtr device,
NvmlGpuTopologyLevel level,
- out IntPtr[] deviceArray)
+ out IntPtr[]? deviceArray)
{
NvmlReturn Interop(ref uint len, IntPtr* ptr) =>
DeviceGetTopologyNearestGpus_Interop(device, level, ref len, ptr);
@@ -564,7 +569,7 @@ NvmlReturn Interop(ref uint len, IntPtr* ptr) =>
///
public unsafe NvmlReturn DeviceGetUUID(
IntPtr device,
- out string uuid) =>
+ out string? uuid) =>
GetNvmlString(
(str, len) => DeviceGetUUID_Interop(device, str, len),
NvmlConstants.NVML_DEVICE_UUID_V2_BUFFER_SIZE,
@@ -576,7 +581,7 @@ public unsafe NvmlReturn DeviceGetUUID(
///
public unsafe NvmlReturn DeviceGetVbiosVersion(
IntPtr device,
- out string version) =>
+ out string? version) =>
GetNvmlString(
(str, len) => DeviceGetVbiosVersion_Interop(device, str, len),
NvmlConstants.NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE,
@@ -588,7 +593,7 @@ public unsafe NvmlReturn DeviceGetVbiosVersion(
///
public unsafe NvmlReturn SystemGetTopologyGpuSet(
uint cpuNumber,
- out IntPtr[] deviceArray)
+ out IntPtr[]? deviceArray)
{
NvmlReturn Interop(ref uint len, IntPtr* ptr) =>
SystemGetTopologyGpuSet_Interop(cpuNumber, ref len, ptr);
@@ -601,7 +606,7 @@ NvmlReturn Interop(ref uint len, IntPtr* ptr) =>
///
public unsafe NvmlReturn VgpuInstanceGetMdevUUID(
uint vgpuInstance,
- out string version) =>
+ out string? version) =>
GetNvmlString(
(str, len) => VgpuInstanceGetMdevUUID_Interop(vgpuInstance, str, len),
NvmlConstants.NVML_DEVICE_UUID_V2_BUFFER_SIZE,
@@ -618,7 +623,7 @@ public unsafe NvmlReturn VgpuInstanceGetMdevUUID(
public unsafe NvmlReturn DeviceGetCpuAffinity(
IntPtr device,
uint cpuSetSize,
- out ulong[] cpuSet)
+ out ulong[]? cpuSet)
{
NvmlReturn Interop(uint len, ulong* ptr) =>
DeviceGetCpuAffinity_Interop(device, len, ptr);
@@ -632,7 +637,7 @@ NvmlReturn Interop(uint len, ulong* ptr) =>
public unsafe NvmlReturn DeviceGetCpuAffinityWithinScope(
IntPtr device,
uint cpuSetSize,
- out ulong[] cpuSet,
+ out ulong[]? cpuSet,
NvmlAffinityScope scope)
{
NvmlReturn Interop(uint len, ulong* ptr) =>
@@ -647,7 +652,7 @@ NvmlReturn Interop(uint len, ulong* ptr) =>
public unsafe NvmlReturn DeviceGetMemoryAffinity(
IntPtr device,
uint nodeSetSize,
- out ulong[] nodeSet,
+ out ulong[]? nodeSet,
NvmlAffinityScope scope)
{
NvmlReturn Interop(uint len, ulong* ptr) =>
@@ -691,7 +696,7 @@ public NvmlReturn SystemGetCudaDriverVersion_v2(
/// Provides access to
/// without using raw pointers.
///
- public NvmlReturn SystemGetDriverVersion(out string version) =>
+ public NvmlReturn SystemGetDriverVersion(out string? version) =>
GetNvmlString(
(str, len) => SystemGetDriverVersion_Interop(str, len),
NvmlConstants.NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE,
@@ -701,7 +706,7 @@ public NvmlReturn SystemGetDriverVersion(out string version) =>
/// Provides access to
/// without using raw pointers.
///
- public NvmlReturn SystemGetNVMLVersion(out string version) =>
+ public NvmlReturn SystemGetNVMLVersion(out string? version) =>
GetNvmlString(
(str, len) => SystemGetNVMLVersion_Interop(str, len),
NvmlConstants.NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE,
@@ -713,7 +718,7 @@ public NvmlReturn SystemGetNVMLVersion(out string version) =>
///
public NvmlReturn SystemGetProcessName(
uint pid,
- out string name,
+ out string? name,
uint length) =>
GetNvmlString(
(str, len) => SystemGetProcessName_Interop(pid, str, len),
@@ -728,7 +733,7 @@ public NvmlReturn SystemGetProcessName(
/// Provides access to
/// without using raw pointers.
///
- public unsafe NvmlReturn SystemGetHicVersion(out NvmlHwbcEntry[] hwbcEntries)
+ public unsafe NvmlReturn SystemGetHicVersion(out NvmlHwbcEntry[]? hwbcEntries)
{
NvmlReturn Interop(ref uint len, NvmlHwbcEntry_Interop* ptr) =>
SystemGetHicVersion_Interop(ref len, ptr);
@@ -737,6 +742,7 @@ NvmlReturn Interop(ref uint len, NvmlHwbcEntry_Interop* ptr) =>
out var interopResult);
if (result == NvmlReturn.NVML_SUCCESS)
{
+ interopResult = interopResult.AsNotNull();
hwbcEntries = new NvmlHwbcEntry[interopResult.Length];
for (int i = 0; i < interopResult.Length; i++)
{
@@ -770,7 +776,7 @@ NvmlReturn Interop(ref uint len, NvmlHwbcEntry_Interop* ptr) =>
///
public unsafe NvmlReturn UnitGetDevices(
IntPtr unit,
- out IntPtr[] devices)
+ out IntPtr[]? devices)
{
NvmlReturn Interop(ref uint len, IntPtr* ptr) =>
UnitGetDevices_Interop(unit, ref len, ptr);
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/CuBlas.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/CuBlas.cs
index 7364a017f..6b09a99db 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/CuBlas.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/CuBlas.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: CuBlas.cs
@@ -13,6 +13,7 @@
using ILGPU.Util;
using System;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace ILGPU.Runtime.Cuda
@@ -148,7 +149,7 @@ private CuBlas(CudaAccelerator accelerator, CuBlasAPIVersion? apiVersion)
API.GetVersion(handle, out int currentVersion));
Version = currentVersion;
- Stream = accelerator.DefaultStream as CudaStream;
+ Stream = accelerator.DefaultStream.AsNotNullCast();
}
#endregion
@@ -230,6 +231,7 @@ public CuBlasMathMode MathMode
public CudaStream Stream
{
get => stream;
+ [MemberNotNull(nameof(stream))]
set
{
if (value == null)
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/CuFFT.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/CuFFT.cs
index d1df7cf7d..2ae50353b 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/CuFFT.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/CuFFT.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: CuFFT.cs
@@ -50,7 +50,7 @@ public CuFFT(CuFFTAPIVersion? version)
/// The transform type.
/// The number of transforms.
/// The error code.
- public CuFFTResult Plan1D(out CuFFTPlan plan, int nx, CuFFTType type, int batch)
+ public CuFFTResult Plan1D(out CuFFTPlan? plan, int nx, CuFFTType type, int batch)
{
var errorCode = API.Plan1D(out var planHandle, nx, type, batch);
plan = errorCode == CuFFTResult.CUFFT_SUCCESS
@@ -67,7 +67,7 @@ public CuFFTResult Plan1D(out CuFFTPlan plan, int nx, CuFFTType type, int batch)
/// The transform size in the y dimension.
/// The transform type.
/// The error code.
- public CuFFTResult Plan2D(out CuFFTPlan plan, int nx, int ny, CuFFTType type)
+ public CuFFTResult Plan2D(out CuFFTPlan? plan, int nx, int ny, CuFFTType type)
{
var errorCode = API.Plan2D(out var planHandle, nx, ny, type);
plan = errorCode == CuFFTResult.CUFFT_SUCCESS
@@ -86,7 +86,7 @@ public CuFFTResult Plan2D(out CuFFTPlan plan, int nx, int ny, CuFFTType type)
/// The transform type.
/// The error code.
public CuFFTResult Plan3D(
- out CuFFTPlan plan,
+ out CuFFTPlan? plan,
int nx,
int ny,
int nz,
@@ -115,7 +115,7 @@ public CuFFTResult Plan3D(
/// The number of transforms.
/// The error code.
public CuFFTResult PlanMany(
- out CuFFTPlan plan,
+ out CuFFTPlan? plan,
int rank,
int[] n,
int[] inembed,
@@ -152,7 +152,7 @@ public CuFFTResult PlanMany(
///
/// Creates an extensible plan.
///
- public CuFFTResult CreatePlan(out CuFFTPlan plan)
+ public CuFFTResult CreatePlan(out CuFFTPlan? plan)
{
var errorCode = API.Create(out var planHandle);
plan = errorCode == CuFFTResult.CUFFT_SUCCESS
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/CuRand.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/CuRand.cs
index ecbc015ca..2aae7a7bd 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/CuRand.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/CuRand.cs
@@ -14,6 +14,7 @@
using ILGPU.Runtime.Cuda.API;
using ILGPU.Util;
using System;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using static ILGPU.Algorithms.Random.RandomExtensions;
@@ -232,7 +233,7 @@ private GPUCuRand(
API.GetVersion(out int version));
Version = version;
- Stream = accelerator.DefaultStream as CudaStream;
+ Stream = accelerator.DefaultStream.AsNotNullCast();
}
#endregion
@@ -260,6 +261,7 @@ private GPUCuRand(
public CudaStream Stream
{
get => currentStream;
+ [MemberNotNull(nameof(currentStream))]
set
{
if (value == null)
diff --git a/Src/ILGPU.Algorithms/Runtime/Cuda/NvJpegStructs.cs b/Src/ILGPU.Algorithms/Runtime/Cuda/NvJpegStructs.cs
index 0ac4d8273..45f0a9356 100644
--- a/Src/ILGPU.Algorithms/Runtime/Cuda/NvJpegStructs.cs
+++ b/Src/ILGPU.Algorithms/Runtime/Cuda/NvJpegStructs.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU Algorithms
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: NvJpegStructs.cs
@@ -9,6 +9,7 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
#pragma warning disable CA1051 // Do not declare visible instance fields
@@ -29,7 +30,7 @@ public struct NvJpegImage
{
#region Properties
- public MemoryBuffer1D[] Channel;
+ public MemoryBuffer1D?[] Channel;
public ulong[] Pitch;
#endregion
@@ -64,7 +65,7 @@ public static NvJpegImage Create(
var size = width * height;
var outputImage = new NvJpegImage
{
- Channel = new MemoryBuffer1D[]
+ Channel = new MemoryBuffer1D?[]
{
numComponents >= 1 ? accelerator.Allocate1D(size) : null,
numComponents >= 2 ? accelerator.Allocate1D(size) : null,
@@ -104,7 +105,7 @@ ulong MemoryBufferToUInt64(MemoryBuffer1D buffer) =>
i < Math.Min(Channel.Length, NvJpegConstants.NVJPEG_MAX_COMPONENT);
i++)
{
- imageInterop.Channel[i] = MemoryBufferToUInt64(Channel[i]);
+ imageInterop.Channel[i] = MemoryBufferToUInt64(Channel[i].AsNotNull());
imageInterop.Pitch[i] = Pitch[i];
}
diff --git a/Src/ILGPU.Algorithms/Vectors/VectorTypes.tt b/Src/ILGPU.Algorithms/Vectors/VectorTypes.tt
index 8671a5c66..136274fc8 100644
--- a/Src/ILGPU.Algorithms/Vectors/VectorTypes.tt
+++ b/Src/ILGPU.Algorithms/Vectors/VectorTypes.tt
@@ -492,7 +492,7 @@ namespace ILGPU.Algorithms.Vectors
///
/// Converts this vector instance to a string.
///
- public string ToString(string format, IFormatProvider formatProvider) =>
+ public string ToString(string? format, IFormatProvider? formatProvider) =>
$"<#= string.Join($", ", vectorItemNames
.Take(vectorLength)
.Select(t => $"{{{t}.ToString(format, formatProvider)}}")) #>";
@@ -797,7 +797,7 @@ namespace ILGPU.Algorithms.Vectors
///
static <#= typeName #> IParsable<<#= typeName #>>.Parse(
string s,
- IFormatProvider provider) =>
+ IFormatProvider? provider) =>
throw new NotSupportedException();
///
@@ -805,7 +805,7 @@ namespace ILGPU.Algorithms.Vectors
///
static <#= typeName #> ISpanParsable<<#= typeName #>>.Parse(
ReadOnlySpan s,
- IFormatProvider provider) =>
+ IFormatProvider? provider) =>
throw new NotSupportedException();
///
@@ -814,7 +814,7 @@ namespace ILGPU.Algorithms.Vectors
static <#= typeName #> INumberBase<<#= typeName #>>.Parse(
ReadOnlySpan s,
NumberStyles style,
- IFormatProvider provider) =>
+ IFormatProvider? provider) =>
throw new NotSupportedException();
///
@@ -823,7 +823,7 @@ namespace ILGPU.Algorithms.Vectors
static <#= typeName #> INumberBase<<#= typeName #>>.Parse(
string s,
NumberStyles style,
- IFormatProvider provider) =>
+ IFormatProvider? provider) =>
throw new NotSupportedException();
///
@@ -833,15 +833,15 @@ namespace ILGPU.Algorithms.Vectors
Span destination,
out int charsWritten,
ReadOnlySpan format,
- IFormatProvider provider) =>
+ IFormatProvider? provider) =>
throw new NotSupportedException();
///
/// Tries to parse the given string into a vectorized instance.
///
static bool IParsable<<#= typeName #>>.TryParse(
- string s,
- IFormatProvider provider,
+ string? s,
+ IFormatProvider? provider,
out <#= typeName #> result) =>
throw new NotSupportedException();
@@ -850,7 +850,7 @@ namespace ILGPU.Algorithms.Vectors
///
static bool ISpanParsable<<#= typeName #>>.TryParse(
ReadOnlySpan s,
- IFormatProvider provider,
+ IFormatProvider? provider,
out <#= typeName #> result) =>
throw new NotSupportedException();
@@ -860,7 +860,7 @@ namespace ILGPU.Algorithms.Vectors
static bool INumberBase<<#= typeName #>>.TryParse(
ReadOnlySpan s,
NumberStyles style,
- IFormatProvider provider,
+ IFormatProvider? provider,
out <#= typeName #> result) =>
throw new NotSupportedException();
@@ -868,9 +868,9 @@ namespace ILGPU.Algorithms.Vectors
/// Tries to parse the given string into a vectorized instance.
///
static bool INumberBase<<#= typeName #>>.TryParse(
- string s,
+ string? s,
NumberStyles style,
- IFormatProvider provider,
+ IFormatProvider? provider,
out <#= typeName #> result) =>
throw new NotSupportedException();
diff --git a/Src/ILGPU.Tests/BasicLoops.cs b/Src/ILGPU.Tests/BasicLoops.cs
index 3d77eea85..c47cae094 100644
--- a/Src/ILGPU.Tests/BasicLoops.cs
+++ b/Src/ILGPU.Tests/BasicLoops.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021-2022 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: BasicLoops.cs
@@ -11,7 +11,6 @@
using ILGPU.Runtime;
using ILGPU.Util;
-using System;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
diff --git a/Src/ILGPU.Tests/DisassemblerTests.cs b/Src/ILGPU.Tests/DisassemblerTests.cs
index d6e180a31..8937f4f0c 100644
--- a/Src/ILGPU.Tests/DisassemblerTests.cs
+++ b/Src/ILGPU.Tests/DisassemblerTests.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: DisassemblerTests.cs
@@ -12,6 +12,7 @@
using ILGPU.Frontend;
using ILGPU.Frontend.DebugInformation;
using ILGPU.Runtime;
+using ILGPU.Util;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -102,7 +103,8 @@ public void StelemLdtoken(Type genericType)
{
var methodInfo = typeof(DisassemblerTests).GetMethod(
nameof(StelemLdtokenKernel),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
var method = methodInfo.MakeGenericMethod(genericType);
var disassembler = new Disassembler(method, SequencePointEnumerator.Empty);
diff --git a/Src/ILGPU.Tests/FixedBuffers.tt b/Src/ILGPU.Tests/FixedBuffers.tt
index a8dc38f00..fcb7eae41 100644
--- a/Src/ILGPU.Tests/FixedBuffers.tt
+++ b/Src/ILGPU.Tests/FixedBuffers.tt
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: FixedBuffers.tt/FixedBuffers.cs
@@ -64,7 +64,7 @@ namespace ILGPU.Tests
return true;
}
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is FixedBufferStruct<#= type.Name #> fixedStruct &&
Equals(fixedStruct);
}
@@ -121,7 +121,7 @@ namespace ILGPU.Tests
return true;
}
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is MultiFixedBufferStruct<#= type.Name #> fixedStruct &&
Equals(fixedStruct);
}
diff --git a/Src/ILGPU.Tests/Generic/KernelMethodAttribute.cs b/Src/ILGPU.Tests/Generic/KernelMethodAttribute.cs
index a9183fec0..42346de50 100644
--- a/Src/ILGPU.Tests/Generic/KernelMethodAttribute.cs
+++ b/Src/ILGPU.Tests/Generic/KernelMethodAttribute.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: KernelMethodAttribute.cs
@@ -9,6 +9,7 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
using System.Diagnostics;
using System.Reflection;
@@ -50,7 +51,7 @@ public KernelMethodAttribute(string methodName, Type type)
///
/// Returns the type in which the kernel method could be found (if any).
///
- public Type Type { get; }
+ public Type? Type { get; }
///
/// Resolves the kernel method using the current configuration.
@@ -58,20 +59,20 @@ public KernelMethodAttribute(string methodName, Type type)
/// The kernel type arguments.
/// The resolved kernel method.
public static MethodInfo GetKernelMethod(
- Type[] typeArguments = null,
+ Type[]? typeArguments = null,
int offset = 1)
{
// TODO: create a nicer way ;)
var stackTrace = new StackTrace();
for (int i = offset; i < stackTrace.FrameCount; ++i)
{
- var frame = stackTrace.GetFrame(i);
- var callingMethod = frame.GetMethod();
+ var frame = stackTrace.GetFrame(i).ThrowIfNull();
+ var callingMethod = frame.GetMethod().ThrowIfNull();
var attribute = callingMethod.GetCustomAttribute<
KernelMethodAttribute>();
if (attribute == null)
continue;
- var type = attribute.Type ?? callingMethod.DeclaringType;
+ var type = attribute.Type ?? callingMethod.DeclaringType.ThrowIfNull();
return TestBase.GetKernelMethod(
type,
attribute.MethodName,
diff --git a/Src/ILGPU.Tests/Generic/TestBase.cs b/Src/ILGPU.Tests/Generic/TestBase.cs
index f8f8efbc8..cc323adf1 100644
--- a/Src/ILGPU.Tests/Generic/TestBase.cs
+++ b/Src/ILGPU.Tests/Generic/TestBase.cs
@@ -59,7 +59,7 @@ public static bool CleanTests
internal static MethodInfo GetKernelMethod(
Type type,
string name,
- Type[] typeArguments)
+ Type[]? typeArguments)
{
var method = type.GetMethod(
name,
diff --git a/Src/ILGPU.Tests/Generic/TestData.cs b/Src/ILGPU.Tests/Generic/TestData.cs
index 1e2908226..369c679f0 100644
--- a/Src/ILGPU.Tests/Generic/TestData.cs
+++ b/Src/ILGPU.Tests/Generic/TestData.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: TestData.cs
@@ -9,6 +9,7 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
using System.Runtime.InteropServices;
using Xunit.Abstractions;
@@ -42,7 +43,10 @@ public static class TestData
/// The value to wrap.
public class TestData : IXunitSerializable
{
- public TestData() { }
+ public TestData()
+ {
+ Value = Utilities.InitNotNullable();
+ }
public TestData(T value)
{
@@ -61,7 +65,7 @@ public void Serialize(IXunitSerializationInfo info)
info.AddValue(nameof(Value), Value);
}
- public override string ToString() => Value.ToString();
+ public override string ToString() => $"{Value}";
}
#region Data Structures
@@ -88,7 +92,7 @@ public void Serialize(IXunitSerializationInfo info) { }
public bool Equals(EmptyStruct other) => true;
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is EmptyStruct other && Equals(other);
public override int GetHashCode() => 0;
@@ -96,9 +100,9 @@ public override bool Equals(object obj) =>
[Serializable]
// warning disabled intentionally for testing this scenario
- #pragma warning disable CS0659 // Type does not override Object.GetHashCode()
+#pragma warning disable CS0659 // Type does not override Object.GetHashCode()
public struct NoHashCodeStruct : IXunitSerializable, IEquatable
- #pragma warning restore CS0659 // Type does not override Object.GetHashCode()
+#pragma warning restore CS0659 // Type does not override Object.GetHashCode()
{
public void Deserialize(IXunitSerializationInfo info) { }
@@ -106,7 +110,7 @@ public void Serialize(IXunitSerializationInfo info) { }
public bool Equals(NoHashCodeStruct other) => true;
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is NoHashCodeStruct other && Equals(other);
}
@@ -181,7 +185,7 @@ public bool Equals(TestStruct other) =>
Z == other.Z &&
W == other.W;
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is TestStruct other && Equals(other);
public override int GetHashCode() =>
@@ -266,7 +270,7 @@ public bool Equals(TestStructEquatable other) =>
Val2 == other.Val2 &&
Val1.Equals(other.Val1);
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is TestStructEquatable other && Equals(other);
public override int GetHashCode() =>
@@ -355,7 +359,7 @@ public bool Equals(TestStructEquatable other) =>
Val0.Equals(other.Val0) &&
Val2.Equals(other.Val2);
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is TestStructEquatable other && Equals(other);
public override int GetHashCode() => data.GetHashCode();
diff --git a/Src/ILGPU.Tests/ILGPU.Tests.csproj b/Src/ILGPU.Tests/ILGPU.Tests.csproj
index 6ff11ad0c..eb23233e9 100644
--- a/Src/ILGPU.Tests/ILGPU.Tests.csproj
+++ b/Src/ILGPU.Tests/ILGPU.Tests.csproj
@@ -6,6 +6,14 @@
+
+
+ enable
+
+
+ $(NoWarn);nullable
+
+
latest
true
diff --git a/Src/ILGPU.Tests/MemoryBufferOperations.tt b/Src/ILGPU.Tests/MemoryBufferOperations.tt
index 70479dcb9..da355499e 100644
--- a/Src/ILGPU.Tests/MemoryBufferOperations.tt
+++ b/Src/ILGPU.Tests/MemoryBufferOperations.tt
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021-2022 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: MemoryBufferOperations.tt/MemoryBufferOperations.cs
@@ -42,6 +42,7 @@ namespace ILGPU.Tests
int length,
int stride,
Func builder)
+ where T : unmanaged
{
int counter = 0;
int strideCounter = 0;
@@ -60,6 +61,7 @@ namespace ILGPU.Tests
private static T[,] InitializeArray2D(
int length,
Func builder)
+ where T : unmanaged
{
int counter = 0;
var src = new T[length, length];
@@ -78,6 +80,7 @@ namespace ILGPU.Tests
private static T[,,] InitializeArray3D(
int length,
Func builder)
+ where T : unmanaged
{
int counter = 0;
var src = new T[length, length, length];
diff --git a/Src/ILGPU.Tests/SharedMemory.cs b/Src/ILGPU.Tests/SharedMemory.cs
index e632f1992..80ca30fdf 100644
--- a/Src/ILGPU.Tests/SharedMemory.cs
+++ b/Src/ILGPU.Tests/SharedMemory.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021-2022 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: SharedMemory.cs
@@ -245,19 +245,21 @@ public void MultiDimensionalSharedMemory2D()
var expected = Enumerable.Repeat(42, groupSize).ToArray();
Verify(buffer.View, expected);
}
-
+
internal static void MultiDimensionalSharedMemoryKernel2DDenseX(
ArrayView1D output)
{
var sharedMemory = ILGPU.SharedMemory.Allocate2DDenseX(
new Index2D(20, 100));
- if (Group.IsFirstThread) {
+ if (Group.IsFirstThread)
+ {
sharedMemory[0, 0] = 0;
sharedMemory[1, 0] = 0;
}
- if (Grid.GlobalIndex.X < 100) {
+ if (Grid.GlobalIndex.X < 100)
+ {
sharedMemory[0, Grid.GlobalIndex.X] = Grid.GlobalIndex.X;
- sharedMemory[1, Grid.GlobalIndex.X] = 7*Grid.GlobalIndex.X;
+ sharedMemory[1, Grid.GlobalIndex.X] = 7 * Grid.GlobalIndex.X;
}
Group.Barrier();
if (Grid.GlobalIndex.X < 100)
@@ -273,9 +275,9 @@ public void MultiDimensionalSharedMemory2DDenseX()
int groupSize = Accelerator.MaxNumThreadsPerGroup;
using var buffer = Accelerator.Allocate1D(groupSize);
Execute(new KernelConfig(1, groupSize), buffer.View);
- var expected =
+ var expected =
Enumerable.Range(0, groupSize).Select(
- x => x < 100 ? 7*x : 0).ToArray();
+ x => x < 100 ? 7 * x : 0).ToArray();
Verify(buffer.View, expected);
}
@@ -284,13 +286,15 @@ internal static void MultiDimensionalSharedMemoryKernel2DDenseY(
{
var sharedMemory = ILGPU.SharedMemory.Allocate2DDenseY(
new Index2D(100, 20));
- if (Group.IsFirstThread) {
+ if (Group.IsFirstThread)
+ {
sharedMemory[0, 0] = 0;
sharedMemory[0, 1] = 0;
}
- if (Grid.GlobalIndex.X < 100) {
+ if (Grid.GlobalIndex.X < 100)
+ {
sharedMemory[Grid.GlobalIndex.X, 0] = Grid.GlobalIndex.X;
- sharedMemory[Grid.GlobalIndex.X, 1] = 7*Grid.GlobalIndex.X;
+ sharedMemory[Grid.GlobalIndex.X, 1] = 7 * Grid.GlobalIndex.X;
}
Group.Barrier();
if (Grid.GlobalIndex.X < 100)
@@ -306,9 +310,9 @@ public void MultiDimensionalSharedMemory2DDenseY()
int groupSize = Accelerator.MaxNumThreadsPerGroup;
using var buffer = Accelerator.Allocate1D(groupSize);
Execute(new KernelConfig(1, groupSize), buffer.View);
- var expected =
+ var expected =
Enumerable.Range(0, groupSize).Select(
- x => x < 100 ? 7*x : 0).ToArray();
+ x => x < 100 ? 7 * x : 0).ToArray();
Verify(buffer.View, expected);
}
@@ -335,7 +339,7 @@ public void MultiDimensionalSharedMemory3D()
var expected = Enumerable.Repeat(42, groupSize).ToArray();
Verify(buffer.View, expected);
}
-
+
internal static void MultiDimensionalSharedMemoryKernel3DDenseXY(
ArrayView1D output)
{
diff --git a/Src/ILGPU.Tests/StaticAbstractInterfaceMembers.cs b/Src/ILGPU.Tests/StaticAbstractInterfaceMembers.cs
index 2310a42fd..78f525511 100644
--- a/Src/ILGPU.Tests/StaticAbstractInterfaceMembers.cs
+++ b/Src/ILGPU.Tests/StaticAbstractInterfaceMembers.cs
@@ -134,7 +134,7 @@ public interface IStaticAbstract
static abstract int Inc(int x);
}
- public class Incrementer: IStaticAbstract
+ public class Incrementer : IStaticAbstract
{
public static int Inc(int x) => x + 1;
}
diff --git a/Src/ILGPU/ArrayView.cs b/Src/ILGPU/ArrayView.cs
index 1f9c40c80..bca8c869f 100644
--- a/Src/ILGPU/ArrayView.cs
+++ b/Src/ILGPU/ArrayView.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2017-2021 ILGPU Project
+// Copyright (c) 2017-2023 ILGPU Project
// www.ilgpu.net
//
// File: ArrayView.cs
@@ -200,7 +200,6 @@ public interface IArrayView :
[NotInsideKernel]
public ArrayView(MemoryBuffer source, long index, long length)
{
- Trace.Assert(source != null, "Invalid source buffer");
Trace.Assert(index >= 0L, "Index out of range");
Trace.Assert(length >= 0L, "Length out of range");
diff --git a/Src/ILGPU/Backends/Backend.cs b/Src/ILGPU/Backends/Backend.cs
index cc0c8eb01..22b0b917b 100644
--- a/Src/ILGPU/Backends/Backend.cs
+++ b/Src/ILGPU/Backends/Backend.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2017-2022 ILGPU Project
+// Copyright (c) 2017-2023 ILGPU Project
// www.ilgpu.net
//
// File: Backend.cs
@@ -328,7 +328,7 @@ private CompiledKernel.KernelInfo CreateKernelInfo()
///
/// Returns the associated kernel information object (if any).
///
- public CompiledKernel.KernelInfo KernelInfo { get; }
+ public CompiledKernel.KernelInfo? KernelInfo { get; }
#endregion
@@ -603,8 +603,8 @@ public Method PreCompileKernelMethod(
}
if (codeGenerationPhase.IsFaulted)
- throw codeGenerationPhase.LastException;
- generatedKernelMethod = generationResult.Result;
+ throw codeGenerationPhase.LastException.AsNotNull();
+ generatedKernelMethod = generationResult.Result.AsNotNull();
codeGenerationPhase.Optimize();
backendHook.FinishedCodeGeneration(mainContext, generatedKernelMethod);
@@ -801,7 +801,11 @@ protected Backend(
BackendType backendType,
ArgumentMapper argumentMapper)
: base(context, capabilities, backendType, argumentMapper)
- { }
+ {
+ // NB: Initialized later by derived classes.
+ IntrinsicProvider =
+ Utilities.InitNotNullable>();
+ }
#endregion
diff --git a/Src/ILGPU/Backends/CodeGeneratorBackend.cs b/Src/ILGPU/Backends/CodeGeneratorBackend.cs
index e1e745254..3eb250e13 100644
--- a/Src/ILGPU/Backends/CodeGeneratorBackend.cs
+++ b/Src/ILGPU/Backends/CodeGeneratorBackend.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CodeGeneratorBackend.cs
@@ -174,7 +174,7 @@ protected abstract TCodeGenerator CreateKernelCodeGenerator(
/// The resulting compiled kernel.
protected abstract CompiledKernel CreateKernel(
EntryPoint entryPoint,
- CompiledKernel.KernelInfo kernelInfo,
+ CompiledKernel.KernelInfo? kernelInfo,
TKernelBuilder builder,
T data);
diff --git a/Src/ILGPU/Backends/CompiledKernel.cs b/Src/ILGPU/Backends/CompiledKernel.cs
index 2471005ae..6dcfa4eb4 100644
--- a/Src/ILGPU/Backends/CompiledKernel.cs
+++ b/Src/ILGPU/Backends/CompiledKernel.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: CompiledKernel.cs
@@ -183,7 +183,7 @@ public virtual void Dump(TextWriter textWriter)
protected CompiledKernel(
Context context,
EntryPoint entryPoint,
- KernelInfo info)
+ KernelInfo? info)
{
Context = context;
EntryPoint = entryPoint;
@@ -236,7 +236,7 @@ protected CompiledKernel(
/// This instance will be available when the property
/// is enabled.
///
- public KernelInfo Info { get; }
+ public KernelInfo? Info { get; }
#endregion
diff --git a/Src/ILGPU/Backends/EntryPoints/ArgumentMapper.cs b/Src/ILGPU/Backends/EntryPoints/ArgumentMapper.cs
index 394dd550c..ab06a25bb 100644
--- a/Src/ILGPU/Backends/EntryPoints/ArgumentMapper.cs
+++ b/Src/ILGPU/Backends/EntryPoints/ArgumentMapper.cs
@@ -636,7 +636,7 @@ protected Type RegisterTypeMapping(Type type, Type mappedType)
protected Type MapType(Type type)
{
Debug.Assert(type != null, "Invalid source type");
- if (typeMapping.TryGetValue(type, out Type mappedType))
+ if (typeMapping.TryGetValue(type, out Type? mappedType))
return mappedType;
if (type.IsByRef)
@@ -673,7 +673,7 @@ protected Type MapType(Type type)
return RegisterTypeMapping(type, typeof(void*));
else if (type.IsEnum)
return RegisterTypeMapping(type, type.GetEnumUnderlyingType());
- else if (type.IsArrayViewType(out Type elementType))
+ else if (type.IsArrayViewType(out Type? elementType))
return RegisterTypeMapping(type, MapViewType(type, elementType));
else
return RegisterTypeMapping(type, MapStructType(type));
@@ -760,7 +760,7 @@ protected void MapInstance(
// Copy object from source to target
target.EmitStoreTarget(emitter, source);
}
- else if (sourceType.IsArrayViewType(out Type elementType))
+ else if (sourceType.IsArrayViewType(out Type? elementType))
{
MapViewInstance(emitter, elementType, source, target);
}
@@ -896,7 +896,7 @@ protected T MapArgumentsStruct(
{
var fieldTarget = new StructureTarget(
localTarget,
- argumentType.GetField(GetFieldName(i)));
+ argumentType.GetField(GetFieldName(i)).AsNotNull());
// Perform actual instance mapping on local
MapParameter(emitter, parameters, i, fieldTarget);
@@ -907,7 +907,7 @@ protected T MapArgumentsStruct(
var lastFieldName = GetFieldName(parameters.Count - 1);
int lastOffset = Marshal.OffsetOf(argumentType, lastFieldName).ToInt32();
int lastFieldSize = Interop.SizeOf(
- argumentType.GetField(lastFieldName).FieldType);
+ argumentType.GetField(lastFieldName).AsNotNull().FieldType);
// Map the whole argument structure
return mappingHandler.MapArgumentStruct(
diff --git a/Src/ILGPU/Backends/EntryPoints/EntryPoint.cs b/Src/ILGPU/Backends/EntryPoints/EntryPoint.cs
index af34e9286..f08463096 100644
--- a/Src/ILGPU/Backends/EntryPoints/EntryPoint.cs
+++ b/Src/ILGPU/Backends/EntryPoints/EntryPoint.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: EntryPoint.cs
@@ -10,6 +10,7 @@
// ---------------------------------------------------------------------------------------
using ILGPU.Runtime;
+using ILGPU.Util;
using System;
using System.Reflection;
@@ -163,7 +164,7 @@ internal RuntimeSystem.ScopedLock CreateLauncherMethod(
/// The acquired scoped lock.
internal RuntimeSystem.ScopedLock CreateLauncherMethod(
RuntimeSystem runtimeSystem,
- Type instanceType,
+ Type? instanceType,
out RuntimeSystem.MethodEmitter methodEmitter) =>
Description.CreateLauncherMethod(
runtimeSystem,
@@ -189,7 +190,8 @@ public readonly struct SharedMemorySpecification
{
typeof(int),
typeof(bool)
- });
+ })
+ .ThrowIfNull();
#endregion
diff --git a/Src/ILGPU/Backends/EntryPoints/EntryPointDescription.cs b/Src/ILGPU/Backends/EntryPoints/EntryPointDescription.cs
index c5cb0b7fe..2b0028385 100644
--- a/Src/ILGPU/Backends/EntryPoints/EntryPointDescription.cs
+++ b/Src/ILGPU/Backends/EntryPoints/EntryPointDescription.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: EntryPointDescription.cs
@@ -76,7 +76,7 @@ public static EntryPointDescription FromImplicitlyGroupedKernel(
/// The index type.
internal EntryPointDescription(
MethodInfo methodSource,
- ParameterInfo[] parameters,
+ ParameterInfo[]? parameters,
IndexType indexType)
{
if (indexType == IndexType.None)
@@ -178,7 +178,7 @@ public void Validate()
/// The acquired scoped lock.
internal RuntimeSystem.ScopedLock CreateLauncherMethod(
RuntimeSystem runtimeSystem,
- Type instanceType,
+ Type? instanceType,
out RuntimeSystem.MethodEmitter methodEmitter)
{
var parameterTypes = new Type[
@@ -229,7 +229,7 @@ public bool Equals(EntryPointDescription other) =>
///
/// The other object.
/// True, if the given object is equal to the current one.
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is EntryPointDescription other && Equals(other);
///
diff --git a/Src/ILGPU/Backends/EntryPoints/ParameterCollection.cs b/Src/ILGPU/Backends/EntryPoints/ParameterCollection.cs
index 96b86059f..e68464cc6 100644
--- a/Src/ILGPU/Backends/EntryPoints/ParameterCollection.cs
+++ b/Src/ILGPU/Backends/EntryPoints/ParameterCollection.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: ParameterCollection.cs
@@ -50,7 +50,7 @@ public Type Current
get
{
var type = enumerator.Current;
- return type.IsByRef ? type.GetElementType() : type;
+ return type.IsByRef ? type.GetElementType().AsNotNull() : type;
}
}
@@ -189,7 +189,7 @@ private static Type GetParameterType(
int parameterIndex)
{
var type = parameterTypes[parameterIndex];
- return type.IsByRef ? type.GetElementType() : type;
+ return type.IsByRef ? type.GetElementType().AsNotNull() : type;
}
///
diff --git a/Src/ILGPU/Backends/IL/ILBackend.cs b/Src/ILGPU/Backends/IL/ILBackend.cs
index 831c638a0..6390a185a 100644
--- a/Src/ILGPU/Backends/IL/ILBackend.cs
+++ b/Src/ILGPU/Backends/IL/ILBackend.cs
@@ -16,6 +16,7 @@
using ILGPU.Resources;
using ILGPU.Runtime;
using ILGPU.Runtime.CPU;
+using ILGPU.Util;
using System;
using System.Collections.Immutable;
using System.Reflection;
@@ -53,7 +54,8 @@ public delegate void Handler(
private static readonly MethodInfo Reconstruct2DIndexMethod =
typeof(ILBackend).GetMethod(
nameof(Reconstruct2DIndex),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
///
/// A reference to the static
@@ -62,7 +64,8 @@ public delegate void Handler(
private static readonly MethodInfo Reconstruct3DIndexMethod =
typeof(ILBackend).GetMethod(
nameof(Reconstruct3DIndex),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
///
/// Helper method to reconstruct 2D indices.
@@ -132,7 +135,7 @@ internal ILBackend(
/// Returns the associated .
///
public new ILArgumentMapper ArgumentMapper =>
- base.ArgumentMapper as ILArgumentMapper;
+ base.ArgumentMapper.AsNotNullCast();
#endregion
@@ -328,17 +331,20 @@ private Type GenerateAcceleratorTask(
for (int i = 0, e = argFieldBuilders.Length; i < e; ++i)
{
argFieldBuilders[i] = taskBuilder.GetField(
- string.Format(ArgumentFormat, i));
+ string.Format(ArgumentFormat, i)).AsNotNull();
}
}
taskConstructor = taskType.GetConstructor(
- CPUAcceleratorTask.ConstructorParameterTypes);
+ CPUAcceleratorTask.ConstructorParameterTypes).AsNotNull();
// Map the final fields
var resultMapping = ImmutableArray.CreateBuilder(
parameters.Count);
for (int i = 0, e = parameters.Count; i < e; ++i)
- resultMapping.Add(taskType.GetField(argFieldBuilders[i].Name));
+ {
+ resultMapping.Add(
+ taskType.GetField(argFieldBuilders[i].Name).AsNotNull());
+ }
taskArgumentMapping = resultMapping.MoveToImmutable();
return taskType;
diff --git a/Src/ILGPU/Backends/IL/ILEmitter.cs b/Src/ILGPU/Backends/IL/ILEmitter.cs
index 050e3ec5f..2cc6e05f1 100644
--- a/Src/ILGPU/Backends/IL/ILEmitter.cs
+++ b/Src/ILGPU/Backends/IL/ILEmitter.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: ILEmitter.cs
@@ -525,7 +525,7 @@ public void EmitCall(MethodInfo target)
{
EmitPrefix();
Writer.Write(target.IsVirtual ? "callvirt " : "call ");
- Writer.Write(target.DeclaringType.FullName);
+ Writer.Write(target.DeclaringType.AsNotNull().FullName);
Writer.Write('.');
Writer.WriteLine(target.Name);
}
@@ -535,7 +535,7 @@ public void EmitNewObject(ConstructorInfo info)
{
EmitPrefix();
Writer.Write("newobj ");
- Writer.Write(info.DeclaringType.FullName);
+ Writer.Write(info.DeclaringType.AsNotNull().FullName);
Writer.Write('.');
Writer.WriteLine(info.Name);
}
diff --git a/Src/ILGPU/Backends/IL/ILEmitterExtensions.cs b/Src/ILGPU/Backends/IL/ILEmitterExtensions.cs
index d48d23542..b2c44573b 100644
--- a/Src/ILGPU/Backends/IL/ILEmitterExtensions.cs
+++ b/Src/ILGPU/Backends/IL/ILEmitterExtensions.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: ILEmitterExtensions.cs
@@ -9,6 +9,7 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
using System.Reflection;
using System.Reflection.Emit;
@@ -20,12 +21,16 @@ namespace ILGPU.Backends.IL
///
public static class ILEmitterExtensions
{
- private static readonly MethodInfo GetHashCodeInfo = typeof(object).GetMethod(
- nameof(object.GetHashCode),
- BindingFlags.Public | BindingFlags.Instance);
- private static readonly MethodInfo EqualsInfo = typeof(object).GetMethod(
- nameof(object.Equals),
- BindingFlags.Public | BindingFlags.Instance);
+ private static readonly MethodInfo GetHashCodeInfo =
+ typeof(object).GetMethod(
+ nameof(object.GetHashCode),
+ BindingFlags.Public | BindingFlags.Instance)
+ .ThrowIfNull();
+ private static readonly MethodInfo EqualsInfo =
+ typeof(object).GetMethod(
+ nameof(object.Equals),
+ BindingFlags.Public | BindingFlags.Instance)
+ .ThrowIfNull();
///
/// Generates hash code and equals functions for the given fields.
@@ -70,7 +75,8 @@ public static MethodInfo GenerateHashCode(
var fieldHashCode = field.FieldType.GetMethod(
GetHashCodeInfo.Name,
- BindingFlags.Public | BindingFlags.Instance);
+ BindingFlags.Public | BindingFlags.Instance)
+ .AsNotNull();
if (!field.FieldType.IsValueType)
{
emitter.Emit(OpCodes.Ldfld, field);
@@ -131,7 +137,8 @@ public static MethodInfo GenerateEquals(
emitter.EmitCall(field.FieldType.GetMethod(
EqualsInfo.Name,
- new Type[] { field.FieldType }));
+ new Type[] { field.FieldType })
+ .AsNotNull());
// IMPORTANT: Each field can branch to the false label. However, if we
// have a large number of fields, depending on the number of IL bytes we
diff --git a/Src/ILGPU/Backends/OpenCL/CLArgumentMapper.cs b/Src/ILGPU/Backends/OpenCL/CLArgumentMapper.cs
index 4e420fe10..2dd330bc9 100644
--- a/Src/ILGPU/Backends/OpenCL/CLArgumentMapper.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLArgumentMapper.cs
@@ -15,6 +15,7 @@
using ILGPU.IR.Types;
using ILGPU.Runtime;
using ILGPU.Runtime.OpenCL;
+using ILGPU.Util;
using System;
using System.Reflection;
using System.Reflection.Emit;
@@ -35,7 +36,8 @@ public sealed class CLArgumentMapper : ViewArgumentMapper
private static readonly MethodInfo SetKernelArgumentMethod =
typeof(CLAPI).GetMethod(
nameof(CLAPI.SetKernelArgumentUnsafeWithKernel),
- BindingFlags.Public | BindingFlags.Instance);
+ BindingFlags.Public | BindingFlags.Instance)
+ .ThrowIfNull();
#endregion
diff --git a/Src/ILGPU/Backends/OpenCL/CLBackend.cs b/Src/ILGPU/Backends/OpenCL/CLBackend.cs
index 8c12a523d..95f4097f5 100644
--- a/Src/ILGPU/Backends/OpenCL/CLBackend.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLBackend.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2022 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLBackend.cs
@@ -16,6 +16,7 @@
using ILGPU.IR.Transformations;
using ILGPU.Runtime;
using ILGPU.Runtime.OpenCL;
+using ILGPU.Util;
using System.Text;
namespace ILGPU.Backends.OpenCL
@@ -68,7 +69,7 @@ public CLBackend(
CLStdVersion = clStdVersion;
InitIntrinsicProvider();
- InitializeKernelTransformers( builder =>
+ InitializeKernelTransformers(builder =>
{
var transformerBuilder = Transformer.CreateBuilder(
TransformerConfiguration.Empty);
@@ -110,13 +111,13 @@ public CLBackend(
/// Returns the associated .
///
public new CLArgumentMapper ArgumentMapper =>
- base.ArgumentMapper as CLArgumentMapper;
+ base.ArgumentMapper.AsNotNullCast();
///
/// Returns the capabilities of this accelerator.
///
public new CLCapabilityContext Capabilities =>
- base.Capabilities as CLCapabilityContext;
+ base.Capabilities.AsNotNullCast();
#endregion
@@ -162,7 +163,7 @@ protected override StringBuilder CreateKernelBuilder(
data = new CLCodeGenerator.GeneratorArgs(
this,
typeGenerator,
- entryPoint as SeparateViewEntryPoint,
+ entryPoint.AsNotNullCast(),
backendContext.SharedAllocations,
backendContext.DynamicSharedAllocations);
return builder;
@@ -192,7 +193,7 @@ protected override CLCodeGenerator CreateKernelCodeGenerator(
///
protected override CompiledKernel CreateKernel(
EntryPoint entryPoint,
- CompiledKernel.KernelInfo kernelInfo,
+ CompiledKernel.KernelInfo? kernelInfo,
StringBuilder builder,
CLCodeGenerator.GeneratorArgs data)
{
@@ -208,7 +209,7 @@ protected override CompiledKernel CreateKernel(
var clSource = builder.ToString();
return new CLCompiledKernel(
Context,
- entryPoint as SeparateViewEntryPoint,
+ entryPoint.AsNotNullCast(),
kernelInfo,
clSource,
CLStdVersion);
diff --git a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Emitter.cs b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Emitter.cs
index 59ddf58db..5fa76fb1a 100644
--- a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Emitter.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Emitter.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLCodeGenerator.Emitter.cs
@@ -465,7 +465,7 @@ public void AppendOperation(RawString operation) =>
/// The string format arguments.
public void AppendOperation(
RawString operation,
- params object[] arguments)
+ params object?[] arguments)
{
var formatExpression = operation.Value;
if (!FormatString.TryParse(formatExpression, out var expressions))
@@ -495,49 +495,49 @@ public void AppendOperation(
{
if (!expression.HasArgument)
{
- AppendOperation(expression.String);
+ AppendOperation(expression.String.AsNotNull());
}
else
{
var argument = arguments[expression.Argument];
- var argumentType = argument.GetType();
+ var argumentType = argument?.GetType();
switch (Type.GetTypeCode(argumentType))
{
case TypeCode.Boolean:
- AppendConstant((bool)argument ? 1 : 0);
+ AppendConstant((bool)argument.AsNotNull() ? 1 : 0);
break;
case TypeCode.SByte:
- AppendConstant((sbyte)argument);
+ AppendConstant((sbyte)argument.AsNotNull());
break;
case TypeCode.Byte:
- AppendConstant((byte)argument);
+ AppendConstant((byte)argument.AsNotNull());
break;
case TypeCode.Int16:
- AppendConstant((short)argument);
+ AppendConstant((short)argument.AsNotNull());
break;
case TypeCode.UInt16:
- AppendConstant((ushort)argument);
+ AppendConstant((ushort)argument.AsNotNull());
break;
case TypeCode.Int32:
- AppendConstant((int)argument);
+ AppendConstant((int)argument.AsNotNull());
break;
case TypeCode.UInt32:
- AppendConstant((uint)argument);
+ AppendConstant((uint)argument.AsNotNull());
break;
case TypeCode.Int64:
- AppendConstant((long)argument);
+ AppendConstant((long)argument.AsNotNull());
break;
case TypeCode.UInt64:
- AppendConstant((ulong)argument);
+ AppendConstant((ulong)argument.AsNotNull());
break;
case TypeCode.Single:
- AppendConstant((float)argument);
+ AppendConstant((float)argument.AsNotNull());
break;
case TypeCode.Double:
- AppendConstant((double)argument);
+ AppendConstant((double)argument.AsNotNull());
break;
case TypeCode.String:
- AppendOperation((string)argument);
+ AppendOperation((string)argument.AsNotNull());
break;
default:
if (argument is Variable variable)
@@ -552,13 +552,13 @@ public void AppendOperation(
}
else if (argumentType == typeof(Half))
{
- AppendConstant((Half)argument);
+ AppendConstant((Half)argument.AsNotNull());
break;
}
throw new NotSupportedException(string.Format(
ErrorMessages.NotSupportedWriteFormatArgumentType,
formatExpression,
- argument.GetType().ToString()));
+ argumentType?.ToString()));
}
}
}
diff --git a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Values.cs b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Values.cs
index fbc810a47..e602844d7 100644
--- a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Values.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Values.cs
@@ -14,7 +14,6 @@
using ILGPU.IR.Values;
using ILGPU.Runtime.OpenCL;
using ILGPU.Util;
-using System;
using System.Runtime.CompilerServices;
namespace ILGPU.Backends.OpenCL
@@ -138,7 +137,7 @@ public void GenerateCode(TernaryArithmeticValue value)
if (!CLInstructions.TryGetArithmeticOperation(
value.Kind,
value.BasicValueType.IsFloat(),
- out string operation))
+ out string? operation))
{
throw new InvalidCodeGenerationException();
}
@@ -593,7 +592,7 @@ public void GenerateCode(SetField value)
private void MakeIntrinsicValue(
Value value,
string operation,
- string args = null)
+ string? args = null)
{
var target = Allocate(value);
using var statement = BeginStatement(target);
@@ -663,7 +662,7 @@ public void GenerateCode(DynamicMemoryLengthValue value)
// Resolve the name of the global variable containing the length of the
// shared dynamic memory buffer.
- var dynamicView = value.GetFirstUseNode().ResolveAs();
+ var dynamicView = value.GetFirstUseNode().ResolveAs().AsNotNull();
var lengthVariableName = GetSharedMemoryAllocationLengthName(dynamicView);
// Load the dynamic memory size (in bytes) from the dynamic length variable
@@ -709,7 +708,7 @@ public void GenerateCode(PredicateBarrier barrier)
if (!CLInstructions.TryGetPredicateBarrier(
barrier.Kind,
- out string operation))
+ out string? operation))
{
throw new InvalidCodeGenerationException();
}
@@ -757,7 +756,7 @@ public void GenerateCode(WarpShuffle shuffle)
if (!CLInstructions.TryGetShuffleOperation(
Backend.Vendor,
shuffle.Kind,
- out string operation))
+ out string? operation))
{
throw new InvalidCodeGenerationException();
}
diff --git a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Views.cs b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Views.cs
index 6e2071726..e5a73d142 100644
--- a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Views.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.Views.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLCodeGenerator.Views.cs
@@ -11,6 +11,7 @@
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
namespace ILGPU.Backends.OpenCL
{
@@ -21,7 +22,7 @@ public void GenerateCode(LoadElementAddress value)
{
var elementIndex = LoadAs(value.Offset);
var source = Load(value.Source);
- var target = AllocatePointerType(value.Type as PointerType);
+ var target = AllocatePointerType(value.Type.AsNotNullCast());
using (var statement = BeginStatement(target))
{
@@ -36,20 +37,20 @@ public void GenerateCode(LoadElementAddress value)
///
public void GenerateCode(AddressSpaceCast value)
{
- var targetType = value.TargetType as AddressSpaceType;
+ var targetType = value.TargetType.AsNotNullCast();
var source = Load(value.Value);
var target = Allocate(value);
bool isOperation = CLInstructions.TryGetAddressSpaceCast(
value.TargetAddressSpace,
- out string operation);
+ out string? operation);
void GeneratePointerCast(StatementEmitter statement)
{
if (isOperation)
{
// There is a specific cast operation
- statement.AppendCommand(operation);
+ statement.AppendCommand(operation.AsNotNull());
statement.BeginArguments();
}
else
diff --git a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.cs b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.cs
index f6fd26159..6c8273db8 100644
--- a/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLCodeGenerator.cs
@@ -16,7 +16,9 @@
using ILGPU.IR.Analyses.TraversalOrders;
using ILGPU.IR.Intrinsics;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace ILGPU.Backends.OpenCL
@@ -151,7 +153,7 @@ protected interface IParametersSetupLogic
///
/// The intrinsic parameter.
/// The allocated variable (if any).
- Variable HandleIntrinsicParameter(int parameterOffset, Parameter parameter);
+ Variable? HandleIntrinsicParameter(int parameterOffset, Parameter parameter);
}
///
@@ -225,7 +227,9 @@ public void Allocate(BasicBlock block, PhiValue phiValue)
/// The block.
/// The variables to declare (if any).
/// True, if there are some phi variables to declare.
- public bool TryGetPhis(BasicBlock block, out List phisToDeclare) =>
+ public bool TryGetPhis(
+ BasicBlock block,
+ [NotNullWhen(true)] out List? phisToDeclare) =>
phiMapping.TryGetValue(block, out phisToDeclare);
}
@@ -393,7 +397,7 @@ protected void SetupParameters(
foreach (var param in Method.Parameters)
{
- Variable variable;
+ Variable? variable;
if (offset < paramOffset)
{
variable = logic.HandleIntrinsicParameter(offset, param);
@@ -578,7 +582,7 @@ protected void GenerateCodeInternal()
}
// Build terminator
- this.GenerateCodeFor(block.Terminator);
+ this.GenerateCodeFor(block.Terminator.AsNotNull());
Builder.AppendLine();
}
}
diff --git a/Src/ILGPU/Backends/OpenCL/CLCompiledKernel.cs b/Src/ILGPU/Backends/OpenCL/CLCompiledKernel.cs
index 04cec3c19..900377a80 100644
--- a/Src/ILGPU/Backends/OpenCL/CLCompiledKernel.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLCompiledKernel.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLCompiledKernel.cs
@@ -10,6 +10,7 @@
// ---------------------------------------------------------------------------------------
using ILGPU.Backends.EntryPoints;
+using ILGPU.Util;
namespace ILGPU.Backends.OpenCL
{
@@ -31,7 +32,7 @@ public sealed class CLCompiledKernel : CompiledKernel
public CLCompiledKernel(
Context context,
SeparateViewEntryPoint entryPoint,
- KernelInfo info,
+ KernelInfo? info,
string source,
CLCVersion version)
: base(context, entryPoint, info)
@@ -58,7 +59,7 @@ public CLCompiledKernel(
/// Returns the internally used entry point.
///
internal new SeparateViewEntryPoint EntryPoint =>
- base.EntryPoint as SeparateViewEntryPoint;
+ base.EntryPoint.AsNotNullCast();
#endregion
}
diff --git a/Src/ILGPU/Backends/OpenCL/CLFunctionGenerator.cs b/Src/ILGPU/Backends/OpenCL/CLFunctionGenerator.cs
index c41d30d36..9b46a7d11 100644
--- a/Src/ILGPU/Backends/OpenCL/CLFunctionGenerator.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLFunctionGenerator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLFunctionGenerator.cs
@@ -62,7 +62,7 @@ public string GetParameterType(Parameter parameter) =>
///
/// This setup logic does not support intrinsic parameters.
///
- public Variable HandleIntrinsicParameter(
+ public Variable? HandleIntrinsicParameter(
int parameterOffset,
Parameter parameter) =>
null;
diff --git a/Src/ILGPU/Backends/OpenCL/CLInstructions.Data.cs b/Src/ILGPU/Backends/OpenCL/CLInstructions.Data.cs
index 031a8dc1b..2c68a32da 100644
--- a/Src/ILGPU/Backends/OpenCL/CLInstructions.Data.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLInstructions.Data.cs
@@ -181,7 +181,7 @@ partial class CLInstructions
"private",
};
- private static readonly string[] AddressSpaceCastOperations =
+ private static readonly string?[] AddressSpaceCastOperations =
{
null,
"to_global",
@@ -195,7 +195,7 @@ partial class CLInstructions
"work_group_barrier",
};
- private static readonly string[] PredicateBarrierOperations =
+ private static readonly string?[] PredicateBarrierOperations =
{
null,
"work_group_all",
diff --git a/Src/ILGPU/Backends/OpenCL/CLInstructions.cs b/Src/ILGPU/Backends/OpenCL/CLInstructions.cs
index eeae85c1e..33c56ab08 100644
--- a/Src/ILGPU/Backends/OpenCL/CLInstructions.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLInstructions.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLInstructions.cs
@@ -12,6 +12,7 @@
using ILGPU.IR;
using ILGPU.IR.Values;
using ILGPU.Runtime.OpenCL;
+using System.Diagnostics.CodeAnalysis;
namespace ILGPU.Backends.OpenCL
{
@@ -44,7 +45,7 @@ public static string GetAddressSpacePrefix(MemoryAddressSpace addressSpace) =>
/// True, if an operation could be resolved.
public static bool TryGetAddressSpaceCast(
MemoryAddressSpace addressSpace,
- out string operation)
+ [NotNullWhen(true)] out string? operation)
{
operation = AddressSpaceCastOperations[(int)addressSpace];
return operation != null;
@@ -109,7 +110,7 @@ public static string GetArithmeticOperation(
public static bool TryGetArithmeticOperation(
TernaryArithmeticKind kind,
bool isFloat,
- out string operation) =>
+ [NotNullWhen(true)] out string? operation) =>
TernaryArithmeticOperations.TryGetValue((kind, isFloat), out operation);
///
@@ -136,7 +137,7 @@ public static string GetBarrier(BarrierKind kind) =>
/// True, if the operation could be resolved.
public static bool TryGetPredicateBarrier(
PredicateBarrierKind kind,
- out string operation)
+ [NotNullWhen(true)] out string? operation)
{
operation = PredicateBarrierOperations[(int)kind];
return operation != null;
@@ -174,7 +175,7 @@ public static string GetMemoryFenceFlags(bool isGlobal) =>
public static bool TryGetShuffleOperation(
CLDeviceVendor vendor,
ShuffleKind kind,
- out string operation) =>
+ [NotNullWhen(true)] out string? operation) =>
ShuffleOperations.TryGetValue((vendor, kind), out operation);
///
diff --git a/Src/ILGPU/Backends/OpenCL/CLKernelFunctionGenerator.cs b/Src/ILGPU/Backends/OpenCL/CLKernelFunctionGenerator.cs
index 878529a06..7257df58d 100644
--- a/Src/ILGPU/Backends/OpenCL/CLKernelFunctionGenerator.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLKernelFunctionGenerator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2022 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLKernelFunctionGenerator.cs
@@ -67,12 +67,12 @@ public KernelParameterSetupLogic(CLKernelFunctionGenerator generator)
///
/// Returns the main index variable.
///
- public Variable IndexVariable { get; private set; }
+ public Variable? IndexVariable { get; private set; }
///
/// Returns the length variable of implicitly grouped kernels.
///
- public Variable LengthVariable { get; private set; }
+ public Variable? LengthVariable { get; private set; }
///
/// Returns the parent type generator.
@@ -88,7 +88,7 @@ public string GetParameterType(Parameter parameter) =>
///
/// Updates index and length variables.
///
- public Variable HandleIntrinsicParameter(
+ public Variable? HandleIntrinsicParameter(
int parameterOffset,
Parameter parameter)
{
@@ -476,11 +476,12 @@ private void EmitImplicitKernelIndex(
///
/// The length variable of implicitly grouped kernels.
///
- private void SetupKernelIndex(Variable indexVariable, Variable lengthVariable)
+ private void SetupKernelIndex(Variable? indexVariable, Variable? lengthVariable)
{
if (EntryPoint.IsExplicitlyGrouped)
return;
Debug.Assert(indexVariable != null, "Invalid index variable");
+ Debug.Assert(lengthVariable != null, "Invalid length variable");
if (EntryPoint.IndexType == IndexType.Index1D)
{
diff --git a/Src/ILGPU/Backends/OpenCL/CLKernelTypeGenerator.cs b/Src/ILGPU/Backends/OpenCL/CLKernelTypeGenerator.cs
index d87c696ca..1d3cc0885 100644
--- a/Src/ILGPU/Backends/OpenCL/CLKernelTypeGenerator.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLKernelTypeGenerator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLKernelTypeGenerator.cs
@@ -13,6 +13,7 @@
using ILGPU.IR;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
@@ -150,7 +151,7 @@ public void Register(Parameter parameter)
// Convert the kernel type using a specific type converter
structureType = typeConverter.ConvertType(
TypeGenerator.TypeContext,
- structureType) as StructureType;
+ structureType).AsNotNullCast();
// Register internally
parameterTypes[parameter.Index] = (structureType, clName);
diff --git a/Src/ILGPU/Backends/OpenCL/CLTypeGenerator.cs b/Src/ILGPU/Backends/OpenCL/CLTypeGenerator.cs
index ea9731999..b17e52f4c 100644
--- a/Src/ILGPU/Backends/OpenCL/CLTypeGenerator.cs
+++ b/Src/ILGPU/Backends/OpenCL/CLTypeGenerator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLTypeGenerator.cs
@@ -65,7 +65,7 @@ public sealed class CLTypeGenerator : DisposeBase, ICLTypeGenerator
///
private static readonly ImmutableArray BasicTypeMapping =
ImmutableArray.Create(
- null,
+ string.Empty,
"bool",
"char",
"short",
@@ -97,7 +97,7 @@ public sealed class CLTypeGenerator : DisposeBase, ICLTypeGenerator
///
/// Maps arithmetic-basic value types to atomic OpenCL language types.
///
- private static readonly ImmutableArray AtomicTypeMapping =
+ private static readonly ImmutableArray AtomicTypeMapping =
ImmutableArray.Create(
string.Empty,
null,
@@ -142,7 +142,7 @@ public string GetBasicValueType(ArithmeticBasicValueType basicValueType) =>
///
/// The basic-value type to resolve.
/// The resolved atomic OpenCL type name.
- public string GetAtomicType(ArithmeticBasicValueType basicValueType) =>
+ public string? GetAtomicType(ArithmeticBasicValueType basicValueType) =>
basicValueType == ArithmeticBasicValueType.Float16 && !Capabilities.Float16
? throw CLCapabilityContext.GetNotSupportedFloat16Exception()
: basicValueType == ArithmeticBasicValueType.Float64 && !Capabilities.Float64
@@ -240,7 +240,7 @@ public string this[TypeNode typeNode]
// Synchronize all accesses below using a read/write scope
using var readWriteScope = readerWriterLock.EnterUpgradeableReadScope();
- if (mapping.TryGetValue(typeNode, out string typeName))
+ if (mapping.TryGetValue(typeNode, out string? typeName))
return typeName;
// Synchronize all accesses below using a write scope
@@ -269,7 +269,7 @@ public string this[TypeNode typeNode]
private string GetOrCreateType(TypeNode typeNode)
{
Debug.Assert(!(typeNode is ViewType), "Invalid view type");
- if (mapping.TryGetValue(typeNode, out string clName))
+ if (mapping.TryGetValue(typeNode, out string? clName))
return clName;
if (typeNode is PointerType pointerType)
diff --git a/Src/ILGPU/Backends/OpenCL/Transformations/CLAcceleratorSpecializer.cs b/Src/ILGPU/Backends/OpenCL/Transformations/CLAcceleratorSpecializer.cs
index fd45a41e7..5cb71f142 100644
--- a/Src/ILGPU/Backends/OpenCL/Transformations/CLAcceleratorSpecializer.cs
+++ b/Src/ILGPU/Backends/OpenCL/Transformations/CLAcceleratorSpecializer.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: CLAcceleratorSpecializer.cs
@@ -11,11 +11,11 @@
using ILGPU.Frontend;
using ILGPU.IR;
-using ILGPU.IR.Rewriting;
using ILGPU.IR.Transformations;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
using ILGPU.Runtime;
+using ILGPU.Util;
using System.Reflection;
namespace ILGPU.Backends.OpenCL.Transformations
@@ -44,7 +44,8 @@ private static unsafe void PrintF(string str)
private static readonly MethodInfo PrintFMethod =
typeof(CLAcceleratorSpecializer).GetMethod(
nameof(PrintF),
- BindingFlags.Static | BindingFlags.NonPublic);
+ BindingFlags.Static | BindingFlags.NonPublic)
+ .ThrowIfNull();
#endregion
diff --git a/Src/ILGPU/Backends/PTX/PTXBackend.cs b/Src/ILGPU/Backends/PTX/PTXBackend.cs
index ebf1e8735..b9b640462 100644
--- a/Src/ILGPU/Backends/PTX/PTXBackend.cs
+++ b/Src/ILGPU/Backends/PTX/PTXBackend.cs
@@ -16,6 +16,7 @@
using ILGPU.IR.Transformations;
using ILGPU.Runtime;
using ILGPU.Runtime.Cuda;
+using ILGPU.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -109,7 +110,7 @@ public PTXBackend(
CudaCapabilityContext capabilities,
CudaArchitecture architecture,
CudaInstructionSet instructionSet,
- NvvmAPI nvvmAPI)
+ NvvmAPI? nvvmAPI)
: base(
context,
capabilities,
@@ -174,18 +175,18 @@ protected override void Dispose(bool disposing)
/// Returns the associated .
///
public new PTXArgumentMapper ArgumentMapper =>
- base.ArgumentMapper as PTXArgumentMapper;
+ base.ArgumentMapper.AsNotNullCast();
///
/// Returns the supported capabilities.
///
public new CudaCapabilityContext Capabilities =>
- base.Capabilities as CudaCapabilityContext;
+ base.Capabilities.AsNotNullCast();
///
/// Returns the NVVM API instance (if available).
///
- public NvvmAPI NvvmAPI { get; private set; }
+ public NvvmAPI? NvvmAPI { get; private set; }
#endregion
@@ -290,7 +291,7 @@ protected override PTXCodeGenerator CreateKernelCodeGenerator(
///
protected override CompiledKernel CreateKernel(
EntryPoint entryPoint,
- CompiledKernel.KernelInfo kernelInfo,
+ CompiledKernel.KernelInfo? kernelInfo,
StringBuilder builder,
PTXCodeGenerator.GeneratorArgs data)
{
@@ -388,7 +389,7 @@ private unsafe void GenerateLibDeviceCode(
if (result == NvvmResult.NVVM_SUCCESS)
{
var compiledString =
- compiledPTX
+ compiledPTX.AsNotNull()
.Replace(".version", "//.version")
.Replace(".target", "//.target")
.Replace(".address_size", "//.address_size");
diff --git a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Emitter.cs b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Emitter.cs
index e0b286baa..dbb529153 100644
--- a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Emitter.cs
+++ b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Emitter.cs
@@ -11,6 +11,7 @@
using ILGPU.IR;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
@@ -204,7 +205,7 @@ public void AppendArgument(PrimitiveRegister argument)
if (argument is ConstantRegister constantRegister)
AppendArgument(constantRegister);
else
- AppendArgument(argument as HardwareRegister);
+ AppendArgument(argument.AsNotNullCast());
}
///
@@ -485,7 +486,7 @@ public PredicateScope(HardwareRegister predicateRegister)
///
/// The associated register allocator.
///
- public PTXRegisterAllocator RegisterAllocator { get; }
+ public PTXRegisterAllocator? RegisterAllocator { get; }
///
/// The allocated predicate register.
@@ -626,8 +627,11 @@ public void EmitComplexCommand(
// Invoke final emitter
var primitiveRegisters = new PrimitiveRegister[registers.Length];
for (int i = 0, e = registers.Length; i < e; ++i)
- primitiveRegisters[i] = registers[i] as PrimitiveRegister;
- command = emitter.AdjustCommand(command, primitiveRegisters);
+ {
+ primitiveRegisters[i] =
+ registers[i].AsNotNullCast();
+ command = emitter.AdjustCommand(command, primitiveRegisters);
+ }
using (var commandEmitter = BeginCommand(command))
emitter.Emit(commandEmitter, primitiveRegisters);
break;
@@ -638,7 +642,8 @@ public void EmitComplexCommand(
for (int j = 0, e2 = registers.Length; j < e2; ++j)
{
elementRegisters[j] =
- (registers[j] as CompoundRegister).Children[i];
+ registers[j].AsNotNullCast()
+ .Children[i];
}
EmitComplexCommand(command, emitter, elementRegisters);
}
@@ -680,7 +685,7 @@ public void EmitComplexCommandWithOffsets(
this,
command,
structureRegister.Children[access.Index]
- as PrimitiveRegister,
+ .AsNotNullCast(),
offset + fieldOffset);
}
break;
@@ -869,7 +874,7 @@ public void EmitIOLoad(
where TIOEmitter : struct, IIOEmitter
where T : struct
{
- HardwareRegister originalRegister = null;
+ HardwareRegister? originalRegister = null;
// We need a temporary 32bit register for predicate conversion at this point:
// 1) load value into temporary register
// 2) convert loaded value into predicate
@@ -913,7 +918,7 @@ public void EmitIOStore(
// We need a temporary 32bit register for predicate conversion at this point:
// 1) convert current predicate into 32bit integer
// 2) store the converted value from the temporary register
- PrimitiveRegister originalRegister = null;
+ PrimitiveRegister? originalRegister = null;
if (register.BasicValueType == BasicValueType.Int1)
{
originalRegister = register;
@@ -922,7 +927,7 @@ public void EmitIOStore(
// Convert predicate
ConvertPredicateToValue(
originalRegister,
- register as HardwareRegister);
+ register.AsNotNullCast());
}
// Emit store
@@ -930,7 +935,7 @@ public void EmitIOStore(
// Free temp register
if (originalRegister != null)
- FreeRegister(register as HardwareRegister);
+ FreeRegister(register.AsNotNullCast());
}
///
@@ -1077,7 +1082,7 @@ public HardwareRegister EnsureHardwareRegister(PrimitiveRegister register)
{
command.AppendRegisterMovementSuffix(register.BasicValueType);
command.AppendArgument(hardwareRegister);
- command.AppendArgument(register as ConstantRegister);
+ command.AppendArgument(register.AsNotNullCast());
}
return hardwareRegister;
}
diff --git a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Values.cs b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Values.cs
index 7972709a8..6672d4863 100644
--- a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Values.cs
+++ b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Values.cs
@@ -329,20 +329,24 @@ public void GenerateCode(Predicate predicate)
new PredicateConfiguration(conditionRegister, true)))
{
statement1.AppendSuffix(BasicValueType.Int1);
- statement1.AppendArgument(targetRegister as PrimitiveRegister);
- statement1.AppendArgument(trueValue as PrimitiveRegister);
+ statement1.AppendArgument(
+ targetRegister.AsNotNullCast());
+ statement1.AppendArgument(
+ trueValue.AsNotNullCast());
}
using var statement2 = BeginMove(
new PredicateConfiguration(conditionRegister, false));
statement2.AppendSuffix(BasicValueType.Int1);
- statement2.AppendArgument(targetRegister as PrimitiveRegister);
- statement2.AppendArgument(falseValue as PrimitiveRegister);
+ statement2.AppendArgument(
+ targetRegister.AsNotNullCast());
+ statement2.AppendArgument(
+ falseValue.AsNotNullCast());
}
else
{
EmitComplexCommand(
- null,
+ string.Empty,
new PredicateEmitter(condition),
targetRegister,
trueValue,
@@ -369,10 +373,10 @@ public void GenerateCode(GenericAtomic atomic)
var targetRegister = requiresResult ? AllocateHardware(atomic) : default;
using var command = BeginCommand(atomicOperation);
command.AppendNonLocalAddressSpace(
- (atomic.Target.Type as AddressSpaceType).AddressSpace);
+ atomic.Target.Type.AsNotNullCast().AddressSpace);
command.AppendSuffix(suffix);
if (requiresResult)
- command.AppendArgument(targetRegister);
+ command.AppendArgument(targetRegister.AsNotNull());
command.AppendArgumentValue(target);
command.AppendArgument(value);
}
@@ -388,7 +392,7 @@ public void GenerateCode(AtomicCAS atomicCAS)
using var command = BeginCommand(PTXInstructions.AtomicCASOperation);
command.AppendNonLocalAddressSpace(
- (atomicCAS.Target.Type as AddressSpaceType).AddressSpace);
+ atomicCAS.Target.Type.AsNotNullCast().AddressSpace);
command.AppendSuffix(atomicCAS.BasicValueType);
command.AppendArgument(targetRegister);
command.AppendArgumentValue(target);
@@ -474,7 +478,7 @@ public void Emit(
codeGenerator.EmitIOLoad(
Emitter,
command,
- register as HardwareRegister,
+ register.AsNotNullCast(),
offset);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -498,7 +502,7 @@ public void Emit(
public void GenerateCode(Load load)
{
var address = LoadHardware(load.Source);
- var sourceType = load.Source.Type as PointerType;
+ var sourceType = load.Source.Type.AsNotNullCast();
var targetRegister = Allocate(load);
EmitVectorizedCommand(
@@ -598,7 +602,7 @@ public void Emit(
public void GenerateCode(Store store)
{
var address = LoadHardware(store.Target);
- var targetType = store.Target.Type as PointerType;
+ var targetType = store.Target.Type.AsNotNullCast();
var value = Load(store.Value);
EmitVectorizedCommand(
@@ -802,7 +806,7 @@ public void GenerateCode(StringValue value)
{
// Check for already existing global constant
var key = (value.Encoding, value.String);
- if (!stringConstants.TryGetValue(key, out string stringBinding))
+ if (!stringConstants.TryGetValue(key, out string? stringBinding))
{
stringBinding = "__strconst" + value.Id;
stringConstants.Add(key, stringBinding);
@@ -901,7 +905,7 @@ public void GenerateCode(GetField value)
Bind(
value,
new CompoundRegister(
- value.Type as StructureType,
+ value.Type.AsNotNullCast(),
childRegisters.MoveToImmutable()));
}
}
@@ -1251,7 +1255,7 @@ public void GenerateCode(LanguageEmitValue emit)
if (emit.UsingRefParams)
{
// If there is an input, initialize with the supplied argument value.
- var pointerType = argument.Type as PointerType;
+ var pointerType = argument.Type.AsNotNullCast();
var pointerElementType = pointerType.ElementType;
var targetRegister = AllocateRegister(
@@ -1275,7 +1279,7 @@ public void GenerateCode(LanguageEmitValue emit)
registers.Add(
emit.IsOutputArgument(argumentIdx)
? AllocateRegister(ResolveRegisterDescription(
- (argument.Type as PointerType).ElementType))
+ argument.Type.AsNotNullCast().ElementType))
: LoadPrimitive(argument));
}
}
@@ -1293,7 +1297,7 @@ public void GenerateCode(LanguageEmitValue emit)
}
else
{
- emitter.AppendRawString(expression.String);
+ emitter.AppendRawString(expression.String.AsNotNull());
}
}
}
@@ -1305,7 +1309,7 @@ public void GenerateCode(LanguageEmitValue emit)
{
var outputArgument = emit.Nodes[argumentIdx];
var address = LoadHardware(outputArgument);
- var targetType = outputArgument.Type as PointerType;
+ var targetType = outputArgument.Type.AsNotNullCast();
var newValue = registers[argumentIdx];
EmitVectorizedCommand(
diff --git a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Views.cs b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Views.cs
index b306e651f..6006b89e3 100644
--- a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Views.cs
+++ b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.Views.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXCodeGenerator.Views.cs
@@ -12,6 +12,7 @@
using ILGPU.IR;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System.Diagnostics;
namespace ILGPU.Backends.PTX
@@ -26,7 +27,7 @@ public void GenerateCode(LoadElementAddress value)
Debug.Assert(value.IsPointerAccess, "Invalid pointer access");
var address = LoadPrimitive(value.Source);
- var sourceType = value.Source.Type as AddressSpaceType;
+ var sourceType = value.Source.Type.AsNotNullCast();
var elementSize = sourceType.ElementType.Size;
if (value.Is32BitAccess)
diff --git a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.cs b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.cs
index e23cad594..bd9436f9e 100644
--- a/Src/ILGPU/Backends/PTX/PTXCodeGenerator.cs
+++ b/Src/ILGPU/Backends/PTX/PTXCodeGenerator.cs
@@ -17,6 +17,7 @@
using ILGPU.IR.Types;
using ILGPU.IR.Values;
using ILGPU.Runtime.Cuda;
+using ILGPU.Util;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
@@ -172,7 +173,7 @@ internal interface IParameterSetupLogic
///
/// The intrinsic parameter.
/// The allocated register (if any).
- Register HandleIntrinsicParameter(int parameterOffset, Parameter parameter);
+ Register? HandleIntrinsicParameter(int parameterOffset, Parameter parameter);
}
///
@@ -183,7 +184,7 @@ internal interface IParameterSetupLogic
///
/// Does not handle intrinsic parameters.
///
- public Register HandleIntrinsicParameter(
+ public Register? HandleIntrinsicParameter(
int parameterOffset,
Parameter parameter) =>
null;
@@ -229,7 +230,7 @@ public void Allocate(BasicBlock block, PhiValue phiValue) =>
///
private static readonly ImmutableArray BasicSuffixes =
ImmutableArray.Create(
- default, "pred",
+ string.Empty, "pred",
"b8", "b16", "b32", "b64",
"f16", "f32", "f64");
@@ -360,7 +361,7 @@ internal PTXCodeGenerator(in GeneratorArgs args, Method method, Allocas allocas)
///
/// Returns the associated backend.
///
- public new PTXBackend Backend => base.Backend as PTXBackend;
+ public new PTXBackend Backend => base.Backend.AsNotNullCast();
///
/// Returns the associated method.
@@ -598,7 +599,7 @@ protected void GenerateCodeInternal(int registerOffset)
}
// Build terminator
- this.GenerateCodeFor(block.Terminator);
+ this.GenerateCodeFor(block.Terminator.AsNotNull());
Builder.AppendLine();
}
@@ -690,7 +691,7 @@ internal List SetupParameters(
foreach (var param in Method.Parameters)
{
- Register register = null;
+ Register? register = null;
if (offset < paramOffset)
{
register = logic.HandleIntrinsicParameter(offset, param);
@@ -792,7 +793,7 @@ public readonly void Emit(
// using the previously allocated temp register
codeGenerator.CreateAddressSpaceCast(
TempRegister,
- primitiveRegister as HardwareRegister,
+ primitiveRegister.AsNotNullCast(),
MemoryAddressSpace.Generic,
addressSpaceType.AddressSpace);
}
@@ -830,7 +831,7 @@ public readonly void Emit(
codeGenerator.EmitIOLoad(
Emitter,
command,
- primitiveRegister as HardwareRegister,
+ primitiveRegister.AsNotNullCast(),
offset);
}
diff --git a/Src/ILGPU/Backends/PTX/PTXCompiledKernel.cs b/Src/ILGPU/Backends/PTX/PTXCompiledKernel.cs
index 58353f5ea..606f49026 100644
--- a/Src/ILGPU/Backends/PTX/PTXCompiledKernel.cs
+++ b/Src/ILGPU/Backends/PTX/PTXCompiledKernel.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXCompiledKernel.cs
@@ -30,7 +30,7 @@ public sealed class PTXCompiledKernel : CompiledKernel
internal PTXCompiledKernel(
Context context,
EntryPoint entryPoint,
- KernelInfo info,
+ KernelInfo? info,
string ptxAssembly)
: base(context, entryPoint, info)
{
diff --git a/Src/ILGPU/Backends/PTX/PTXDebugInfoGenerator.cs b/Src/ILGPU/Backends/PTX/PTXDebugInfoGenerator.cs
index e0851eeaa..331a8589a 100644
--- a/Src/ILGPU/Backends/PTX/PTXDebugInfoGenerator.cs
+++ b/Src/ILGPU/Backends/PTX/PTXDebugInfoGenerator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXDebugInfoGenerator.cs
@@ -45,7 +45,7 @@ internal PTXDebugInfoGeneratorScope(PTXDebugInfoGenerator parent)
///
/// Returns the current location.
///
- public FileLocation Current { get; private set; }
+ public FileLocation? Current { get; private set; }
#endregion
diff --git a/Src/ILGPU/Backends/PTX/PTXInstructions.cs b/Src/ILGPU/Backends/PTX/PTXInstructions.cs
index d432c2b3f..33b356e5b 100644
--- a/Src/ILGPU/Backends/PTX/PTXInstructions.cs
+++ b/Src/ILGPU/Backends/PTX/PTXInstructions.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXInstructions.cs
@@ -54,14 +54,14 @@ public static string GetCompareOperation(
{
if (CompareUnorderedFloatOperations.TryGetValue(
(kind, type),
- out string operation))
+ out string? operation))
{
return operation;
}
}
else
{
- if (CompareOperations.TryGetValue((kind, type), out string operation))
+ if (CompareOperations.TryGetValue((kind, type), out string? operation))
return operation;
}
throw new NotSupportedIntrinsicException(kind.ToString());
@@ -76,7 +76,7 @@ public static string GetCompareOperation(
public static string GetConvertOperation(
ArithmeticBasicValueType source,
ArithmeticBasicValueType target) =>
- ConvertOperations.TryGetValue((source, target), out string operation)
+ ConvertOperations.TryGetValue((source, target), out string? operation)
? operation
: throw new NotSupportedIntrinsicException($"{source} -> {target}");
@@ -111,7 +111,7 @@ public static string GetArithmeticOperation(
return fastMath &&
UnaryArithmeticOperationsFastMath.TryGetValue(
key,
- out string operation) ||
+ out string? operation) ||
UnaryArithmeticOperations.TryGetValue(key, out operation)
? operation
: throw new NotSupportedIntrinsicException(kind.ToString());
@@ -148,7 +148,7 @@ public static string GetArithmeticOperation(
return fastMath &&
BinaryArithmeticOperationsFastMath.TryGetValue(
key,
- out string operation) ||
+ out string? operation) ||
BinaryArithmeticOperations.TryGetValue(key, out operation)
? operation
: throw new NotSupportedIntrinsicException(kind.ToString());
@@ -163,7 +163,7 @@ public static string GetArithmeticOperation(
public static string GetArithmeticOperation(
TernaryArithmeticKind kind,
ArithmeticBasicValueType type) =>
- TernaryArithmeticOperations.TryGetValue((kind, type), out string operation)
+ TernaryArithmeticOperations.TryGetValue((kind, type), out string? operation)
? operation
: throw new NotSupportedIntrinsicException(kind.ToString());
@@ -174,7 +174,7 @@ public static string GetArithmeticOperation(
/// True, if the return value is required.
/// The resolved atomic operation.
public static string GetAtomicOperation(AtomicKind kind, bool requireResult) =>
- AtomicOperations.TryGetValue((kind, requireResult), out string operation)
+ AtomicOperations.TryGetValue((kind, requireResult), out string? operation)
? operation
: throw new NotSupportedIntrinsicException(kind.ToString());
@@ -187,7 +187,7 @@ public static string GetAtomicOperation(AtomicKind kind, bool requireResult) =>
public static string GetAtomicOperationSuffix(
AtomicKind kind,
ArithmeticBasicValueType type) =>
- AtomicOperationsTypes.TryGetValue((kind, type), out string operation)
+ AtomicOperationsTypes.TryGetValue((kind, type), out string? operation)
? operation
: throw new NotSupportedIntrinsicException(kind.ToString());
@@ -248,7 +248,7 @@ public static string GetShuffleOperation(ShuffleKind kind) =>
/// The number of elements.
/// The vector operation suffix.
public static string GetVectorOperationSuffix(int numElements) =>
- VectorSuffixes.TryGetValue(numElements, out string operation)
+ VectorSuffixes.TryGetValue(numElements, out string? operation)
? operation
: throw new NotSupportedIntrinsicException("v" + numElements.ToString());
}
diff --git a/Src/ILGPU/Backends/PTX/PTXKernelFunctionGenerator.cs b/Src/ILGPU/Backends/PTX/PTXKernelFunctionGenerator.cs
index 113a22072..413f694ba 100644
--- a/Src/ILGPU/Backends/PTX/PTXKernelFunctionGenerator.cs
+++ b/Src/ILGPU/Backends/PTX/PTXKernelFunctionGenerator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXKernelFunctionGenerator.cs
@@ -14,6 +14,7 @@
using ILGPU.IR.Analyses;
using ILGPU.IR.Values;
using ILGPU.Runtime;
+using ILGPU.Util;
using System;
using System.Text;
@@ -47,12 +48,12 @@ public KernelParameterSetupLogic(
///
/// Returns the main index register.
///
- public Register IndexRegister { get; private set; }
+ public Register? IndexRegister { get; private set; }
///
/// Returns the length register of implicitly grouped kernels.
///
- public Register LengthRegister { get; private set; }
+ public Register? LengthRegister { get; private set; }
///
/// Returns the associated register allocator.
@@ -62,7 +63,7 @@ public KernelParameterSetupLogic(
///
/// Updates index and length registers.
///
- public Register HandleIntrinsicParameter(
+ public Register? HandleIntrinsicParameter(
int parameterOffset,
Parameter parameter)
{
@@ -251,7 +252,7 @@ private void EmitImplicitKernelIndex(
///
/// The length register of implicitly grouped kernels.
///
- private void SetupKernelIndex(Register indexRegister, Register lengthRegister)
+ private void SetupKernelIndex(Register? indexRegister, Register? lengthRegister)
{
// Skip this step for grouped kernels
if (EntryPoint.IsExplicitlyGrouped)
@@ -260,19 +261,19 @@ private void SetupKernelIndex(Register indexRegister, Register lengthRegister)
{
EmitImplicitKernelIndex(
0,
- indexRegister as PrimitiveRegister,
- lengthRegister as PrimitiveRegister);
+ indexRegister.AsNotNullCast(),
+ lengthRegister.AsNotNullCast());
}
else
{
- var compoundIndex = indexRegister as CompoundRegister;
- var compoundLength = lengthRegister as CompoundRegister;
+ var compoundIndex = indexRegister.AsNotNullCast();
+ var compoundLength = lengthRegister.AsNotNullCast();
for (int i = 0, e = (int)EntryPoint.IndexType; i < e; ++i)
{
EmitImplicitKernelIndex(
i,
- compoundIndex.Children[i] as PrimitiveRegister,
- compoundLength.Children[i] as PrimitiveRegister);
+ compoundIndex.Children[i].AsNotNullCast(),
+ compoundLength.Children[i].AsNotNullCast());
}
}
}
diff --git a/Src/ILGPU/Backends/PTX/Transformations/PTXAcceleratorSpecializer.cs b/Src/ILGPU/Backends/PTX/Transformations/PTXAcceleratorSpecializer.cs
index 660a21d5e..a02f9046f 100644
--- a/Src/ILGPU/Backends/PTX/Transformations/PTXAcceleratorSpecializer.cs
+++ b/Src/ILGPU/Backends/PTX/Transformations/PTXAcceleratorSpecializer.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: PTXAcceleratorSpecializer.cs
@@ -16,6 +16,7 @@
using ILGPU.IR.Values;
using ILGPU.Resources;
using ILGPU.Runtime;
+using ILGPU.Util;
using System.Reflection;
using System.Text;
@@ -60,7 +61,8 @@ private static void AssertFailed(
private static readonly MethodInfo PrintFMethod =
typeof(PTXAcceleratorSpecializer).GetMethod(
nameof(PrintF),
- BindingFlags.Static | BindingFlags.NonPublic);
+ BindingFlags.Static | BindingFlags.NonPublic)
+ .ThrowIfNull();
///
/// A handle to the
@@ -69,7 +71,8 @@ private static void AssertFailed(
private static readonly MethodInfo AssertFailedMethod =
typeof(PTXAcceleratorSpecializer).GetMethod(
nameof(AssertFailed),
- BindingFlags.Static | BindingFlags.NonPublic);
+ BindingFlags.Static | BindingFlags.NonPublic)
+ .ThrowIfNull();
#endregion
@@ -129,7 +132,7 @@ protected override void Implement(
context.Declare(AssertFailedMethod, out var _));
// Move the debug assertion to this block
- var sourceMessage = debugAssert.Message.ResolveAs();
+ var sourceMessage = debugAssert.Message.ResolveAs().AsNotNull();
var message = innerBuilder.CreatePrimitiveValue(
location,
sourceMessage.String,
diff --git a/Src/ILGPU/Backends/PointerViews/LowerPointerViews.cs b/Src/ILGPU/Backends/PointerViews/LowerPointerViews.cs
index 9565cbed2..c9b652d68 100644
--- a/Src/ILGPU/Backends/PointerViews/LowerPointerViews.cs
+++ b/Src/ILGPU/Backends/PointerViews/LowerPointerViews.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: LowerPointerViews.cs
@@ -14,6 +14,7 @@
using ILGPU.IR.Transformations;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
namespace ILGPU.Backends.PointerViews
{
@@ -192,7 +193,8 @@ private static void Lower(
// Compute new length:
// newLength = length * sourceElementSize / targetElementSize;
- var sourceElementType = (typeLowering[value] as ViewType).ElementType;
+ var sourceElementType =
+ typeLowering[value].AsNotNullCast().ElementType;
var sourceElementSize = builder.CreateLongSizeOf(
location,
sourceElementType);
diff --git a/Src/ILGPU/Backends/PointerViews/Utilities.cs b/Src/ILGPU/Backends/PointerViews/Utilities.cs
index 7bdd75f4e..370fae61a 100644
--- a/Src/ILGPU/Backends/PointerViews/Utilities.cs
+++ b/Src/ILGPU/Backends/PointerViews/Utilities.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Utilities.cs
@@ -9,6 +9,7 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
using System.Collections.Generic;
using System.Reflection;
@@ -55,7 +56,8 @@ public static ConstructorInfo GetViewConstructor(Type implType) =>
{
typeof(ArrayView<>).MakeGenericType(
implType.GetGenericArguments()[0])
- });
+ })
+ .ThrowIfNull();
///
/// Returns the pointer field of a view implementation.
@@ -63,7 +65,7 @@ public static ConstructorInfo GetViewConstructor(Type implType) =>
/// The view implementation type.
/// The resolved field.
public static FieldInfo GetPtrField(Type implType) =>
- implType.GetField(nameof(ViewImplementation.Ptr));
+ implType.GetField(nameof(ViewImplementation.Ptr)).ThrowIfNull();
///
/// Returns the length field of a view implementation.
@@ -71,7 +73,7 @@ public static FieldInfo GetPtrField(Type implType) =>
/// The view implementation type.
/// The resolved field.
public static FieldInfo GetLengthField(Type implType) =>
- implType.GetField(nameof(ViewImplementation.Length));
+ implType.GetField(nameof(ViewImplementation.Length)).ThrowIfNull();
///
/// The method handle of the method.
@@ -79,7 +81,8 @@ public static FieldInfo GetLengthField(Type implType) =>
private static readonly MethodInfo GetNativePtrMethodInfo =
typeof(ViewImplementation).GetMethod(
nameof(GetNativePtr),
- BindingFlags.NonPublic | BindingFlags.Static);
+ BindingFlags.NonPublic | BindingFlags.Static)
+ .ThrowIfNull();
///
/// Gets the associated native pointer that is stored inside the given view.
diff --git a/Src/ILGPU/Backends/RegisterAllocator.cs b/Src/ILGPU/Backends/RegisterAllocator.cs
index aa5a7ef20..64e6fbb98 100644
--- a/Src/ILGPU/Backends/RegisterAllocator.cs
+++ b/Src/ILGPU/Backends/RegisterAllocator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: RegisterAllocator.cs
@@ -12,6 +12,7 @@
using ILGPU.IR;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -266,7 +267,7 @@ internal CompoundRegister(
///
/// Returns the underlying type.
///
- public new StructureType Type => base.Type as StructureType;
+ public new StructureType Type => base.Type.AsNotNullCast();
///
/// Returns all child registers.
@@ -412,7 +413,7 @@ public HardwareRegister Allocate(Value node, RegisterDescription description)
{
node.AssertNotNull(node);
- if (aliases.TryGetValue(node, out Value alias))
+ if (aliases.TryGetValue(node, out Value? alias))
node = alias;
if (!registerLookup.TryGetValue(node, out RegisterEntry entry))
{
@@ -420,7 +421,7 @@ public HardwareRegister Allocate(Value node, RegisterDescription description)
entry = new RegisterEntry(targetRegister, node);
registerLookup.Add(node, entry);
}
- var result = entry.Register as HardwareRegister;
+ var result = entry.Register.AsNotNullCast();
node.AssertNotNull(result);
return result;
}
@@ -444,7 +445,7 @@ public HardwareRegister AllocateHardware(Value node)
public Register Allocate(Value node)
{
node.AssertNotNull(node);
- if (aliases.TryGetValue(node, out Value alias))
+ if (aliases.TryGetValue(node, out Value? alias))
node = alias;
if (!registerLookup.TryGetValue(node, out RegisterEntry entry))
{
@@ -504,7 +505,7 @@ public void Alias(Value node, Value aliasNode)
{
node.AssertNotNull(node);
node.AssertNotNull(aliasNode);
- if (aliases.TryGetValue(aliasNode, out Value otherAlias))
+ if (aliases.TryGetValue(aliasNode, out Value? otherAlias))
aliasNode = otherAlias;
aliases[node] = aliasNode;
}
@@ -517,7 +518,7 @@ public void Alias(Value node, Value aliasNode)
public T LoadAs(Value node)
where T : Register
{
- var result = Load(node) as T;
+ var result = Load(node).AsNotNullCast();
node.AssertNotNull(result);
return result;
}
@@ -530,7 +531,7 @@ public T LoadAs(Value node)
public Register Load(Value node)
{
node.AssertNotNull(node);
- if (aliases.TryGetValue(node, out Value alias))
+ if (aliases.TryGetValue(node, out Value? alias))
node = alias;
return registerLookup.TryGetValue(node, out RegisterEntry entry)
? entry.Register
@@ -546,7 +547,7 @@ public PrimitiveRegister LoadPrimitive(Value node)
{
var result = Load(node);
node.AssertNotNull(result);
- return result as PrimitiveRegister;
+ return result.AsNotNullCast();
}
///
@@ -558,7 +559,7 @@ public HardwareRegister LoadHardware(Value node)
{
var result = Load(node);
node.AssertNotNull(result);
- return result as HardwareRegister;
+ return result.AsNotNullCast();
}
///
diff --git a/Src/ILGPU/Backends/SeparateViews/ViewImplementation.cs b/Src/ILGPU/Backends/SeparateViews/ViewImplementation.cs
index 42443ced0..74bbd7c0d 100644
--- a/Src/ILGPU/Backends/SeparateViews/ViewImplementation.cs
+++ b/Src/ILGPU/Backends/SeparateViews/ViewImplementation.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: ViewImplementation.cs
@@ -32,7 +32,8 @@ public unsafe readonly struct ViewImplementation
/// A handle to the method.
///
private static readonly MethodInfo CreateMethod = typeof(ViewImplementation).
- GetMethod(nameof(Create));
+ GetMethod(nameof(Create))
+ .ThrowIfNull();
///
/// Returns a specialized create method.
@@ -42,8 +43,8 @@ public unsafe readonly struct ViewImplementation
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MethodInfo GetCreateMethod(Type sourceType)
{
- sourceType.IsArrayViewType(out Type elementType);
- return CreateMethod.MakeGenericMethod(elementType);
+ sourceType.IsArrayViewType(out Type? elementType);
+ return CreateMethod.MakeGenericMethod(elementType.AsNotNull());
}
///
@@ -71,7 +72,7 @@ public static ViewImplementation Create(ArrayView source)
/// The view implementation type.
/// The resolved field.
public static FieldInfo GetIndexField(Type implType) =>
- implType.GetField(nameof(Index));
+ implType.GetField(nameof(Index)).AsNotNull();
///
/// Returns the length field of a view implementation.
@@ -79,7 +80,7 @@ public static FieldInfo GetIndexField(Type implType) =>
/// The view implementation type.
/// The resolved field.
public static FieldInfo GetLengthField(Type implType) =>
- implType.GetField(nameof(Length));
+ implType.GetField(nameof(Length)).AsNotNull();
#endregion
diff --git a/Src/ILGPU/Backends/VariableAllocator.cs b/Src/ILGPU/Backends/VariableAllocator.cs
index 80c00e92c..04d5e59e5 100644
--- a/Src/ILGPU/Backends/VariableAllocator.cs
+++ b/Src/ILGPU/Backends/VariableAllocator.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2019-2021 ILGPU Project
+// Copyright (c) 2019-2023 ILGPU Project
// www.ilgpu.net
//
// File: VariableAllocator.cs
@@ -146,7 +146,7 @@ internal PointerVariable(
///
/// Returns the represented IR type.
///
- public new PointerType Type => base.Type as PointerType;
+ public new PointerType Type => base.Type.AsNotNullCast();
}
///
@@ -166,7 +166,7 @@ internal StringVariable(int id, StringType type)
///
/// Returns the represented IR string type.
///
- public new StringType Type => base.Type as StringType;
+ public new StringType Type => base.Type.AsNotNullCast();
}
///
@@ -186,7 +186,7 @@ internal ObjectVariable(int id, ObjectType type)
///
/// Returns the represented IR type.
///
- public new ObjectType Type => base.Type as ObjectType;
+ public new ObjectType Type => base.Type.AsNotNullCast();
}
#endregion
@@ -213,7 +213,7 @@ protected VariableAllocator() { }
/// The allocated variable.
public Variable Allocate(Value value)
{
- if (variableLookup.TryGetValue(value, out Variable variable))
+ if (variableLookup.TryGetValue(value, out Variable? variable))
return variable;
variable = value is PrimitiveValue primitiveValue
? new ConstantVariable(idCounter++, primitiveValue)
@@ -230,7 +230,7 @@ public Variable Allocate(Value value)
/// The allocated variable.
public Variable Allocate(Value value, ArithmeticBasicValueType basicValueType)
{
- if (variableLookup.TryGetValue(value, out Variable variable))
+ if (variableLookup.TryGetValue(value, out Variable? variable))
return variable;
variable = AllocateType(basicValueType);
variableLookup.Add(value, variable);
@@ -244,7 +244,7 @@ public Variable Allocate(Value value, ArithmeticBasicValueType basicValueType)
/// The allocated variable.
public T AllocateAs(Value value)
where T : Variable =>
- Allocate(value) as T;
+ Allocate(value).AsNotNullCast();
///
/// Allocates the given type.
diff --git a/Src/ILGPU/CompatibilitySuppressions.xml b/Src/ILGPU/CompatibilitySuppressions.xml
index 2f7dfb841..4d6628336 100644
--- a/Src/ILGPU/CompatibilitySuppressions.xml
+++ b/Src/ILGPU/CompatibilitySuppressions.xml
@@ -1,4 +1,459 @@
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`1
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`2
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`1
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`2
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`1
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`2
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`1
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`2
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`1
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0001
+ T:ILGPU.IR.Intrinsics.IntrinsicValueMatcher`2
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ F:ILGPU.Frontend.DebugInformation.MethodScope.Invalid
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Frontend.CodeGenerationResult.get_ResultHandle
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.IRContext.TryGetMethodHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.ReadOnlyCollection.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Transformations.LowerViews.ViewTypeLowering.#ctor
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.IRTypeContext.get_Dense1DStrideType
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.TypeLowering`1.#ctor
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorObject.#ctor
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorStream.#ctor
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.MemoryBuffer.#ctor(System.Int64,System.Int32)
+ lib/net471/ILGPU.dll
+ lib/net471/ILGPU.dll
+ true
+
+
+ CP0002
+ F:ILGPU.Frontend.DebugInformation.MethodScope.Invalid
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Frontend.CodeGenerationResult.get_ResultHandle
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.IRContext.TryGetMethodHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.ReadOnlyCollection.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Transformations.LowerViews.ViewTypeLowering.#ctor
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.IRTypeContext.get_Dense1DStrideType
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.TypeLowering`1.#ctor
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorObject.#ctor
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorStream.#ctor
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.MemoryBuffer.#ctor(System.Int64,System.Int32)
+ lib/net5.0/ILGPU.dll
+ lib/net5.0/ILGPU.dll
+ true
+
+
+ CP0002
+ F:ILGPU.Frontend.DebugInformation.MethodScope.Invalid
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Frontend.CodeGenerationResult.get_ResultHandle
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.IRContext.TryGetMethodHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.ReadOnlyCollection.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Transformations.LowerViews.ViewTypeLowering.#ctor
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.IRTypeContext.get_Dense1DStrideType
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.TypeLowering`1.#ctor
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorObject.#ctor
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorStream.#ctor
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.MemoryBuffer.#ctor(System.Int64,System.Int32)
+ lib/net6.0/ILGPU.dll
+ lib/net6.0/ILGPU.dll
+ true
+
+
+ CP0002
+ F:ILGPU.Frontend.DebugInformation.MethodScope.Invalid
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Frontend.CodeGenerationResult.get_ResultHandle
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.IRContext.TryGetMethodHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.ReadOnlyCollection.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Transformations.LowerViews.ViewTypeLowering.#ctor
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.IRTypeContext.get_Dense1DStrideType
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.TypeLowering`1.#ctor
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorObject.#ctor
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorStream.#ctor
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.MemoryBuffer.#ctor(System.Int64,System.Int32)
+ lib/net7.0/ILGPU.dll
+ lib/net7.0/ILGPU.dll
+ true
+
+
+ CP0002
+ F:ILGPU.Frontend.DebugInformation.MethodScope.Invalid
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Frontend.CodeGenerationResult.get_ResultHandle
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.IRContext.TryGetMethodHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.ReadOnlyCollection.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.MethodMapping`1.TryGetHandle(System.Reflection.MethodBase,ILGPU.IR.MethodHandle@)
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Transformations.LowerViews.ViewTypeLowering.#ctor
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.IRTypeContext.get_Dense1DStrideType
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.IR.Types.TypeLowering`1.#ctor
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorObject.#ctor
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.AcceleratorStream.#ctor
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
+
+ CP0002
+ M:ILGPU.Runtime.MemoryBuffer.#ctor(System.Int64,System.Int32)
+ lib/netstandard2.1/ILGPU.dll
+ lib/netstandard2.1/ILGPU.dll
+ true
+
\ No newline at end of file
diff --git a/Src/ILGPU/Context.cs b/Src/ILGPU/Context.cs
index 98e16fdcd..b2cb96ecb 100644
--- a/Src/ILGPU/Context.cs
+++ b/Src/ILGPU/Context.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2017-2022 ILGPU Project
+// Copyright (c) 2017-2023 ILGPU Project
// www.ilgpu.net
//
// File: Context.cs
@@ -96,7 +96,7 @@ internal Enumerator(List devices)
///
/// Returns the current use.
///
- public TDevice Current => enumerator.Current as TDevice;
+ public TDevice Current => enumerator.Current.AsNotNullCast();
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -142,7 +142,7 @@ public readonly TDevice this[int deviceIndex]
if (deviceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(deviceIndex));
return deviceIndex < Count
- ? devices[deviceIndex] as TDevice
+ ? devices[deviceIndex].AsNotNullCast()
: throw new NotSupportedException(
RuntimeErrorMessages.NotSupportedTargetAccelerator);
}
@@ -176,7 +176,8 @@ public readonly TDevice this[int deviceIndex]
static Context()
{
var versionString = Assembly.GetExecutingAssembly().
- GetCustomAttribute().Version;
+ GetCustomAttribute().ThrowIfNull()
+ .Version;
int offset = 0;
for (int i = 0; i < 3; ++i)
offset = versionString.IndexOf('.', offset + 1);
@@ -184,7 +185,8 @@ static Context()
InliningAttributeBuilder = new CustomAttributeBuilder(
typeof(MethodImplAttribute).GetConstructor(
- new Type[] { typeof(MethodImplOptions) }),
+ new Type[] { typeof(MethodImplOptions) })
+ .ThrowIfNull(),
new object[] { MethodImplOptions.AggressiveInlining });
}
@@ -195,7 +197,7 @@ static Context()
///
/// Will be called when a new accelerator has been created.
///
- public event EventHandler AcceleratorCreated;
+ public event EventHandler? AcceleratorCreated;
#endregion
@@ -241,7 +243,7 @@ internal Context(
IntrinsicManager = builder.IntrinsicManager;
// Create frontend
- DebugInformationManager frontendDebugInformationManager =
+ DebugInformationManager? frontendDebugInformationManager =
Properties.DebugSymbolsMode > DebugSymbolsMode.Disabled
? DebugInformationManager
: null;
@@ -613,7 +615,7 @@ internal ContextCodeGenerationPhase(
///
/// Returns the exception from code generation failure.
///
- public Exception LastException => Context.ILFrontend.LastException;
+ public Exception? LastException => Context.ILFrontend.LastException;
#endregion
diff --git a/Src/ILGPU/ContextProperties.cs b/Src/ILGPU/ContextProperties.cs
index db3729e4b..7f2159f3b 100644
--- a/Src/ILGPU/ContextProperties.cs
+++ b/Src/ILGPU/ContextProperties.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: ContextProperties.cs
@@ -403,12 +403,12 @@ private ContextProperties(Dictionary sourceProperties)
///
/// Returns the path to LibNVVM DLL.
///
- public string LibNvvmPath { get; protected set; }
+ public string? LibNvvmPath { get; protected set; }
///
/// Returns the path to LibDevice bitcode.
///
- public string LibDevicePath { get; protected set; }
+ public string? LibDevicePath { get; protected set; }
#endregion
diff --git a/Src/ILGPU/Frontend/Block.CFGBuilder.cs b/Src/ILGPU/Frontend/Block.CFGBuilder.cs
index eae38d733..a293f40c4 100644
--- a/Src/ILGPU/Frontend/Block.CFGBuilder.cs
+++ b/Src/ILGPU/Frontend/Block.CFGBuilder.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Block.CFGBuilder.cs
@@ -130,7 +130,7 @@ internal CFGBuilder(
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Block AppendBasicBlock(Location location, int target)
{
- if (!blockMapping.TryGetValue(target, out Block block))
+ if (!blockMapping.TryGetValue(target, out Block? block))
{
var basicBlock = Builder.CreateBasicBlock(location);
block = new Block(CodeGenerator, basicBlock);
@@ -177,7 +177,7 @@ private void BuildBasicBlocks()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AddSuccessor(Block current, Block successor)
{
- if (!successorMapping.TryGetValue(current, out List successors))
+ if (!successorMapping.TryGetValue(current, out List? successors))
{
successors = new List();
successorMapping.Add(current, successors);
@@ -230,7 +230,7 @@ private void SetupBasicBlocks(
{
var instruction = disassembledMethod[instructionIdx];
// Handle implicit cases: jumps to blocks without a jump instruction
- if (blockMapping.TryGetValue(instruction.Offset, out Block other) &&
+ if (blockMapping.TryGetValue(instruction.Offset, out Block? other) &&
current != other)
{
// Wire current and new block
diff --git a/Src/ILGPU/Frontend/Block.cs b/Src/ILGPU/Frontend/Block.cs
index bebd412e3..8bdec1167 100644
--- a/Src/ILGPU/Frontend/Block.cs
+++ b/Src/ILGPU/Frontend/Block.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Block.cs
@@ -83,7 +83,7 @@ private Block(CodeGenerator codeGenerator, BasicBlock.Builder builder)
///
/// Returns the current terminator.
///
- public TerminatorValue Terminator => BasicBlock.Terminator;
+ public TerminatorValue? Terminator => BasicBlock.Terminator;
///
/// Returns the current stack counter.
@@ -134,7 +134,7 @@ public Value GetValue(VariableRef var) =>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan GetBuilderTerminator(int count)
{
- var targets = ((BuilderTerminator)Terminator).Targets;
+ var targets = Terminator.AsNotNullCast().Targets;
Terminator.Assert(targets.Length == count);
return targets;
}
@@ -257,7 +257,7 @@ public Value PopInt(Location location, ConvertFlags flags)
public ValueList PopMethodArgs(
Location location,
MethodBase methodBase,
- Value instanceValue)
+ Value? instanceValue)
{
var parameters = methodBase.GetParameters();
var parameterOffset = methodBase.GetParameterOffset();
@@ -279,8 +279,9 @@ public ValueList PopMethodArgs(
{
if (instanceValue == null)
{
- var declaringType = Builder.CreateType(methodBase.DeclaringType);
- if (!Intrinsics.IsIntrinsicArrayType(methodBase.DeclaringType))
+ var baseDeclaringType = methodBase.DeclaringType.AsNotNull();
+ var declaringType = Builder.CreateType(baseDeclaringType);
+ if (!Intrinsics.IsIntrinsicArrayType(baseDeclaringType))
{
declaringType = Builder.CreatePointerType(
declaringType,
diff --git a/Src/ILGPU/Frontend/CodeGenerator/Arithmetic.cs b/Src/ILGPU/Frontend/CodeGenerator/Arithmetic.cs
index b15d9ca74..6b5fcf2d7 100644
--- a/Src/ILGPU/Frontend/CodeGenerator/Arithmetic.cs
+++ b/Src/ILGPU/Frontend/CodeGenerator/Arithmetic.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Arithmetic.cs
@@ -13,6 +13,7 @@
using ILGPU.IR.Types;
using ILGPU.IR.Values;
using ILGPU.Util;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace ILGPU.Frontend
@@ -58,7 +59,7 @@ shiftValue is null
private bool TryConvertIntoLoadElementAddress(
Value left,
BinaryArithmeticValue baseAddress,
- out Value result)
+ [NotNullWhen(true)] out Value? result)
{
if (
// Check multiplications
diff --git a/Src/ILGPU/Frontend/CodeGenerator/Calls.cs b/Src/ILGPU/Frontend/CodeGenerator/Calls.cs
index 374b10f91..ababdbb7c 100644
--- a/Src/ILGPU/Frontend/CodeGenerator/Calls.cs
+++ b/Src/ILGPU/Frontend/CodeGenerator/Calls.cs
@@ -104,7 +104,7 @@ private void MakeCall(MethodBase target)
/// The resolved call target.
private MethodInfo ResolveVirtualCallTarget(
MethodInfo target,
- Type constrainedType)
+ Type? constrainedType)
{
const BindingFlags ConstraintMethodFlags = BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic;
@@ -127,7 +127,7 @@ private MethodInfo ResolveVirtualCallTarget(
// However, there are two special cases that are supported:
// x.GetHashCode(), x.ToString()
// where GetHashCode and ToString are defined in Object.
- MethodInfo actualTarget = null;
+ MethodInfo? actualTarget = null;
if (target.DeclaringType == typeof(object))
{
var @params = target.GetParameters();
@@ -146,7 +146,7 @@ private MethodInfo ResolveVirtualCallTarget(
throw Location.GetNotSupportedException(
ErrorMessages.NotSupportedVirtualMethodCallToObject,
target.Name,
- actualTarget.DeclaringType,
+ actualTarget.DeclaringType.AsNotNull(),
constrainedType);
}
}
@@ -156,7 +156,7 @@ private MethodInfo ResolveVirtualCallTarget(
if (sourceGenerics.Length > 0)
target = target.GetGenericMethodDefinition();
var interfaceMapping = constrainedType.GetInterfaceMap(
- target.DeclaringType);
+ target.DeclaringType.AsNotNull());
for (
int i = 0, e = interfaceMapping.InterfaceMethods.Length;
i < e;
@@ -207,7 +207,7 @@ private void MakeVirtualCall(ILInstruction instruction)
///
/// The target type on which to invoke the method.
///
- private void MakeVirtualCall(MethodInfo target, Type constrainedType)
+ private void MakeVirtualCall(MethodInfo target, Type? constrainedType)
{
target = ResolveVirtualCallTarget(target, constrainedType);
MakeCall(target);
diff --git a/Src/ILGPU/Frontend/CodeGenerator/CodeGenerator.cs b/Src/ILGPU/Frontend/CodeGenerator/CodeGenerator.cs
index d1b70fcf1..d443a04e1 100644
--- a/Src/ILGPU/Frontend/CodeGenerator/CodeGenerator.cs
+++ b/Src/ILGPU/Frontend/CodeGenerator/CodeGenerator.cs
@@ -71,6 +71,9 @@ public CodeGenerator(
cfgBuilder.Blocks);
SetupVariables();
+
+ // NB: Initialized during GenerateCode.
+ Block = Utilities.InitNotNullable();
}
///
@@ -103,7 +106,7 @@ private void SetupVariables()
// Initialize params
if (!Method.IsStatic && !Method.IsNotCapturingLambda())
{
- var declaringType = builder.CreateType(Method.DeclaringType);
+ var declaringType = builder.CreateType(Method.DeclaringType.AsNotNull());
declaringType = builder.CreatePointerType(
declaringType,
MemoryAddressSpace.Generic);
@@ -142,7 +145,7 @@ private void SetupVariables()
}
// Initialize locals
- var localVariables = Method.GetMethodBody().LocalVariables;
+ var localVariables = Method.GetMethodBody().AsNotNull().LocalVariables;
for (int i = 0, e = localVariables.Count; i < e; ++i)
{
var variable = localVariables[i];
@@ -384,7 +387,8 @@ private void GenerateCodeForBlock()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void VerifyNotRuntimeMethod(MethodBase method)
{
- Debug.Assert(method != null, "Invalid method");
+ if (method.DeclaringType == null || method.DeclaringType.FullName == null)
+ return;
var @namespace = method.DeclaringType.FullName;
// Internal unsafe intrinsic methods
if (@namespace.StartsWith(
diff --git a/Src/ILGPU/Frontend/CodeGenerator/Convert.cs b/Src/ILGPU/Frontend/CodeGenerator/Convert.cs
index bbc2a1473..163659e0d 100644
--- a/Src/ILGPU/Frontend/CodeGenerator/Convert.cs
+++ b/Src/ILGPU/Frontend/CodeGenerator/Convert.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Convert.cs
@@ -59,7 +59,7 @@ public Value CreateConversion(
{
if (value.Type is AddressSpaceType)
{
- var otherType = targetType as AddressSpaceType;
+ var otherType = targetType.AsNotNullCast();
value = Builder.CreateAddressSpaceCast(
Location,
value,
diff --git a/Src/ILGPU/Frontend/CodeGenerator/Fields.cs b/Src/ILGPU/Frontend/CodeGenerator/Fields.cs
index 5d529f93e..722ee848e 100644
--- a/Src/ILGPU/Frontend/CodeGenerator/Fields.cs
+++ b/Src/ILGPU/Frontend/CodeGenerator/Fields.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Fields.cs
@@ -28,7 +28,7 @@ partial class CodeGenerator
private FieldSpan ComputeFieldSpan(TypeNode type, FieldInfo field)
{
var typeInfo = TypeContext.GetTypeInfo(field.FieldType);
- var parentInfo = TypeContext.GetTypeInfo(field.DeclaringType);
+ var parentInfo = TypeContext.GetTypeInfo(field.DeclaringType.AsNotNull());
var fieldIndex = parentInfo.GetAbsoluteIndex(field);
if (type.IsStructureType)
@@ -93,7 +93,7 @@ private void MakeLoadFieldAddress(FieldInfo field)
if (field == null)
throw Location.GetInvalidOperationException();
var targetPointerType = Builder.CreatePointerType(
- Builder.CreateType(field.DeclaringType),
+ Builder.CreateType(field.DeclaringType.AsNotNull()),
MemoryAddressSpace.Generic);
var address = Block.Pop(
targetPointerType,
diff --git a/Src/ILGPU/Frontend/CodeGenerator/Objects.cs b/Src/ILGPU/Frontend/CodeGenerator/Objects.cs
index 595168d24..887a7854a 100644
--- a/Src/ILGPU/Frontend/CodeGenerator/Objects.cs
+++ b/Src/ILGPU/Frontend/CodeGenerator/Objects.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Objects.cs
@@ -60,7 +60,7 @@ private void MakeNewObject(MethodBase method)
if (constructor == null)
throw Location.GetInvalidOperationException();
- var type = constructor.DeclaringType;
+ var type = constructor.DeclaringType.AsNotNull();
var typeNode = Builder.CreateType(type);
var alloca = CreateTempAlloca(typeNode);
diff --git a/Src/ILGPU/Frontend/DebugInformation/AssemblyDebugInformation.cs b/Src/ILGPU/Frontend/DebugInformation/AssemblyDebugInformation.cs
index 8b1053dab..b6d97698c 100644
--- a/Src/ILGPU/Frontend/DebugInformation/AssemblyDebugInformation.cs
+++ b/Src/ILGPU/Frontend/DebugInformation/AssemblyDebugInformation.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: AssemblyDebugInformation.cs
@@ -12,6 +12,7 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
@@ -52,6 +53,10 @@ internal AssemblyDebugInformation(Assembly assembly)
{
Assembly = assembly;
Modules = ImmutableArray.Empty;
+
+ readerProvider =
+ MetadataReaderProvider.FromPortablePdbImage(ImmutableArray.Empty);
+ MetadataReader = readerProvider.GetMetadataReader();
}
///
@@ -75,7 +80,7 @@ internal AssemblyDebugInformation(Assembly assembly, Stream pdbStream)
{
var definitionHandle = methodHandle.ToDefinitionHandle();
var metadataToken = MetadataTokens.GetToken(definitionHandle);
- if (TryResolveMethod(metadataToken, out MethodBase method))
+ if (TryResolveMethod(metadataToken, out MethodBase? method))
{
debugInformation.Add(
method,
@@ -129,7 +134,9 @@ MetadataReaderOperation IMetadataReaderOperationProvider.BeginOperation() =>
/// The resolved method (or null).
/// True, if the given token could be resolved.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public bool TryResolveMethod(int metadataToken, out MethodBase method)
+ public bool TryResolveMethod(
+ int metadataToken,
+ [NotNullWhen(true)] out MethodBase? method)
{
foreach (var module in Modules)
{
@@ -151,7 +158,7 @@ public bool TryResolveMethod(int metadataToken, out MethodBase method)
/// True, if the requested debug information could be loaded.
public bool TryLoadDebugInformation(
MethodBase methodBase,
- out MethodDebugInformation methodDebugInformation)
+ [NotNullWhen(true)] out MethodDebugInformation? methodDebugInformation)
{
Debug.Assert(methodBase != null, "Invalid method");
Debug.Assert(
diff --git a/Src/ILGPU/Frontend/DebugInformation/DebugInformationManager.cs b/Src/ILGPU/Frontend/DebugInformation/DebugInformationManager.cs
index ce3c3f136..d667c3cf0 100644
--- a/Src/ILGPU/Frontend/DebugInformation/DebugInformationManager.cs
+++ b/Src/ILGPU/Frontend/DebugInformation/DebugInformationManager.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: DebugInformationManager.cs
@@ -58,7 +58,8 @@ private interface ILoader
///
bool Load(
Assembly assembly,
- out AssemblyDebugInformation assemblyDebugInformation);
+ [NotNullWhen(true)]
+ out AssemblyDebugInformation? assemblyDebugInformation);
}
///
@@ -104,7 +105,7 @@ public bool Load(
Assembly assembly,
out AssemblyDebugInformation assemblyDebugInformation)
{
- if (Parent.pdbFiles.TryGetValue(PDBFileName, out string fileName))
+ if (Parent.pdbFiles.TryGetValue(PDBFileName, out string? fileName))
{
try
{
@@ -152,20 +153,21 @@ public AutoFileLoader(DebugInformationManager parent)
///
public DebugInformationManager Parent { get; }
- ///
+ ///
public bool Load(
Assembly assembly,
- out AssemblyDebugInformation assemblyDebugInformation)
+ [NotNullWhen(true)]
+ out AssemblyDebugInformation? assemblyDebugInformation)
{
assemblyDebugInformation = null;
if (assembly.IsDynamic || string.IsNullOrEmpty(assembly.Location))
return false;
var debugDir = Path.GetDirectoryName(assembly.Location);
- if (!Parent.lookupDirectories.Contains(debugDir))
+ if (debugDir != null && !Parent.lookupDirectories.Contains(debugDir))
Parent.RegisterLookupDirectory(debugDir);
- var pdbFileName = assembly.GetName().Name;
+ var pdbFileName = assembly.GetName().Name.AsNotNull();
var loader = new FileLoader(Parent, pdbFileName);
return loader.Load(assembly, out assemblyDebugInformation);
}
@@ -199,7 +201,7 @@ public StreamLoader(DebugInformationManager parent, Stream pdbStream)
///
public Stream PDBStream { get; }
- ///
+ ///
[SuppressMessage(
"Design",
"CA1031:Do not catch general exception types",
@@ -208,7 +210,8 @@ public StreamLoader(DebugInformationManager parent, Stream pdbStream)
"of an invalid/incompatible/broken PDB file.")]
public bool Load(
Assembly assembly,
- out AssemblyDebugInformation assemblyDebugInformation)
+ [NotNullWhen(true)]
+ out AssemblyDebugInformation? assemblyDebugInformation)
{
try
{
@@ -268,7 +271,7 @@ public DebugInformationManager()
/// True, if the debug information could be loaded.
public bool TryLoadSymbols(
Assembly assembly,
- out AssemblyDebugInformation assemblyDebugInformation) =>
+ [NotNullWhen(true)] out AssemblyDebugInformation? assemblyDebugInformation) =>
TryLoadSymbolsInternal(
assembly,
new AutoFileLoader(this),
@@ -287,7 +290,7 @@ public bool TryLoadSymbols(
public bool TryLoadSymbols(
Assembly assembly,
string pdbFileName,
- out AssemblyDebugInformation assemblyDebugInformation)
+ [NotNullWhen(true)] out AssemblyDebugInformation? assemblyDebugInformation)
{
if (pdbFileName == null)
throw new ArgumentNullException(nameof(pdbFileName));
@@ -312,7 +315,7 @@ public bool TryLoadSymbols(
public bool TryLoadSymbols(
Assembly assembly,
Stream pdbStream,
- out AssemblyDebugInformation assemblyDebugInformation)
+ [NotNullWhen(true)] out AssemblyDebugInformation? assemblyDebugInformation)
{
if (pdbStream == null)
throw new ArgumentNullException(nameof(pdbStream));
@@ -336,7 +339,7 @@ public bool TryLoadSymbols(
private bool TryLoadSymbolsInternal(
Assembly assembly,
in TLoader loader,
- out AssemblyDebugInformation assemblyDebugInformation)
+ [NotNullWhen(true)] out AssemblyDebugInformation? assemblyDebugInformation)
where TLoader : struct, ILoader
{
if (assembly == null)
@@ -371,7 +374,9 @@ private bool TryLoadSymbolsInternal(
/// The name of the debug-information file.
/// The resolved filename (or null).
/// True, if the given debug-information file could be found.
- public bool TryFindPbdFile(string pdbFileName, out string fileName)
+ public bool TryFindPbdFile(
+ string pdbFileName,
+ [NotNullWhen(true)] out string? fileName)
{
cacheLock.EnterReadLock();
try
@@ -432,7 +437,7 @@ public void RegisterLookupDirectory(string directory)
/// True, if debug information could be loaded.
public bool TryLoadDebugInformation(
MethodBase methodBase,
- out MethodDebugInformation methodDebugInformation)
+ [NotNullWhen(true)] out MethodDebugInformation? methodDebugInformation)
{
Debug.Assert(methodBase != null, "Invalid method");
methodDebugInformation = null;
@@ -458,7 +463,7 @@ public bool TryLoadDebugInformation(
public SequencePointEnumerator LoadSequencePoints(MethodBase methodBase) =>
TryLoadDebugInformation(
methodBase,
- out MethodDebugInformation methodDebugInformation)
+ out MethodDebugInformation? methodDebugInformation)
? methodDebugInformation.CreateSequencePointEnumerator()
: SequencePointEnumerator.Empty;
@@ -479,11 +484,12 @@ public void ClearCache(ClearCacheMode mode)
{
// Do not dispose system assemblies
var assembliesToRemove = new List(assemblies.Count);
- foreach (var assembly in assemblies.Keys)
+ foreach (Assembly assembly in assemblies.Keys)
{
- if (assembly.FullName.StartsWith(
- Context.AssemblyName,
- StringComparison.OrdinalIgnoreCase))
+ if (assembly.FullName != null &&
+ assembly.FullName.StartsWith(
+ Context.AssemblyName,
+ StringComparison.OrdinalIgnoreCase))
{
continue;
}
diff --git a/Src/ILGPU/Frontend/DebugInformation/LocalVariable.cs b/Src/ILGPU/Frontend/DebugInformation/LocalVariable.cs
index be2dc6f73..e711cf390 100644
--- a/Src/ILGPU/Frontend/DebugInformation/LocalVariable.cs
+++ b/Src/ILGPU/Frontend/DebugInformation/LocalVariable.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: LocalVariable.cs
@@ -73,7 +73,7 @@ public LocalVariable(int index, string name)
///
/// True, if the given object is equal to the current local variable.
///
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is LocalVariable localVariable && Equals(localVariable);
///
diff --git a/Src/ILGPU/Frontend/DebugInformation/MethodScope.cs b/Src/ILGPU/Frontend/DebugInformation/MethodScope.cs
index d3de4bdab..61e2a52bf 100644
--- a/Src/ILGPU/Frontend/DebugInformation/MethodScope.cs
+++ b/Src/ILGPU/Frontend/DebugInformation/MethodScope.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: MethodScope.cs
@@ -21,15 +21,6 @@ namespace ILGPU.Frontend.DebugInformation
///
public sealed class MethodScope : IEquatable
{
- #region Constants
-
- ///
- /// Represents an invalid method scope.
- ///
- public static readonly MethodScope Invalid;
-
- #endregion
-
#region Static
///
@@ -121,7 +112,7 @@ public ImmutableArray.Enumerator GetEnumerator() =>
///
/// The other scope.
/// True, if the given scope is equal to the current scope.
- public bool Equals(MethodScope other) =>
+ public bool Equals(MethodScope? other) =>
other != null &&
StartOffset == other.StartOffset &&
Length == other.Length;
@@ -135,7 +126,7 @@ public bool Equals(MethodScope other) =>
///
/// The other sequence object.
/// True, if the given object is equal to the current scope.
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is MethodScope other && Equals(other);
///
diff --git a/Src/ILGPU/Frontend/Disassembler.cs b/Src/ILGPU/Frontend/Disassembler.cs
index f71592774..107c066f2 100644
--- a/Src/ILGPU/Frontend/Disassembler.cs
+++ b/Src/ILGPU/Frontend/Disassembler.cs
@@ -62,7 +62,7 @@ public sealed partial class Disassembler : ILocation
///
/// The current flags argument.
///
- private object flagsArgument;
+ private object? flagsArgument;
///
/// Represents the current list of instructions.
@@ -77,7 +77,7 @@ public sealed partial class Disassembler : ILocation
///
/// Returns the source location.
///
- private readonly CompilationStackLocation compilationStackLocation;
+ private readonly CompilationStackLocation? compilationStackLocation;
///
/// Constructs a new disassembler.
@@ -90,22 +90,20 @@ public sealed partial class Disassembler : ILocation
public Disassembler(
MethodBase methodBase,
SequencePointEnumerator sequencePointEnumerator,
- CompilationStackLocation compilationStackLocation = null)
+ CompilationStackLocation? compilationStackLocation = null)
{
MethodBase = methodBase
?? throw new ArgumentNullException(nameof(methodBase));
MethodGenericArguments = MethodBase is MethodInfo
? MethodBase.GetGenericArguments()
: Array.Empty();
- TypeGenericArguments = MethodBase.DeclaringType.GetGenericArguments();
- MethodBody = MethodBase.GetMethodBody();
- if (MethodBody == null)
- {
- throw new NotSupportedException(string.Format(
+ TypeGenericArguments =
+ MethodBase.DeclaringType.AsNotNull().GetGenericArguments();
+ MethodBody = MethodBase.GetMethodBody()
+ ?? throw new NotSupportedException(string.Format(
ErrorMessages.NativeMethodNotSupported,
MethodBase.Name));
- }
- il = MethodBody.GetILAsByteArray();
+ il = MethodBody.GetILAsByteArray() ?? Array.Empty();
instructions = ImmutableArray.CreateBuilder(il.Length);
debugInformationEnumerator = sequencePointEnumerator;
this.compilationStackLocation = compilationStackLocation;
@@ -129,7 +127,7 @@ public Disassembler(
///
/// Returns the declaring type of the method.
///
- public Type DeclaringType => MethodBase.DeclaringType;
+ public Type DeclaringType => MethodBase.DeclaringType.AsNotNull();
///
/// Returns the associated managed module.
@@ -225,7 +223,7 @@ public DisassembledMethod Disassemble()
/// The token of the method to be disassembled.
private void DisassembleCall(ILInstructionType type, int methodToken)
{
- var method = ResolveMethod(methodToken);
+ var method = ResolveMethod(methodToken).AsNotNull();
var popCount = method.GetParameters().Length;
var methodInfo = method as MethodInfo;
int pushCount = 0;
@@ -273,7 +271,7 @@ private void AppendInstruction(
ILInstructionType type,
ushort popCount,
ushort pushCount,
- object argument = null) =>
+ object? argument = null) =>
AppendInstructionWithFlags(
type,
popCount,
@@ -298,7 +296,7 @@ private void AppendInstructionWithFlags(
ushort popCount,
ushort pushCount,
ILInstructionFlags additionalFlags,
- object argument = null) =>
+ object? argument = null) =>
// Merge with current flags
instructions.Add(new ILInstruction(
instructionOffset,
@@ -331,7 +329,7 @@ private Type ResolveType(int token) =>
///
/// The token of the method to resolve.
/// The resolved method.
- private MethodBase ResolveMethod(int token) =>
+ private MethodBase? ResolveMethod(int token) =>
AssociatedModule.ResolveMethod(
token,
TypeGenericArguments,
@@ -343,7 +341,7 @@ private MethodBase ResolveMethod(int token) =>
///
/// The token of the field to resolve.
/// The resolved field.
- private FieldInfo ResolveField(int token) =>
+ private FieldInfo? ResolveField(int token) =>
AssociatedModule.ResolveField(
token,
TypeGenericArguments,
@@ -409,7 +407,7 @@ private Type ReadTypeArg()
/// Reads a field reference from the current instruction data.
///
/// The decoded field reference.
- private FieldInfo ReadFieldArg()
+ private FieldInfo? ReadFieldArg()
{
var token = ReadIntArg();
return ResolveField(token);
diff --git a/Src/ILGPU/Frontend/ILFrontend.cs b/Src/ILGPU/Frontend/ILFrontend.cs
index cb0aa9cbd..657924f98 100644
--- a/Src/ILGPU/Frontend/ILFrontend.cs
+++ b/Src/ILGPU/Frontend/ILFrontend.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: ILFrontend.cs
@@ -37,7 +37,7 @@ private readonly struct ProcessingEntry
public ProcessingEntry(
MethodBase method,
CompilationStackLocation compilationStackLocation,
- CodeGenerationResult result)
+ CodeGenerationResult? result)
{
Method = method;
CompilationStackLocation = compilationStackLocation;
@@ -57,7 +57,7 @@ public ProcessingEntry(
///
/// Returns the processing future.
///
- public CodeGenerationResult Result { get; }
+ public CodeGenerationResult? Result { get; }
///
/// Returns true if this is an external processing request.
@@ -88,7 +88,7 @@ public void SetResult(Method irFunction)
private readonly Stack processing =
new Stack(1 << 6);
- private volatile CodeGenerationPhase codeGenerationPhase;
+ private volatile CodeGenerationPhase? codeGenerationPhase;
///
/// Constructs a new frontend with two threads.
@@ -99,7 +99,7 @@ public void SetResult(Method irFunction)
///
public ILFrontend(
Context context,
- DebugInformationManager debugInformationManager)
+ DebugInformationManager? debugInformationManager)
: this(context, debugInformationManager, 2)
{ }
@@ -114,7 +114,7 @@ public ILFrontend(
/// The number of threads.
public ILFrontend(
Context context,
- DebugInformationManager debugInformationManager,
+ DebugInformationManager? debugInformationManager,
int numThreads)
{
if (numThreads < 1)
@@ -141,7 +141,7 @@ public ILFrontend(
///
/// Returns the associated debug information manager (if any).
///
- public DebugInformationManager DebugInformationManager { get; }
+ public DebugInformationManager? DebugInformationManager { get; }
///
/// Returns true if the code generation has failed.
@@ -151,7 +151,7 @@ public ILFrontend(
///
/// Returns the exception from code generation failure.
///
- public Exception LastException { get; private set; }
+ public Exception? LastException { get; private set; }
#endregion
@@ -291,7 +291,7 @@ internal void FinishCodeGeneration(CodeGenerationPhase phase)
"This code generation phase had nothing to do");
if (phase.HadWorkToDo)
driverNotifier.Wait();
- LastException = codeGenerationPhase.FirstException;
+ LastException = codeGenerationPhase?.FirstException;
if (Interlocked.CompareExchange(
ref codeGenerationPhase,
@@ -335,7 +335,6 @@ public sealed class CodeGenerationResult
/// The associated method.
internal CodeGenerationResult(MethodBase method)
{
- Debug.Assert(method != null, "Invalid method");
Method = method;
}
@@ -347,12 +346,7 @@ internal CodeGenerationResult(MethodBase method)
///
/// The associated function result.
///
- public Method Result { get; internal set; }
-
- ///
- /// Returns the associated function handle.
- ///
- public MethodHandle ResultHandle => Result.Handle;
+ public Method? Result { get; internal set; }
///
/// Returns true if this result has a function value.
@@ -362,7 +356,7 @@ internal CodeGenerationResult(MethodBase method)
///
/// The first exception during code generation, if any.
///
- public Exception FirstException { get; internal set; }
+ public Exception? FirstException { get; internal set; }
}
@@ -376,7 +370,7 @@ public sealed class CodeGenerationPhase : DisposeBase
private volatile bool isFinished;
private volatile bool hadWorkToDo;
- private volatile Exception firstException;
+ private volatile Exception? firstException;
///
/// Constructs a new generation phase.
@@ -412,7 +406,7 @@ internal CodeGenerationPhase(
///
/// Returns the associated debug information manager (if any).
///
- public DebugInformationManager DebugInformationManager { get; }
+ public DebugInformationManager? DebugInformationManager { get; }
///
/// Returns the associated verifier instance.
@@ -432,7 +426,7 @@ internal CodeGenerationPhase(
///
/// Returns the first exception recorded during code-generation.
///
- public Exception FirstException => firstException;
+ public Exception? FirstException => firstException;
#endregion
@@ -455,7 +449,7 @@ internal void GenerateCodeInternal(
Dictionary detectedMethods,
out Method generatedMethod)
{
- ILocation location = null;
+ ILocation? location = null;
try
{
generatedMethod = Context.Declare(method, out bool created);
diff --git a/Src/ILGPU/Frontend/ILInstruction.cs b/Src/ILGPU/Frontend/ILInstruction.cs
index 6a20ea554..3400d4a47 100644
--- a/Src/ILGPU/Frontend/ILInstruction.cs
+++ b/Src/ILGPU/Frontend/ILInstruction.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: ILInstruction.cs
@@ -10,6 +10,7 @@
// ---------------------------------------------------------------------------------------
using ILGPU.IR;
+using ILGPU.Util;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
@@ -515,7 +516,7 @@ public struct ILInstructionFlagsContext : IEquatable
/// The flags argument.
public ILInstructionFlagsContext(
ILInstructionFlags flags,
- object argument)
+ object? argument)
{
Flags = flags;
Argument = argument;
@@ -533,7 +534,7 @@ public ILInstructionFlagsContext(
///
/// Returns the flag argument.
///
- public object Argument { get; }
+ public object? Argument { get; }
#endregion
@@ -556,7 +557,7 @@ public bool Equals(ILInstructionFlagsContext other) =>
///
/// The other object.
/// True, if the current object is equal to the given one.
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is ILInstructionFlagsContext context && context == this;
///
@@ -595,15 +596,9 @@ public override string ToString() =>
ILInstructionFlagsContext first,
ILInstructionFlagsContext second)
{
- if (first.Flags != second.Flags ||
- first.Argument == null && second.Argument != null ||
- first.Argument != null && second.Argument == null)
- {
+ if (first.Flags != second.Flags)
return false;
- }
- return
- first.Argument == null && second.Argument == null ||
- first.Argument.Equals(second.Argument);
+ return Equals(first.Argument, second.Argument);
}
///
@@ -663,7 +658,7 @@ public ILInstruction(
ILInstructionFlagsContext flagsContext,
ushort popCount,
ushort pushCount,
- object argument,
+ object? argument,
Location location)
{
Offset = offset;
@@ -714,7 +709,7 @@ public ILInstruction(
///
/// Returns the instruction argument.
///
- public object Argument { get; }
+ public object? Argument { get; }
///
/// Returns true if the instruction is a call instruction.
@@ -759,7 +754,7 @@ public bool IsCall
///
/// The target type T.
/// The instruction argument T.
- public T GetArgumentAs() => (T)Argument;
+ public T GetArgumentAs() => (T)Argument.AsNotNull();
///
/// Returns true if current instruction has the given flags.
@@ -817,21 +812,15 @@ public void ForEachOffset(TOperation operation)
"Style",
"IDE0046:Convert to conditional expression",
Justification = "Avoid nested if conditionals")]
- public bool Equals(ILInstruction other)
+ public bool Equals(ILInstruction? other)
{
if (other == null)
return false;
if (InstructionType != other.InstructionType ||
- FlagsContext != other.FlagsContext ||
- Argument == null && other.Argument != null ||
- Argument != null && other.Argument == null)
- {
+ FlagsContext != other.FlagsContext)
return false;
- }
- return
- Argument == null && other.Argument == null ||
- Argument.Equals(other.Argument);
+ return Equals(Argument, other.Argument);
}
#endregion
@@ -843,7 +832,7 @@ public bool Equals(ILInstruction other)
///
/// The other object.
/// True, if the current object is equal to the given one.
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is ILInstruction otherObj && otherObj == this;
///
diff --git a/Src/ILGPU/Frontend/Intrinsic/ArrayIntrinsics.cs b/Src/ILGPU/Frontend/Intrinsic/ArrayIntrinsics.cs
index 3a4560643..e5088e4c0 100644
--- a/Src/ILGPU/Frontend/Intrinsic/ArrayIntrinsics.cs
+++ b/Src/ILGPU/Frontend/Intrinsic/ArrayIntrinsics.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2021 ILGPU Project
+// Copyright (c) 2021-2023 ILGPU Project
// www.ilgpu.net
//
// File: ArrayIntrinsics.cs
@@ -12,6 +12,7 @@
using ILGPU.IR;
using ILGPU.IR.Values;
using ILGPU.Resources;
+using ILGPU.Util;
using System;
namespace ILGPU.Frontend.Intrinsic
@@ -78,7 +79,8 @@ private static ValueReference CreateNewArray(ref InvocationContext context)
}
// Create an array view type of the appropriate dimension
- var managedElementType = context.Method.DeclaringType.GetElementType();
+ var managedElementType =
+ context.Method.DeclaringType.AsNotNull().GetElementType().AsNotNull();
var elementType = builder.CreateType(managedElementType);
var arrayType = builder.CreateArrayType(elementType, dimension);
diff --git a/Src/ILGPU/Frontend/Intrinsic/InteropIntrinsics.cs b/Src/ILGPU/Frontend/Intrinsic/InteropIntrinsics.cs
index b4e07b99c..93d48536d 100644
--- a/Src/ILGPU/Frontend/Intrinsic/InteropIntrinsics.cs
+++ b/Src/ILGPU/Frontend/Intrinsic/InteropIntrinsics.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: InteropIntrinsics.cs
@@ -90,7 +90,7 @@ private static ValueReference CreateOffsetOf(ref InvocationContext context)
var builder = context.Builder;
var typeInfo = builder.TypeContext.GetTypeInfo(
context.GetMethodGenericArguments()[0]);
- var fieldName = context[0].ResolveAs();
+ var fieldName = context[0].ResolveAs().AsNotNull();
int fieldIndex = 0;
foreach (var field in typeInfo.Fields)
{
diff --git a/Src/ILGPU/Frontend/Intrinsic/Intrinsics.cs b/Src/ILGPU/Frontend/Intrinsic/Intrinsics.cs
index 3d31e7453..d3f2e91eb 100644
--- a/Src/ILGPU/Frontend/Intrinsic/Intrinsics.cs
+++ b/Src/ILGPU/Frontend/Intrinsic/Intrinsics.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Intrinsics.cs
@@ -94,49 +94,64 @@ private static readonly DeviceFunctionHandler[]
{
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleAcceleratorOperation(
- ref context, attribute as AcceleratorIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleAtomicOperation(
- ref context, attribute as AtomicIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleCompareOperation(
- ref context, attribute as CompareIntriniscAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleConvertOperation(
- ref context, attribute as ConvertIntriniscAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleGridOperation(
- ref context, attribute as GridIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleGroupOperation(
- ref context, attribute as GroupIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleInterop(
- ref context, attribute as InteropIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleMathOperation(
- ref context, attribute as MathIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleMemoryBarrierOperation(
- ref context, attribute as MemoryBarrierIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleSharedMemoryOperation(
- ref context, attribute as SharedMemoryIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleLocalMemoryOperation(
- ref context, attribute as LocalMemoryIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleViewOperation(
- ref context, attribute as ViewIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleWarpOperation(
- ref context, attribute as WarpIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleUtilityOperation(
- ref context, attribute as UtilityIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
(ref InvocationContext context, IntrinsicAttribute attribute) =>
HandleLanguageOperation(
- ref context, attribute as LanguageIntrinsicAttribute),
+ ref context,
+ attribute.AsNotNullCast()),
};
#endregion
@@ -163,15 +178,15 @@ public static bool HandleIntrinsic(
if (intrinsic != null)
result = IntrinsicHandlers[(int)intrinsic.Type](ref context, intrinsic);
- if (IsIntrinsicArrayType(method.DeclaringType))
+ if (IsIntrinsicArrayType(method.DeclaringType.AsNotNull()))
{
result = HandleArrays(ref context);
// All array operations will be handled by the ILGPU intrinsic handlers
return true;
}
else if (FunctionHandlers.TryGetValue(
- method.DeclaringType,
- out DeviceFunctionHandler handler))
+ method.DeclaringType.AsNotNull(),
+ out DeviceFunctionHandler? handler))
{
result = handler(ref context);
}
@@ -265,8 +280,8 @@ private static unsafe void InitializeArray(ref InvocationContext context)
var location = context.Location;
// Resolve the array data
- var handle = context[1].ResolveAs();
- var value = handle.GetHandle().GetValue(null);
+ var handle = context[1].ResolveAs().AsNotNull();
+ var value = handle.GetHandle().GetValue(null).AsNotNull();
int valueSize = Marshal.SizeOf(value);
// Load the associated array data
@@ -284,7 +299,8 @@ private static unsafe void InitializeArray(ref InvocationContext context)
for (int i = 0, e = valueSize / elementSize; i < e; ++i)
{
byte* address = data + elementSize * i;
- var instance = Marshal.PtrToStructure(new IntPtr(address), elementType);
+ var instance =
+ Marshal.PtrToStructure(new IntPtr(address), elementType).AsNotNull();
// Convert element to IR value
var irValue = builder.CreateValue(location, instance, elementType);
diff --git a/Src/ILGPU/Frontend/Intrinsic/SharedMemoryIntrinsics.cs b/Src/ILGPU/Frontend/Intrinsic/SharedMemoryIntrinsics.cs
index bf332953e..0759ebb2c 100644
--- a/Src/ILGPU/Frontend/Intrinsic/SharedMemoryIntrinsics.cs
+++ b/Src/ILGPU/Frontend/Intrinsic/SharedMemoryIntrinsics.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: SharedMemoryIntrinsics.cs
@@ -12,6 +12,7 @@
using ILGPU.IR;
using ILGPU.IR.Values;
using ILGPU.Resources;
+using ILGPU.Util;
using System;
namespace ILGPU.Frontend.Intrinsic
@@ -79,7 +80,9 @@ private static ValueReference HandleSharedMemoryOperation(
var alloca = builder.CreateDynamicAllocaArray(
location,
allocationType,
- MemoryAddressSpace.Shared).ResolveAs();
+ MemoryAddressSpace.Shared)
+ .ResolveAs()
+ .AsNotNull();
return builder.CreateNewView(
location,
alloca,
diff --git a/Src/ILGPU/Frontend/Intrinsic/ViewIntrinsics.cs b/Src/ILGPU/Frontend/Intrinsic/ViewIntrinsics.cs
index 62fe83045..60cf51a13 100644
--- a/Src/ILGPU/Frontend/Intrinsic/ViewIntrinsics.cs
+++ b/Src/ILGPU/Frontend/Intrinsic/ViewIntrinsics.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: ViewIntrinsics.cs
@@ -13,6 +13,7 @@
using ILGPU.IR.Types;
using ILGPU.IR.Values;
using ILGPU.Resources;
+using ILGPU.Util;
using System;
namespace ILGPU.Frontend.Intrinsic
@@ -87,7 +88,7 @@ private static ValueReference HandleViewOperation(
builder.CreateGetViewLongLength(location, instanceValue),
builder.CreateLongSizeOf(
location,
- (instanceValue.Type as AddressSpaceType).ElementType),
+ instanceValue.Type.AsNotNullCast().ElementType),
BinaryArithmeticKind.Mul),
ViewIntrinsicKind.GetSubView => builder.CreateSubViewValue(
location,
diff --git a/Src/ILGPU/Frontend/InvocationContext.cs b/Src/ILGPU/Frontend/InvocationContext.cs
index 68047eeab..a55ecb975 100644
--- a/Src/ILGPU/Frontend/InvocationContext.cs
+++ b/Src/ILGPU/Frontend/InvocationContext.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: InvocationContext.cs
@@ -13,6 +13,7 @@
using ILGPU.IR.Construction;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -153,7 +154,7 @@ public string FormatErrorMessage(string message) =>
///
/// The generic arguments of the used method.
public Type[] GetTypeGenericArguments() =>
- Method.DeclaringType.GetGenericArguments();
+ Method.DeclaringType.AsNotNull().GetGenericArguments();
///
/// Declares a (potentially new) method.
diff --git a/Src/ILGPU/Frontend/VariableRef.cs b/Src/ILGPU/Frontend/VariableRef.cs
index 9f51d6116..a13d2fd55 100644
--- a/Src/ILGPU/Frontend/VariableRef.cs
+++ b/Src/ILGPU/Frontend/VariableRef.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: VariableRef.cs
@@ -107,7 +107,7 @@ public VariableRef(int index, VariableRefType refType)
///
/// True, if the given variable ref is equal to the current one.
///
- public override bool Equals(object obj) =>
+ public override bool Equals(object? obj) =>
obj is VariableRef variableRef && variableRef == this;
///
diff --git a/Src/ILGPU/Half.cs b/Src/ILGPU/Half.cs
index f3a717901..3ba3b695f 100644
--- a/Src/ILGPU/Half.cs
+++ b/Src/ILGPU/Half.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2022 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: Half.cs
@@ -145,7 +145,7 @@ internal Half(ushort rawValue)
///
/// The other object.
/// True, if the given object is equal to the current half.
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is Half half && Equals(half);
///
diff --git a/Src/ILGPU/IIndex.cs b/Src/ILGPU/IIndex.cs
index 3e8554b53..1364a736b 100644
--- a/Src/ILGPU/IIndex.cs
+++ b/Src/ILGPU/IIndex.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2017-2022 ILGPU Project
+// Copyright (c) 2017-2023 ILGPU Project
// www.ilgpu.net
//
// File: IIndex.cs
@@ -92,7 +92,7 @@ public static class IndexTypeExtensions
///
/// An internal mapping of the values to managed types.
///
- private static readonly Type[] ManagedIndexTypes =
+ private static readonly Type?[] ManagedIndexTypes =
{
null,
typeof(Index1D),
diff --git a/Src/ILGPU/ILGPU.csproj b/Src/ILGPU/ILGPU.csproj
index 11ab96c71..c294e2dbb 100644
--- a/Src/ILGPU/ILGPU.csproj
+++ b/Src/ILGPU/ILGPU.csproj
@@ -10,6 +10,14 @@
$(LibraryFileVersion)
+
+
+ enable
+
+
+ $(NoWarn);nullable
+
+
true
en-US
diff --git a/Src/ILGPU/IR/Analyses/Allocas.cs b/Src/ILGPU/IR/Analyses/Allocas.cs
index 15caa338d..3b410252a 100644
--- a/Src/ILGPU/IR/Analyses/Allocas.cs
+++ b/Src/ILGPU/IR/Analyses/Allocas.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Allocas.cs
@@ -273,13 +273,13 @@ private static void AddAllocation(
Alloca alloca,
ImmutableArray.Builder builder,
ref int memorySize,
- ImmutableArray.Builder dynamicBuilder = null)
+ ImmutableArray.Builder? dynamicBuilder = null)
{
var info = new AllocaInformation(builder.Count, alloca);
if (info.IsDynamicArray)
{
- alloca.AssertNotNull(dynamicBuilder);
- dynamicBuilder.Add(info);
+ alloca.AssertNotNull(dynamicBuilder.AsNotNull());
+ dynamicBuilder.AsNotNull().Add(info);
}
else
{
@@ -358,13 +358,13 @@ public static int GetAllocaTypeAlignment(TypeNode type) =>
/// The value to get the type information for.
/// The type, if the value is supported, null otherwise.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static TypeNode TryGetAnalysisType(Value value) =>
+ private static TypeNode? TryGetAnalysisType(Value value) =>
value switch
{
PhiValue phiValue => phiValue.Type,
PointerCast cast => cast.TargetElementType,
AddressSpaceCast cast =>
- (cast.TargetType as AddressSpaceType).ElementType,
+ cast.TargetType.AsNotNullCast().ElementType,
NewView newView => newView.ViewElementType,
ViewCast cast => cast.TargetElementType,
SubViewValue subView => subView.ElementType,
@@ -427,7 +427,7 @@ public readonly int ComputeAllocaAlignment(Alloca alloca)
while (toProcess.Count > 0)
{
var current = toProcess.Pop();
- TypeNode type;
+ TypeNode? type;
// Check whether we have already seen this value
if (!visited.Add(current))
diff --git a/Src/ILGPU/IR/Analyses/AnalysisValue.cs b/Src/ILGPU/IR/Analyses/AnalysisValue.cs
index f8a79f2b4..07d6909de 100644
--- a/Src/ILGPU/IR/Analyses/AnalysisValue.cs
+++ b/Src/ILGPU/IR/Analyses/AnalysisValue.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2021 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: AnalysisValue.cs
@@ -180,7 +180,7 @@ public readonly bool Equals(AnalysisValue other)
///
/// The other object.
/// True, if the given object is equal to the current value.
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is AnalysisValue value && Equals(value);
///
@@ -193,7 +193,7 @@ public readonly override bool Equals(object obj) =>
/// Returns the string representation of this value.
///
/// The string representation of this value.
- public readonly override string ToString() =>
+ public readonly override string? ToString() =>
childData.Length > 0
? $"{Data} [{string.Join(", ", childData)}]"
: Data.ToString();
diff --git a/Src/ILGPU/IR/Analyses/Dominators.cs b/Src/ILGPU/IR/Analyses/Dominators.cs
index d8ca2eb3f..951ba9837 100644
--- a/Src/ILGPU/IR/Analyses/Dominators.cs
+++ b/Src/ILGPU/IR/Analyses/Dominators.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2022 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Dominators.cs
@@ -224,7 +224,7 @@ public BasicBlock GetImmediateCommonDominator(ReadOnlySpan blocks)
private BasicBlock GetPhiParent(BasicBlock dominatorBlock, UseCollection uses)
{
// Check for phi-value references
- BasicBlock phiParent = null;
+ BasicBlock? phiParent = null;
foreach (Use use in uses)
{
if (!(use.Resolve() is PhiValue phiValue))
diff --git a/Src/ILGPU/IR/Analyses/FixPointAnalysis.cs b/Src/ILGPU/IR/Analyses/FixPointAnalysis.cs
index 45d722c22..3c68d71f0 100644
--- a/Src/ILGPU/IR/Analyses/FixPointAnalysis.cs
+++ b/Src/ILGPU/IR/Analyses/FixPointAnalysis.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2020-2022 ILGPU Project
+// Copyright (c) 2020-2023 ILGPU Project
// www.ilgpu.net
//
// File: FixPointAnalysis.cs
@@ -13,10 +13,12 @@
using ILGPU.IR.Analyses.TraversalOrders;
using ILGPU.IR.Types;
using ILGPU.IR.Values;
+using ILGPU.Util;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace ILGPU.IR.Analyses
@@ -81,7 +83,7 @@ protected BaseAnalysisContext(BasicBlockSet onStack)
/// The popped block (if any).
/// True, if a value could be popped from the stack.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public bool TryPop(out BasicBlock block)
+ public bool TryPop([NotNullWhen(true)] out BasicBlock? block)
{
block = null;
if (Stack.Count < 1)
@@ -353,7 +355,10 @@ protected ValueFixPointAnalysis(T defaultValue)
protected override bool Update(Value node, TContext context)
{
var oldValue = context[node];
- var newValue = Merge(oldValue, node, context as ValueAnalysisContext);
+ var newValue = Merge(
+ oldValue,
+ node,
+ context.AsNotNullCast());
context[node] = newValue;
return oldValue != newValue;
}
@@ -446,8 +451,11 @@ protected override AnalysisValue CreateData(Method method) =>
valueMapping[value] = CreateData(value);
}
// Register terminators
- if (!valueMapping.ContainsKey(block.Terminator))
- valueMapping[block.Terminator] = CreateData(block.Terminator);
+ if (!valueMapping.ContainsKey(block.Terminator.AsNotNull()))
+ {
+ valueMapping[block.Terminator.AsNotNull()] =
+ CreateData(block.Terminator.AsNotNull());
+ }
}
// Create the analysis context and perform the analysis
@@ -856,7 +864,9 @@ public readonly bool TryGetReturnData(
/// The result data (if any).
/// True, if return data could be determined.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public readonly bool TryGetData(Method method, out TMethodData result)
+ public readonly bool TryGetData(
+ Method method,
+ [MaybeNullWhen(false)] out TMethodData? result)
{
result = default;
return Mapping?.TryGetValue(method, out result) ?? false;
@@ -949,7 +959,7 @@ public readonly bool Equals(GlobalAnalysisEntry other)
///
/// True, if the given object is equal to the current entry.
///
- public readonly override bool Equals(object obj) =>
+ public readonly override bool Equals(object? obj) =>
obj is GlobalAnalysisEntry entry && Equals(entry);
///
diff --git a/Src/ILGPU/IR/Analyses/Landscape.cs b/Src/ILGPU/IR/Analyses/Landscape.cs
index 1d9b6b906..1d76439f1 100644
--- a/Src/ILGPU/IR/Analyses/Landscape.cs
+++ b/Src/ILGPU/IR/Analyses/Landscape.cs
@@ -1,6 +1,6 @@
// ---------------------------------------------------------------------------------------
// ILGPU
-// Copyright (c) 2018-2021 ILGPU Project
+// Copyright (c) 2018-2023 ILGPU Project
// www.ilgpu.net
//
// File: Landscape.cs
@@ -9,10 +9,12 @@
// Source License. See LICENSE.txt for details.
// ---------------------------------------------------------------------------------------
+using ILGPU.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace ILGPU.IR.Analyses
@@ -38,9 +40,9 @@ public sealed class Entry
(first, second) => first.Method.Id.CompareTo(second.Method.Id);
private readonly HashSet usesSet = new HashSet();
- private List uses;
+ private List? uses;
- internal Entry(Method method, References references, in T data)
+ internal Entry(Method method, References references, in T? data)
{
method.AssertNotNull(method);
@@ -57,7 +59,7 @@ internal Entry(Method method, References references, in T data)
///
/// Returns custom information.
///
- public T Data { get; }
+ public T? Data { get; }
///
/// Returns the number of basic block.
@@ -67,7 +69,7 @@ internal Entry(Method method, References references, in T data)
///
/// Returns the number of uses.
///
- public int NumUses => uses.Count;
+ public int NumUses => usesSet.Count;
///
/// Returns true if this function has references.
@@ -110,7 +112,8 @@ internal void FinishUses()
///
/// An enumerator to enumerate all depending method entries.
///
- internal List.Enumerator GetEnumerator() => uses.GetEnumerator();
+ internal List.Enumerator GetEnumerator() =>
+ uses.AsNotNull().GetEnumerator();
///
/// Returns the string representation of this entry.
@@ -132,7 +135,7 @@ public interface IDataProvider
/// All references to other methods.
///
/// The resolved custom data.
- T GetData(Method method, References methodReferences);
+ T? GetData(Method method, References methodReferences);
}
///
@@ -233,7 +236,7 @@ protected Landscape() { }
/// The source method.
/// The resolved landscape entry.
public Entry this[Method method] =>
- TryGetEntry(method, out Entry entry)
+ TryGetEntry(method, out Entry? entry)
? entry
: throw new KeyNotFoundException();
@@ -252,7 +255,7 @@ protected Landscape() { }
/// The method.
/// The resolved entry.
/// True, if the entry could be resolved.
- public bool TryGetEntry(Method method, out Entry entry) =>
+ public bool TryGetEntry(Method method, [NotNullWhen(true)] out Entry? entry) =>
entries.TryGetValue(method, out entry);
///
@@ -283,7 +286,7 @@ protected void Init(
{
foreach (var reference in entry.References)
{
- if (entries.TryGetValue(reference, out Entry referenceEntry))
+ if (entries.TryGetValue(reference, out Entry? referenceEntry))
referenceEntry.AddUse(entry.Method);
}
}
@@ -381,7 +384,7 @@ public sealed class Landscape : Landscape