Use pooled array builders in all generators

このコミットが含まれているのは:
Sergio Pedri committed 2022-10-07 09:14:17 -07:00
1 親 d4b1e71c39
コミット 883d99ca9f
31ファイル変更
+320 -205

検索条件に一致するファイルはありません

+5 -5
ファイルの表示
@@ -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
/// <returns>The <see cref="ConstructorInfo"/> instance for <paramref name="structDeclarationSymbol"/>.</returns>
public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol)
{
ImmutableArray<ParameterInfo>.Builder parameters = ImmutableArray.CreateBuilder<ParameterInfo>();
ImmutableArray<string>.Builder defaulted = ImmutableArray.CreateBuilder<string>();
using ImmutableArrayBuilder<ParameterInfo> parameters = ImmutableArrayBuilder<ParameterInfo>.Rent();
using ImmutableArrayBuilder<string> defaulted = ImmutableArrayBuilder<string>.Rent();
foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
@@ -93,7 +93,7 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator
}
}
return new(parameters.ToImmutableArray(), defaulted.ToImmutableArray());
return new(parameters.ToImmutable(), defaulted.ToImmutable());
}
/// <summary>
+5 -4
ファイルの表示
@@ -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
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The HLSL source to compile, if present.</returns>
public static string? GetInvalidReturnType(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
public static string? GetInvalidReturnType(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, IMethodSymbol methodSymbol)
{
if (!(methodSymbol.ReturnType is INamedTypeSymbol
{
@@ -58,7 +59,7 @@ partial class D2DPixelShaderSourceGenerator
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The HLSL source to compile, if present.</returns>
public static string GetHlslSource(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
public static string GetHlslSource(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, IMethodSymbol methodSymbol)
{
_ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData);
@@ -80,7 +81,7 @@ partial class D2DPixelShaderSourceGenerator
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The shader profile to use to compile the shader, if present.</returns>
public static D2D1ShaderProfile GetShaderProfile(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
public static D2D1ShaderProfile GetShaderProfile(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, IMethodSymbol methodSymbol)
{
if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData))
{
@@ -107,7 +108,7 @@ partial class D2DPixelShaderSourceGenerator
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions GetCompileOptions(ImmutableArray<DiagnosticInfo>.Builder diagnostics, IMethodSymbol methodSymbol)
public static D2D1CompileOptions GetCompileOptions(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, IMethodSymbol methodSymbol)
{
if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
{
+2 -1
ファイルの表示
@@ -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<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
// Get the processed HLSL first and check for cancellation
string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol);
@@ -38,7 +38,7 @@ partial class ID2D1ShaderGenerator
/// <param name="inputComplexIndices">The indicess of the complex shader inputs.</param>
/// <returns>The HLSL source for the shader.</returns>
public static string GetHlslSource(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
@@ -102,14 +102,14 @@ partial class ID2D1ShaderGenerator
/// <param name="valueFields">The sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</param>
/// <param name="resourceTextureFields">The sequence of captured resource textures in <paramref name="structDeclarationSymbol"/>.</param>
private static void GetInstanceFields(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> 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<IFieldSymbol>())
{
@@ -193,7 +193,7 @@ partial class ID2D1ShaderGenerator
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
@@ -201,7 +201,7 @@ partial class ID2D1ShaderGenerator
IDictionary<IFieldSymbol, string> 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
/// <param name="needsD2D1RequiresScenePosition">Whether or not the shader needs the <c>[D2DRequiresScenePosition]</c> annotation.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> 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
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> 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();
}
/// <summary>
@@ -381,13 +382,14 @@ partial class ID2D1ShaderGenerator
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<INamedTypeSymbol> types,
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods)
{
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
IReadOnlyCollection<INamedTypeSymbol> invalidTypes;
using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent();
IReadOnlyCollection <INamedTypeSymbol> invalidTypes;
// Process the discovered types
foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes))
@@ -449,7 +451,7 @@ partial class ID2D1ShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray<DiagnosticInfo>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var memberSymbol in structDeclarationSymbol.GetMembers())
{
@@ -475,7 +477,7 @@ partial class ID2D1ShaderGenerator
/// <param name="requiresScenePosition">Whether the shader type is declaring the need for scene position.</param>
/// <param name="usesPositionDependentMethods">Whether the shader is using APIs that rely on scene position.</param>
private static void ReportInvalidD2DRequiresScenePositionUse(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool requiresScenePosition,
bool usesPositionDependentMethods)
+25 -11
ファイルの表示
@@ -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
/// <param name="inputComplexIndices">The indices of the complex shader inputs.</param>
/// <param name="combinedInputTypes">The combined and serialized input types for each available input.</param>
public static void GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
out int inputCount,
out ImmutableArray<int> inputSimpleIndices,
@@ -40,8 +40,8 @@ partial class ID2D1ShaderGenerator
inputCount = 0;
ImmutableArray<int>.Builder inputSimpleIndicesBuilder = ImmutableArray.CreateBuilder<int>();
ImmutableArray<int>.Builder inputComplexIndicesBuilder = ImmutableArray.CreateBuilder<int>();
using ImmutableArrayBuilder<int> inputSimpleIndicesBuilder = ImmutableArrayBuilder<int>.Rent();
using ImmutableArrayBuilder<int> inputComplexIndicesBuilder = ImmutableArrayBuilder<int>.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<bool> selectedSimpleInputIndices = stackalloc bool[8];
Span<bool> 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<uint>.Builder combinedBuilder = ImmutableArray.CreateBuilder<uint>(inputCount);
using ImmutableArrayBuilder<uint> combinedBuilder = ImmutableArrayBuilder<uint>.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();
}
}
}
@@ -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<StatementSyntax>.Empty;
}
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
// Insert the fallback for empty shaders. This will generate the following code:
//
@@ -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
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions? GetCompileOptions(ImmutableArray<DiagnosticInfo>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
public static D2D1CompileOptions? GetCompileOptions(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
{
@@ -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<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
// global::System.Span<byte> data = stackalloc byte[<CONSTANT_BUFFER_SIZE>];
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<ExpressionSyntax>(
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<byte> data = stackalloc byte[<CONSTANT_BUFFER_SIZE>];
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<ExpressionSyntax>(
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(
@@ -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
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> 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<int>.Builder builder = ImmutableArray.CreateBuilder<int>(rows);
using ImmutableArrayBuilder<int> builder = ImmutableArrayBuilder<int>.Rent();
for (int j = 0; j < rows; j++)
{
@@ -140,7 +141,7 @@ partial class ID2D1ShaderGenerator
elementName!,
rows,
columns,
builder.MoveToImmutable());
builder.ToImmutable());
}
else
{
@@ -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<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.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<byte> data = stackalloc byte[<INPUT_DESCRIPTIONS_SIZE>];
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(
@@ -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
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputDescriptions">The produced input descriptions for the shader.</param>
public static void GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
out ImmutableArray<InputDescription> inputDescriptions)
{
int inputCount = 0;
ImmutableArray<InputDescription>.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder<InputDescription>();
using ImmutableArrayBuilder<InputDescription> inputDescriptionsBuilder = ImmutableArrayBuilder<InputDescription>.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<bool> 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];
@@ -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<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.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<byte> data = stackalloc byte[<RESOURCE_TEXTURE_DESCRIPTIONS_SIZE>];
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(
@@ -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
/// <param name="inputCount">The number of inputs for the shader.</param>
/// <param name="resourceTextureDescriptions">The produced resource texture descriptions for the shader.</param>
public static void GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
int inputCount,
out ImmutableArray<ResourceTextureDescription> 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<IFieldSymbol>())
{
@@ -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<ResourceTextureDescription> resourceTextureDescriptionsBuilder = ImmutableArrayBuilder<ResourceTextureDescription>.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<bool> 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];
+2 -1
ファイルの表示
@@ -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<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
+2 -3
ファイルの表示
@@ -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
/// <summary>
/// The collection of produced <see cref="DiagnosticInfo"/> instances.
/// </summary>
protected readonly ImmutableArray<DiagnosticInfo>.Builder Diagnostics;
protected readonly ImmutableArrayBuilder<DiagnosticInfo> Diagnostics;
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
@@ -58,7 +57,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
{
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
+2 -3
ファイルの表示
@@ -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<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
bool isEntryPoint)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
@@ -106,7 +105,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.staticMethods = staticMethods;
+1 -2
ファイルの表示
@@ -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<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArray<DiagnosticInfo>.Builder diagnostics)
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
}
+3 -2
ファイルの表示
@@ -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
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<DiagnosticInfo>.Builder diagnostics,
this ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
@@ -33,7 +34,7 @@ internal static class DiagnosticsExtensions
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<DiagnosticInfo>.Builder diagnostics,
this ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
+64 -5
ファイルの表示
@@ -12,7 +12,7 @@ namespace ComputeSharp.SourceGeneration.Helpers;
/// A helper type to build sequences of values with pooled buffers.
/// </summary>
/// <typeparam name="T">The type of items to create sequences for.</typeparam>
internal ref struct ImmutableArrayBuilder<T>
internal struct ImmutableArrayBuilder<T> : IDisposable
{
/// <summary>
/// The shared <see cref="ObjectPool{T}"/> instance to share <see cref="Writer"/> objects.
@@ -49,6 +49,24 @@ internal ref struct ImmutableArrayBuilder<T>
this.writer = writer;
}
/// <summary>
/// Gets the data written to the underlying buffer so far, as a <see cref="ReadOnlySpan{T}"/>.
/// </summary>
public readonly ReadOnlySpan<T> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.writer!.WrittenSpan;
}
/// <summary>
/// Gets the number of elements currently written in the current instance.
/// </summary>
public readonly int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.writer!.WrittenSpan.Length;
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.Add(T)"/>
public readonly void Add(T item)
{
@@ -64,6 +82,16 @@ internal ref struct ImmutableArrayBuilder<T>
this.writer!.AddRange(items);
}
/// <summary>
/// Inserts an item to the builder at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param>
public readonly void Insert(int index, T item)
{
this.writer!.Insert(index, item);
}
/// <inheritdoc cref="ImmutableArray{T}.Builder.ToImmutable"/>
public readonly ImmutableArray<T> ToImmutable()
{
@@ -84,7 +112,7 @@ internal ref struct ImmutableArrayBuilder<T>
return this.writer!.WrittenSpan.ToString();
}
/// <inheritdoc cref="IDisposable.Dispose"/>
/// <inheritdoc/>
public void Dispose()
{
Writer? writer = this.writer;
@@ -131,9 +159,7 @@ internal ref struct ImmutableArrayBuilder<T>
this.index = 0;
}
/// <summary>
/// Gets the data written to the underlying buffer so far, as a <see cref="ReadOnlySpan{T}"/>.
/// </summary>
/// <inheritdoc cref="ImmutableArrayBuilder{T}.WrittenSpan"/>
public ReadOnlySpan<T> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -158,6 +184,25 @@ internal ref struct ImmutableArrayBuilder<T>
this.index += items.Length;
}
/// <inheritdoc cref="ImmutableArrayBuilder{T}.Insert"/>
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++;
}
/// <summary>
/// Clears the items in the current writer.
/// </summary>
@@ -201,4 +246,18 @@ internal ref struct ImmutableArrayBuilder<T>
this.array = newArray;
}
}
}
/// <summary>
/// Private helpers for the <see cref="ImmutableArrayBuilder{T}"/> type.
/// </summary>
file static class ImmutableArrayBuilder
{
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> for <c>"index"</c>.
/// </summary>
public static void ThrowArgumentOutOfRangeExceptionForIndex()
{
throw new ArgumentOutOfRangeException("index");
}
}
+1 -1
ファイルの表示
@@ -27,7 +27,7 @@ internal sealed partial record HierarchyInfo(string FilenameHint, string FullyQu
/// <returns>A <see cref="HierarchyInfo"/> instance describing <paramref name="typeSymbol"/>.</returns>
public static HierarchyInfo From(INamedTypeSymbol typeSymbol)
{
ImmutableArray<TypeInfo>.Builder hierarchy = ImmutableArray.CreateBuilder<TypeInfo>();
using ImmutableArrayBuilder<TypeInfo> hierarchy = ImmutableArrayBuilder<TypeInfo>.Rent();
for (INamedTypeSymbol? parent = typeSymbol;
parent is not null;
@@ -84,7 +84,8 @@ partial class IShaderGenerator
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
StringBuilder textBuilder = new();
int capturedDelegates = 0;
int prologueStatements = 0;
+20 -17
ファイルの表示
@@ -37,7 +37,7 @@ partial class IShaderGenerator
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <returns>The resulting info on the processed shader.</returns>
public static HlslShaderSourceInfo GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> 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<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> 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<IFieldSymbol>())
@@ -192,14 +193,14 @@ partial class IShaderGenerator
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
SemanticModelProvider semanticModel,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> 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<FieldDeclarationSyntax>())
{
@@ -259,11 +260,11 @@ partial class IShaderGenerator
/// <param name="types">The collection of currently discovered types.</param>
/// <returns>A sequence of captured members in <paramref name="structDeclarationSymbol"/>.</returns>
private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
ICollection<INamedTypeSymbol> 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<IFieldSymbol>())
{
@@ -321,7 +322,7 @@ partial class IShaderGenerator
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> 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
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> 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();
}
/// <summary>
@@ -446,13 +448,14 @@ partial class IShaderGenerator
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
ISymbol sourceSymbol,
IEnumerable<INamedTypeSymbol> types,
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods)
{
ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>();
IReadOnlyCollection<INamedTypeSymbol> invalidTypes;
using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent();
IReadOnlyCollection <INamedTypeSymbol> invalidTypes;
// Process the discovered types
foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes))
@@ -514,7 +517,7 @@ partial class IShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray<DiagnosticInfo>.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol)
private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder<DiagnosticInfo> diagnostics, INamedTypeSymbol structDeclarationSymbol)
{
foreach (var memberSymbol in structDeclarationSymbol.GetMembers())
{
+2 -1
ファイルの表示
@@ -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
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
bool supportsDynamicShaders)
+70 -63
ファイルの表示
@@ -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<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
bool isComputeShader = shaderType == ShaderType.ComputeShader;
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
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<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
if (resourceCount > 0)
{
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
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<ExpressionSyntax>(
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<uint> span0 = stackalloc uint[<VARIABLES>];
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<ExpressionSyntax>(
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<ulong> span1 = stackalloc ulong[<RESOURCES>];
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<ExpressionSyntax>(
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(
+4 -3
ファイルの表示
@@ -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
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> 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<int>.Builder builder = ImmutableArray.CreateBuilder<int>(rows);
using ImmutableArrayBuilder<int> builder = ImmutableArrayBuilder<int>.Rent();
for (int j = 0; j < rows; j++)
{
@@ -165,7 +166,7 @@ partial class IShaderGenerator
elementName!,
rows,
columns,
builder.MoveToImmutable());
builder.ToImmutable());
}
else
{
@@ -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
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
using ImmutableArrayBuilder<StatementSyntax> statements = ImmutableArrayBuilder<StatementSyntax>.Rent();
// global::System.Span<byte> span0 = stackalloc byte[5];
statements.Add(
+3 -1
ファイルの表示
@@ -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<FieldInfo> capturedFields)
{
ImmutableArray<ResourceDescriptor>.Builder descriptors = ImmutableArray.CreateBuilder<ResourceDescriptor>();
using ImmutableArrayBuilder<ResourceDescriptor> descriptors = ImmutableArrayBuilder<ResourceDescriptor>.Rent();
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
+2 -1
ファイルの表示
@@ -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<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
// GetDispatchId() info
ImmutableArray<string> dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
+3 -3
ファイルの表示
@@ -79,7 +79,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
IMethodSymbol methodSymbol,
out ImmutableArray<DiagnosticInfo> diagnostics)
{
ImmutableArray<DiagnosticInfo>.Builder builder = ImmutableArray.CreateBuilder<DiagnosticInfo>();
using ImmutableArrayBuilder<DiagnosticInfo> builder = ImmutableArrayBuilder<DiagnosticInfo>.Rent();
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
@@ -112,7 +112,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
ImmutableArray<DiagnosticInfo>.Builder diagnostics,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
CSharpSyntaxNode methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> 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)
-1
ファイルの表示
@@ -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;
-1
ファイルの表示
@@ -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;