diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index 6d78bed9..9d573fd3 100644 --- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -1,8 +1,8 @@ -using System.Collections.Immutable; -using System.Linq; +using System.Linq; using System.Text; using ComputeSharp.Core.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -66,8 +66,8 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator /// The instance for . public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol) { - ImmutableArray.Builder parameters = ImmutableArray.CreateBuilder(); - ImmutableArray.Builder defaulted = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder parameters = ImmutableArrayBuilder.Rent(); + using ImmutableArrayBuilder defaulted = ImmutableArrayBuilder.Rent(); foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -93,7 +93,7 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator } } - return new(parameters.ToImmutableArray(), defaulted.ToImmutableArray()); + return new(parameters.ToImmutable(), defaulted.ToImmutable()); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index e475010c..b346673b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -7,6 +7,7 @@ using ComputeSharp.D2D1.Exceptions; using ComputeSharp.D2D1.Shaders.Translation; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using TerraFX.Interop.DirectX; @@ -29,7 +30,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The HLSL source to compile, if present. - public static string? GetInvalidReturnType(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static string? GetInvalidReturnType(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { if (!(methodSymbol.ReturnType is INamedTypeSymbol { @@ -58,7 +59,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The HLSL source to compile, if present. - public static string GetHlslSource(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static string GetHlslSource(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { _ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData); @@ -80,7 +81,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The shader profile to use to compile the shader, if present. - public static D2D1ShaderProfile GetShaderProfile(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static D2D1ShaderProfile GetShaderProfile(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) { @@ -107,7 +108,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions GetCompileOptions(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static D2D1CompileOptions GetCompileOptions(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index 431050d1..0d96cb7e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -32,7 +33,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.TargetNode; IMethodSymbol methodSymbol = (IMethodSymbol)context.TargetSymbol; - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // Get the processed HLSL first and check for cancellation string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 4b3ee9b2..f9687982 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -38,7 +38,7 @@ partial class ID2D1ShaderGenerator /// The indicess of the complex shader inputs. /// The HLSL source for the shader. public static string GetHlslSource( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -102,14 +102,14 @@ partial class ID2D1ShaderGenerator /// The sequence of captured fields in . /// The sequence of captured resource textures in . private static void GetInstanceFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types, out ImmutableArray<(string Name, string HlslType)> valueFields, out ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields) { - ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); - ImmutableArray<(string, string, int)>.Builder resourceTextures = ImmutableArray.CreateBuilder<(string, string, int)>(); + using ImmutableArrayBuilder<(string, string)> values = ImmutableArrayBuilder<(string, string)>.Rent(); + using ImmutableArrayBuilder<(string, string, int)> resourceTextures = ImmutableArrayBuilder<(string, string, int)>.Rent(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -193,7 +193,7 @@ partial class ID2D1ShaderGenerator /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -201,7 +201,7 @@ partial class ID2D1ShaderGenerator IDictionary constantDefinitions, out bool needsD2D1RequiresScenePosition) { - ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + using ImmutableArrayBuilder<(string, string, string?)> builder = ImmutableArrayBuilder<(string, string, string?)>.Rent(); needsD2D1RequiresScenePosition = false; @@ -264,7 +264,7 @@ partial class ID2D1ShaderGenerator /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, @@ -281,7 +281,8 @@ partial class ID2D1ShaderGenerator select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + + using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); needsD2D1RequiresScenePosition = false; @@ -359,7 +360,7 @@ partial class ID2D1ShaderGenerator /// A sequence of discovered constants to declare in the shader. private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); foreach (var constant in constantDefinitions) { @@ -369,7 +370,7 @@ partial class ID2D1ShaderGenerator builder.Add((constantName, constant.Value)); } - return builder.MoveToImmutable(); + return builder.ToImmutable(); } /// @@ -381,13 +382,14 @@ partial class ID2D1ShaderGenerator /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types, IReadOnlyDictionary instanceMethods) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); - IReadOnlyCollection invalidTypes; + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); + + IReadOnlyCollection invalidTypes; // Process the discovered types foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) @@ -449,7 +451,7 @@ partial class ID2D1ShaderGenerator /// /// The collection of produced instances. /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { foreach (var memberSymbol in structDeclarationSymbol.GetMembers()) { @@ -475,7 +477,7 @@ partial class ID2D1ShaderGenerator /// Whether the shader type is declaring the need for scene position. /// Whether the shader is using APIs that rely on scene position. private static void ReportInvalidD2DRequiresScenePositionUse( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool requiresScenePosition, bool usesPositionDependentMethods) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index 1245ba01..53bc8909 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -26,7 +26,7 @@ partial class ID2D1ShaderGenerator /// The indices of the complex shader inputs. /// The combined and serialized input types for each available input. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, out int inputCount, out ImmutableArray inputSimpleIndices, @@ -40,8 +40,8 @@ partial class ID2D1ShaderGenerator inputCount = 0; - ImmutableArray.Builder inputSimpleIndicesBuilder = ImmutableArray.CreateBuilder(); - ImmutableArray.Builder inputComplexIndicesBuilder = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder inputSimpleIndicesBuilder = ImmutableArrayBuilder.Rent(); + using ImmutableArrayBuilder inputComplexIndicesBuilder = ImmutableArrayBuilder.Rent(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { @@ -75,18 +75,32 @@ partial class ID2D1ShaderGenerator } // All simple indices must be in range - if (inputSimpleIndicesBuilder.Concat(inputComplexIndicesBuilder).Any(i => (uint)i >= rawInputCount)) + foreach (int index in inputSimpleIndicesBuilder.WrittenSpan) { - diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); + if ((uint)index >= rawInputCount) + { + diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } + } + + // All complex indices must be in range as well + foreach (int index in inputComplexIndicesBuilder.WrittenSpan) + { + if ((uint)index >= rawInputCount) + { + diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); + + return; + } } Span selectedSimpleInputIndices = stackalloc bool[8]; Span selectedComplexInputIndices = stackalloc bool[8]; // All simple indices must be unique - foreach (int index in inputSimpleIndicesBuilder) + foreach (int index in inputSimpleIndicesBuilder.WrittenSpan) { ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index]; @@ -101,7 +115,7 @@ partial class ID2D1ShaderGenerator } // All complex indices must be unique as well - foreach (int index in inputComplexIndicesBuilder) + foreach (int index in inputComplexIndicesBuilder.WrittenSpan) { ref bool isInputIndexUsed = ref selectedComplexInputIndices[index]; @@ -127,7 +141,7 @@ partial class ID2D1ShaderGenerator } // Build the combined input types list now that inputs have been validated - ImmutableArray.Builder combinedBuilder = ImmutableArray.CreateBuilder(inputCount); + using ImmutableArrayBuilder combinedBuilder = ImmutableArrayBuilder.Rent(); for (int i = 0; i < inputCount; i++) { @@ -139,7 +153,7 @@ partial class ID2D1ShaderGenerator combinedBuilder.Add(selectedSimpleInputIndices[i] ? 0u : 1u); } - combinedInputTypes = combinedBuilder.MoveToImmutable(); + combinedInputTypes = combinedBuilder.ToImmutable(); } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index ec17de8f..fc8709d8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -50,7 +51,7 @@ partial class ID2D1ShaderGenerator return ImmutableArray.Empty; } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // Insert the fallback for empty shaders. This will generate the following code: // diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index 2661e394..624f9b69 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -9,6 +9,7 @@ using ComputeSharp.D2D1.Exceptions; using ComputeSharp.D2D1.Shaders.Translation; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using TerraFX.Interop.DirectX; @@ -51,7 +52,7 @@ partial class ID2D1ShaderGenerator /// The collection of produced instances. /// The input instance to process. /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions? GetCompileOptions(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + public static D2D1CompileOptions? GetCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index f4f964df..aaace9de 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -63,7 +64,36 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.DefaultKeyword)))))); } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); + + // global::System.Span data = stackalloc byte[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("data")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))))))))))); + + // ref byte r0 = ref data[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("data")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); // Generate loading statements for each captured field foreach (FieldInfo fieldInfo in fieldInfos) @@ -123,35 +153,6 @@ partial class ID2D1ShaderGenerator } } - // global::System.Span data = stackalloc byte[]; - statements.Insert(0, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("data")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))))))))))); - - // ref byte r0 = ref data[0]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("data")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - // loader.LoadConstantBuffer(data); statements.Add( ExpressionStatement( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs index 25b20138..fa90409d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -29,7 +30,7 @@ partial class ID2D1ShaderGenerator /// The size of the shader constant buffer. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, ITypeSymbol structDeclarationSymbol, out int constantBufferSizeInBytes) { @@ -123,7 +124,7 @@ partial class ID2D1ShaderGenerator // each row needs to be at a multiple of 16 bytes (a float4 register). if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); for (int j = 0; j < rows; j++) { @@ -140,7 +141,7 @@ partial class ID2D1ShaderGenerator elementName!, rows, columns, - builder.MoveToImmutable()); + builder.ToImmutable()); } else { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs index 3a568749..952fb95a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -62,14 +63,14 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.DefaultKeyword)))))); } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // The size of the buffer with the input descriptions is the number of input descriptions, times the size of each // input description, which is a struct containing three int-sized fields (index, filter, and level of detail). int inputDescriptionSizeInBytes = inputDescriptions.Length * sizeof(int) * 3; // global::System.Span data = stackalloc byte[]; - statements.Insert(0, + statements.Add( LocalDeclarationStatement( VariableDeclaration( GenericName(Identifier("global::System.Span")) @@ -84,7 +85,7 @@ partial class ID2D1ShaderGenerator LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescriptionSizeInBytes))))))))))); // ref byte r0 = ref data[0]; - statements.Insert(1, + statements.Add( LocalDeclarationStatement( VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) .AddVariables( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index c1b9182c..c8dd433f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -24,12 +24,13 @@ partial class ID2D1ShaderGenerator /// The input instance to process. /// The produced input descriptions for the shader. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, out ImmutableArray inputDescriptions) { int inputCount = 0; - ImmutableArray.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder(); + + using ImmutableArrayBuilder inputDescriptionsBuilder = ImmutableArrayBuilder.Rent(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { @@ -63,17 +64,20 @@ partial class ID2D1ShaderGenerator } // All simple indices must be in range - if (inputDescriptionsBuilder.Any(description => description.Index >= inputCount)) + foreach (InputDescription inputDescription in inputDescriptionsBuilder.WrittenSpan) { - diagnostics.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); + if (inputDescription.Index >= inputCount) + { + diagnostics.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } Span selectedInputDescriptionIndices = stackalloc bool[8]; // All input description indices must be unique - foreach (InputDescription inputDescription in inputDescriptionsBuilder) + foreach (InputDescription inputDescription in inputDescriptionsBuilder.WrittenSpan) { ref bool isInputDescriptionIndexUsed = ref selectedInputDescriptionIndices[(int)inputDescription.Index]; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs index 82bac704..6ebafc2c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -62,14 +63,14 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.DefaultKeyword)))))); } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // The size of the buffer with the resource texture descriptions is the number of resurce textures descriptions, // times the size of each input description, which is a struct containing two int-sized fields (index and rank). int resourceTextureDescriptionSizeInBytes = resourceTextureDescriptionsInfo.Length * sizeof(int) * 2; // global::System.Span data = stackalloc byte[]; - statements.Insert(0, + statements.Add( LocalDeclarationStatement( VariableDeclaration( GenericName(Identifier("global::System.Span")) @@ -84,7 +85,7 @@ partial class ID2D1ShaderGenerator LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceTextureDescriptionSizeInBytes))))))))))); // ref byte r0 = ref data[0]; - statements.Insert(1, + statements.Add( LocalDeclarationStatement( VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) .AddVariables( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index c9fd1576..0c788c2f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -26,12 +26,12 @@ partial class ID2D1ShaderGenerator /// The number of inputs for the shader. /// The produced resource texture descriptions for the shader. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, int inputCount, out ImmutableArray resourceTextureDescriptions) { - ImmutableArray<(int? Index, int Rank)>.Builder resourceTextureInfos = ImmutableArray.CreateBuilder<(int?, int)>(); + using ImmutableArrayBuilder<(int? Index, int Rank)> resourceTextureInfos = ImmutableArrayBuilder<(int? Index, int Rank)>.Rent(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -72,7 +72,15 @@ partial class ID2D1ShaderGenerator } // Extract the resource texture descriptions for the rest of the pipeline - resourceTextureDescriptions = resourceTextureInfos.Select(static info => new ResourceTextureDescription((uint)(info.Index ?? 0), (uint)info.Rank)).ToImmutableArray(); + using (ImmutableArrayBuilder resourceTextureDescriptionsBuilder = ImmutableArrayBuilder.Rent()) + { + foreach ((int? index, int rank) in resourceTextureInfos.WrittenSpan) + { + resourceTextureDescriptionsBuilder.Add(new ResourceTextureDescription((uint)(index ?? 0), (uint)rank)); + } + + resourceTextureDescriptions = resourceTextureDescriptionsBuilder.ToImmutable(); + } // If the input count is invalid, do nothing and avoid emitting potentially incorrect // diagnostics based on the resource texture indices with respect to the input count. @@ -84,25 +92,31 @@ partial class ID2D1ShaderGenerator } // Validate that the resource texture indices don't overlap with the shader inputs - if (resourceTextureInfos.Any(info => info.Index < inputCount)) + foreach ((int? index, _) in resourceTextureInfos.WrittenSpan) { - diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol); + if (index < inputCount) + { + diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } // Validate that no resource texture has an index greater than or equal to 16 - if (resourceTextureInfos.Any(info => info.Index >= 16)) + foreach ((int? index, _) in resourceTextureInfos.WrittenSpan) { - diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol); + if (index >= 16) + { + diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } Span selectedResourceTextureIndices = stackalloc bool[16]; // All input description indices must be unique (also take this path for invalid indices) - foreach ((int? index, _) in resourceTextureInfos) + foreach ((int? index, _) in resourceTextureInfos.WrittenSpan) { ref bool isResourceTextureIndexUsed = ref selectedResourceTextureIndices[index ?? 0]; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index e4502804..447d3bce 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -50,7 +51,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator return default; } - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index be59ad0a..bbfe304e 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -45,7 +44,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// /// The collection of produced instances. /// - protected readonly ImmutableArray.Builder Diagnostics; + protected readonly ImmutableArrayBuilder Diagnostics; /// /// Creates a new instance with the specified parameters. @@ -58,7 +57,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArrayBuilder diagnostics) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 400ab405..a80b9e59 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -79,7 +78,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary staticMethods, IDictionary instanceMethods, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, bool isEntryPoint) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { @@ -106,7 +105,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary staticMethods, IDictionary instanceMethods, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArrayBuilder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs index 653d08d5..8e9dab94 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -31,7 +30,7 @@ internal sealed partial class StaticFieldRewriter : HlslSourceRewriter SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArrayBuilder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { } diff --git a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs index 01923f37..b1404c61 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs @@ -1,4 +1,5 @@ using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -17,7 +18,7 @@ internal static class DiagnosticsExtensions /// The source to attach the diagnostics to. /// The optional arguments for the formatted message to include. public static void Add( - this ImmutableArray.Builder diagnostics, + this ImmutableArrayBuilder diagnostics, DiagnosticDescriptor descriptor, ISymbol symbol, params object[] args) @@ -33,7 +34,7 @@ internal static class DiagnosticsExtensions /// The source to attach the diagnostics to. /// The optional arguments for the formatted message to include. public static void Add( - this ImmutableArray.Builder diagnostics, + this ImmutableArrayBuilder diagnostics, DiagnosticDescriptor descriptor, SyntaxNode node, params object[] args) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index cb98574e..40eae510 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -12,7 +12,7 @@ namespace ComputeSharp.SourceGeneration.Helpers; /// A helper type to build sequences of values with pooled buffers. /// /// The type of items to create sequences for. -internal ref struct ImmutableArrayBuilder +internal struct ImmutableArrayBuilder : IDisposable { /// /// The shared instance to share objects. @@ -49,6 +49,24 @@ internal ref struct ImmutableArrayBuilder this.writer = writer; } + /// + /// Gets the data written to the underlying buffer so far, as a . + /// + public readonly ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.writer!.WrittenSpan; + } + + /// + /// Gets the number of elements currently written in the current instance. + /// + public readonly int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.writer!.WrittenSpan.Length; + } + /// public readonly void Add(T item) { @@ -64,6 +82,16 @@ internal ref struct ImmutableArrayBuilder this.writer!.AddRange(items); } + /// + /// Inserts an item to the builder at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The object to insert into the . + public readonly void Insert(int index, T item) + { + this.writer!.Insert(index, item); + } + /// public readonly ImmutableArray ToImmutable() { @@ -84,7 +112,7 @@ internal ref struct ImmutableArrayBuilder return this.writer!.WrittenSpan.ToString(); } - /// + /// public void Dispose() { Writer? writer = this.writer; @@ -131,9 +159,7 @@ internal ref struct ImmutableArrayBuilder this.index = 0; } - /// - /// Gets the data written to the underlying buffer so far, as a . - /// + /// public ReadOnlySpan WrittenSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -158,6 +184,25 @@ internal ref struct ImmutableArrayBuilder this.index += items.Length; } + /// + public void Insert(int index, T item) + { + if (index < 0 || index > this.index) + { + ImmutableArrayBuilder.ThrowArgumentOutOfRangeExceptionForIndex(); + } + + EnsureCapacity(1); + + if (index < this.index) + { + Array.Copy(this.array, index, this.array, index + 1, this.index - index); + } + + this.array[index] = item; + this.index++; + } + /// /// Clears the items in the current writer. /// @@ -201,4 +246,18 @@ internal ref struct ImmutableArrayBuilder this.array = newArray; } } +} + +/// +/// Private helpers for the type. +/// +file static class ImmutableArrayBuilder +{ + /// + /// Throws an for "index". + /// + public static void ThrowArgumentOutOfRangeExceptionForIndex() + { + throw new ArgumentOutOfRangeException("index"); + } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index 1b069322..511af340 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -27,7 +27,7 @@ internal sealed partial record HierarchyInfo(string FilenameHint, string FullyQu /// A instance describing . public static HierarchyInfo From(INamedTypeSymbol typeSymbol) { - ImmutableArray.Builder hierarchy = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder hierarchy = ImmutableArrayBuilder.Rent(); for (INamedTypeSymbol? parent = typeSymbol; parent is not null; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 8a8f4556..4d5b5186 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -84,7 +84,8 @@ partial class IShaderGenerator /// The series of statements to build the HLSL source to compile to execute the current shader. private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); + StringBuilder textBuilder = new(); int capturedDelegates = 0; int prologueStatements = 0; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 703cf89f..03aa3fb3 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -37,7 +37,7 @@ partial class IShaderGenerator /// The for . /// The resulting info on the processed shader. public static HlslShaderSourceInfo GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) @@ -101,13 +101,14 @@ partial class IShaderGenerator ImmutableArray<(string MetadataName, string Name, string HlslType)>, ImmutableArray<(string Name, string HlslType)>) GetInstanceFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types, bool isComputeShader) { - ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>(); - ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + using ImmutableArrayBuilder<(string, string, string)> resources = ImmutableArrayBuilder<(string, string, string)>.Rent(); + using ImmutableArrayBuilder<(string, string)> values = ImmutableArrayBuilder<(string, string)>.Rent(); + bool hlslResourceFound = false; foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) @@ -192,14 +193,14 @@ partial class IShaderGenerator /// The collection of discovered constant definitions. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions) { - ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + using ImmutableArrayBuilder<(string, string, string?)> builder = ImmutableArrayBuilder<(string, string, string?)>.Rent(); foreach (var fieldDeclaration in structDeclaration.Members.OfType()) { @@ -259,11 +260,11 @@ partial class IShaderGenerator /// The collection of currently discovered types. /// A sequence of captured members in . private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types) { - ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); + using ImmutableArrayBuilder<(string, string, int?)> builder = ImmutableArrayBuilder<(string, string, int?)>.Rent(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -321,7 +322,7 @@ partial class IShaderGenerator /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, @@ -337,8 +338,9 @@ partial class IShaderGenerator where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - string? entryPoint = null; - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); + + string ? entryPoint = null; bool isSamplerUsed = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) @@ -424,7 +426,7 @@ partial class IShaderGenerator /// A sequence of discovered constants to declare in the shader. internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); foreach (var constant in constantDefinitions) { @@ -434,7 +436,7 @@ partial class IShaderGenerator builder.Add((constantName, constant.Value)); } - return builder.MoveToImmutable(); + return builder.ToImmutable(); } /// @@ -446,13 +448,14 @@ partial class IShaderGenerator /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, ISymbol sourceSymbol, IEnumerable types, IReadOnlyDictionary instanceMethods) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); - IReadOnlyCollection invalidTypes; + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); + + IReadOnlyCollection invalidTypes; // Process the discovered types foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) @@ -514,7 +517,7 @@ partial class IShaderGenerator /// /// The collection of produced instances. /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { foreach (var memberSymbol in structDeclarationSymbol.GetMembers()) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 8443bf2c..61b70547 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -11,6 +11,7 @@ using System.Threading; using ComputeSharp.Exceptions; using ComputeSharp.Shaders.Translation; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; @@ -38,7 +39,7 @@ partial class IShaderGenerator /// Indicates whether or not dynamic shaders are supported. /// The thread ids for the precompiled shader, if available. public static ThreadIdsInfo GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, bool supportsDynamicShaders) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 53b0caa3..8684d2cc 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -67,14 +68,76 @@ partial class IShaderGenerator int resourceCount, int root32BitConstantsCount) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - bool isComputeShader = shaderType == ShaderType.ComputeShader; + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); + + // global::System.Span span0 = stackalloc uint[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); + + if (resourceCount > 0) + { + // global::System.Span span1 = stackalloc ulong[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount))))))))))); + } + + // ref uint r0 = ref span0[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + if (resourceCount > 0) + { + // ref ulong r1 = ref span1[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + } // Append the statements for the dispatch ranges: // // span0[0] = (uint)x; // span0[1] = (uint)y; - // span0[2] = (uint)z; statements.Add( ExpressionStatement( AssignmentExpression( @@ -91,8 +154,10 @@ partial class IShaderGenerator .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); - // If the shader is a compute shader, also track the bounds on the Z axis - if (isComputeShader) + // If the shader is a compute shader, also track the bounds on the Z axis: + // + // span0[2] = (uint)z; + if (shaderType == ShaderType.ComputeShader) { statements.Add( ExpressionStatement( @@ -173,35 +238,6 @@ partial class IShaderGenerator } } - // global::System.Span span0 = stackalloc uint[]; - statements.Insert(0, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); - - // ref uint r0 = ref span0[0]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - // loader.LoadCapturedValues(span0); statements.Add( ExpressionStatement( @@ -214,35 +250,6 @@ partial class IShaderGenerator if (resourceCount > 0) { - // global::System.Span span1 = stackalloc ulong[]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount))))))))))); - - // ref ulong r1 = ref span1[0]; - statements.Insert(3, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - // loader.LoadCapturedResources(span1); statements.Add( ExpressionStatement( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index bfdb56ec..298f27e4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; @@ -31,7 +32,7 @@ partial class IShaderGenerator /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, ITypeSymbol structDeclarationSymbol, ShaderType shaderType, out int resourceCount, @@ -148,7 +149,7 @@ partial class IShaderGenerator // each row needs to be at a multiple of 16 bytes (a float4 register). if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); for (int j = 0; j < rows; j++) { @@ -165,7 +166,7 @@ partial class IShaderGenerator elementName!, rows, columns, - builder.MoveToImmutable()); + builder.ToImmutable()); } else { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 4ae4f04c..a6807487 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Globalization; using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -54,7 +55,7 @@ partial class IShaderGenerator /// The sequence of instances to load shader dispatch data. private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // global::System.Span span0 = stackalloc byte[5]; statements.Add( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index b89652a4..c0f2a926 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -1,4 +1,5 @@ using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGenerators.Models; @@ -26,7 +27,8 @@ partial class IShaderGenerator bool isSamplerUsed, ImmutableArray capturedFields) { - ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder descriptors = ImmutableArrayBuilder.Rent(); + int constantBufferOffset = 1; int readOnlyResourceOffset = 0; int readWriteResourceOffset = 0; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 3c207729..c5b1da2b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; using System.Text; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; @@ -55,7 +56,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator return default; } - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // GetDispatchId() info ImmutableArray dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol); diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7985bf26..81356654 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -79,7 +79,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator IMethodSymbol methodSymbol, out ImmutableArray diagnostics) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -112,7 +112,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator /// The collection of discovered constant definitions. /// A sequence of processed methods in (main method and all captured methods). private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, CSharpSyntaxNode methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, @@ -137,7 +137,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator .NormalizeWhitespace(eol: "\n") .ToFullString(); - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(shaderSourceRewriter.LocalFunctions.Count); + using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 951b348d..3a3a2aa5 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -using System.Threading; using System.Threading.Tasks; using CommunityToolkit.Diagnostics; using ComputeSharp.__Internals; diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index ad8033c2..b1a57806 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting;