From 86488b4563979ceb842937c396b3e6d818bf44cb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 5 Dec 2021 01:55:08 +0100 Subject: [PATCH 01/36] Update HashCode polyfill in generator project --- .../Helpers/HashCode.cs | 384 ++++++++++++++++-- 1 file changed, 357 insertions(+), 27 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs index 1861ee67..19030b40 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs @@ -1,47 +1,377 @@ -namespace System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; + +#pragma warning disable CS0809 + +namespace System; /// /// A polyfill type that mirrors some methods from on .NET 6. /// internal struct HashCode { + private const uint Prime1 = 2654435761U; + private const uint Prime2 = 2246822519U; + private const uint Prime3 = 3266489917U; + private const uint Prime4 = 668265263U; + private const uint Prime5 = 374761393U; + + private static readonly uint seed = GenerateGlobalSeed(); + + private uint v1, v2, v3, v4; + private uint queue1, queue2, queue3; + private uint length; + /// - /// Combines six values into a hash code. + /// Initializes the default seed. /// - /// The type of the first value to combine into the hash code. - /// The type of the second value to combine into the hash code. - /// The type of the third value to combine into the hash code. - /// The type of the fourth value to combine into the hash code. - /// The type of the fifth value to combine into the hash code. - /// The type of the sixth value to combine into the hash code. - /// The first value to combine into the hash code. - /// The second value to combine into the hash code. - /// The third value to combine into the hash code. - /// The fourth value to combine into the hash code. - /// The fifth value to combine into the hash code. - /// The sixth value to combine into the hash code. - /// The hash code that represents the six values. + /// A random seed. + [Pure] + private static unsafe uint GenerateGlobalSeed() + { + byte[] bytes = new byte[4]; + + RandomNumberGenerator.Create().GetBytes(bytes); + + return BitConverter.ToUInt32(bytes, 0); + } + + public static int Combine(T1 value1) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hash = MixEmptyState(); + + hash += 4; + hash = QueueRound(hash, hc1); + hash = MixFinal(hash); + + return (int)hash; + } + + public static int Combine(T1 value1, T2 value2) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hash = MixEmptyState(); + + hash += 8; + hash = QueueRound(hash, hc1); + hash = QueueRound(hash, hc2); + hash = MixFinal(hash); + + return (int)hash; + } + + public static int Combine(T1 value1, T2 value2, T3 value3) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hc3 = (uint)(value3?.GetHashCode() ?? 0); + uint hash = MixEmptyState(); + + hash += 12; + hash = QueueRound(hash, hc1); + hash = QueueRound(hash, hc2); + hash = QueueRound(hash, hc3); + hash = MixFinal(hash); + + return (int)hash; + } + + public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hc3 = (uint)(value3?.GetHashCode() ?? 0); + uint hc4 = (uint)(value4?.GetHashCode() ?? 0); + + Initialize(out uint v1, out uint v2, out uint v3, out uint v4); + + v1 = Round(v1, hc1); + v2 = Round(v2, hc2); + v3 = Round(v3, hc3); + v4 = Round(v4, hc4); + + uint hash = MixState(v1, v2, v3, v4); + + hash += 16; + hash = MixFinal(hash); + + return (int)hash; + } + + public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hc3 = (uint)(value3?.GetHashCode() ?? 0); + uint hc4 = (uint)(value4?.GetHashCode() ?? 0); + uint hc5 = (uint)(value5?.GetHashCode() ?? 0); + + Initialize(out uint v1, out uint v2, out uint v3, out uint v4); + + v1 = Round(v1, hc1); + v2 = Round(v2, hc2); + v3 = Round(v3, hc3); + v4 = Round(v4, hc4); + + uint hash = MixState(v1, v2, v3, v4); + + hash += 20; + hash = QueueRound(hash, hc5); + hash = MixFinal(hash); + + return (int)hash; + } + public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) { - throw new NotSupportedException(); + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hc3 = (uint)(value3?.GetHashCode() ?? 0); + uint hc4 = (uint)(value4?.GetHashCode() ?? 0); + uint hc5 = (uint)(value5?.GetHashCode() ?? 0); + uint hc6 = (uint)(value6?.GetHashCode() ?? 0); + + Initialize(out uint v1, out uint v2, out uint v3, out uint v4); + + v1 = Round(v1, hc1); + v2 = Round(v2, hc2); + v3 = Round(v3, hc3); + v4 = Round(v4, hc4); + + uint hash = MixState(v1, v2, v3, v4); + + hash += 24; + hash = QueueRound(hash, hc5); + hash = QueueRound(hash, hc6); + hash = MixFinal(hash); + + return (int)hash; + } + + public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hc3 = (uint)(value3?.GetHashCode() ?? 0); + uint hc4 = (uint)(value4?.GetHashCode() ?? 0); + uint hc5 = (uint)(value5?.GetHashCode() ?? 0); + uint hc6 = (uint)(value6?.GetHashCode() ?? 0); + uint hc7 = (uint)(value7?.GetHashCode() ?? 0); + + Initialize(out uint v1, out uint v2, out uint v3, out uint v4); + + v1 = Round(v1, hc1); + v2 = Round(v2, hc2); + v3 = Round(v3, hc3); + v4 = Round(v4, hc4); + + uint hash = MixState(v1, v2, v3, v4); + + hash += 28; + hash = QueueRound(hash, hc5); + hash = QueueRound(hash, hc6); + hash = QueueRound(hash, hc7); + hash = MixFinal(hash); + + return (int)hash; + } + + public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) + { + uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc2 = (uint)(value2?.GetHashCode() ?? 0); + uint hc3 = (uint)(value3?.GetHashCode() ?? 0); + uint hc4 = (uint)(value4?.GetHashCode() ?? 0); + uint hc5 = (uint)(value5?.GetHashCode() ?? 0); + uint hc6 = (uint)(value6?.GetHashCode() ?? 0); + uint hc7 = (uint)(value7?.GetHashCode() ?? 0); + uint hc8 = (uint)(value8?.GetHashCode() ?? 0); + + Initialize(out uint v1, out uint v2, out uint v3, out uint v4); + + v1 = Round(v1, hc1); + v2 = Round(v2, hc2); + v3 = Round(v3, hc3); + v4 = Round(v4, hc4); + + v1 = Round(v1, hc5); + v2 = Round(v2, hc6); + v3 = Round(v3, hc7); + v4 = Round(v4, hc8); + + uint hash = MixState(v1, v2, v3, v4); + + hash += 32; + hash = MixFinal(hash); + + return (int)hash; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) + { + v1 = seed + Prime1 + Prime2; + v2 = seed + Prime2; + v3 = seed; + v4 = seed - Prime1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint Round(uint hash, uint input) + { + return RotateLeft(hash + input * Prime2, 13) * Prime1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint QueueRound(uint hash, uint queuedValue) + { + return RotateLeft(hash + queuedValue * Prime3, 17) * Prime4; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint MixState(uint v1, uint v2, uint v3, uint v4) + { + return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18); + } + + private static uint MixEmptyState() + { + return seed + Prime5; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint MixFinal(uint hash) + { + hash ^= hash >> 15; + hash *= Prime2; + hash ^= hash >> 13; + hash *= Prime3; + hash ^= hash >> 16; + + return hash; } - /// - /// Adds a single value to the hash code. - /// - /// The type of the value to add to the hash code. - /// The value to add to the hash code. public void Add(T value) { - throw new NotSupportedException(); + Add(value?.GetHashCode() ?? 0); + } + + public void Add(T value, IEqualityComparer? comparer) + { + Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode())); + } + + /// Adds a span of bytes to the hash code. + /// The span. + /// + /// This method does not guarantee that the result of adding a span of bytes will match + /// the result of adding the same bytes individually. + /// + public void AddBytes(ReadOnlySpan value) + { + ref byte pos = ref MemoryMarshal.GetReference(value); + ref byte end = ref Unsafe.Add(ref pos, value.Length); + + while ((nint)Unsafe.ByteOffset(ref pos, ref end) >= sizeof(int)) + { + Add(Unsafe.ReadUnaligned(ref pos)); + pos = ref Unsafe.Add(ref pos, sizeof(int)); + } + + while (Unsafe.IsAddressLessThan(ref pos, ref end)) + { + Add((int)pos); + pos = ref Unsafe.Add(ref pos, 1); + } + } + + private void Add(int value) + { + uint val = (uint)value; + uint previousLength = length++; + uint position = previousLength % 4; + + if (position == 0) + { + queue1 = val; + } + else if (position == 1) + { + queue2 = val; + } + else if (position == 2) + { + queue3 = val; + } + else + { + if (previousLength == 3) + { + Initialize(out v1, out v2, out v3, out v4); + } + + v1 = Round(v1, queue1); + v2 = Round(v2, queue2); + v3 = Round(v3, queue3); + v4 = Round(v4, val); + } } - /// - /// Calculates the final hash code after consecutive invocations. - /// - /// The calculated hash code. public int ToHashCode() { - throw new NotSupportedException(); + uint length = this.length; + uint position = length % 4; + uint hash = length < 4 ? MixEmptyState() : MixState(v1, v2, v3, v4); + + hash += length * 4; + + if (position > 0) + { + hash = QueueRound(hash, queue1); + + if (position > 1) + { + hash = QueueRound(hash, queue2); + + if (position > 2) + { + hash = QueueRound(hash, queue3); + } + } + } + + hash = MixFinal(hash); + + return (int)hash; + } + + /// + [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => throw new NotSupportedException(); + + /// + [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object? obj) => throw new NotSupportedException(); + + /// + /// Rotates the specified value left by the specified number of bits. + /// Similar in behavior to the x86 instruction ROL. + /// + /// The value to rotate. + /// The number of bits to rotate by. + /// Any value outside the range [0..31] is treated as congruent mod 32. + /// The rotated value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint RotateLeft(uint value, int offset) + { + return (value << offset) | (value >> (32 - offset)); } } \ No newline at end of file From fd820a67c7cc5a37a2e3ee44b772c912fe275d3b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 5 Dec 2021 01:55:41 +0100 Subject: [PATCH 02/36] Add incremental generation for GetDispatchId --- ...r.Incremental.CreateGetDispatchIdMethod.cs | 113 +++++++++++ .../IShaderGenerator.Incremental.cs | 182 ++++++++++++++++++ .../Models/HierarchyInfo.cs | 59 ++++++ 3 files changed, 354 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs new file mode 100644 index 00000000..53d58a4c --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs @@ -0,0 +1,113 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using ComputeSharp.__Internals; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator +{ + /// + /// Extracts the names of all instance fields of a type. + /// + /// The input instance to process. + /// The names of all instance fields within . + [Pure] + private static ImmutableArray GetDelegateFieldNames(INamedTypeSymbol structDeclarationSymbol) + { + return + structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .Select(static member => member.Name) + .ToImmutableArray(); + } + + /// + /// Creates a instance for the GetDispatchId method. + /// + ///The names of all instance fields within the current shader type. + /// The resulting instance for the GetDispatchId method. + private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames) + { + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(delegateFieldNames)); + } + + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The names of all instance fields within the current shader type. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) + { + if (delegateFieldNames.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List blockStatements = new(4); + + // global::System.HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("global::System.HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + foreach (string fieldName in delegateFieldNames) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(fieldName), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs new file mode 100644 index 00000000..0f1d1c87 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator : IIncrementalGenerator +{ + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + // Check whether [SkipLocalsInit] can be used + IncrementalValueProvider canUseSkipLocalsInit = + context.CompilationProvider + .Select(static (compilation, token) => + compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && + compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null); + + // Get all declared struct types and their type symbols + IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = + context.SyntaxProvider.CreateSyntaxProvider( + static (node, token) => node is StructDeclarationSyntax structDeclaration, + static (context, token) => ( + (StructDeclarationSyntax)context.Node, + Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) + .Where(static pair => pair.Symbol is not null)!; + + // Get the symbol for the IComputeShader interface + IncrementalValueProvider iComputeShaderSymbol = + context.CompilationProvider + .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName))!; + + // Get the symbol for the IPixelShader interface + IncrementalValueProvider iPixelShaderSymbol = + context.CompilationProvider + .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName))!; + + // Filter struct declarations that implement a shader interface, and also gather the shader type + IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, Type Type)> shaderDeclarations = + structDeclarations + .Combine(iComputeShaderSymbol.Combine(iPixelShaderSymbol)) + .Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Left, item.Right.Right))) + .Where(static item => item.Type is not null) + .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, item.Type!)); + + // Get the hierarchy info and delegate field names for each shader type + IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray Delegates)> hierarchyInfoAndShaderFieldNames = + shaderDeclarations + .Select(static (item, token) => (HierarchyInfo.From(item.Symbol), GetDelegateFieldNames(item.Symbol))); + + // Generate the GetDispatchId() methods + context.RegisterSourceOutput(hierarchyInfoAndShaderFieldNames.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Delegates); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); + } + + /// + /// Gets the shader type for a given shader, if any. + /// + /// The input instance to check. + /// The instance for . + /// The instance for . + /// Either or , or . + [Pure] + private static Type? GetShaderType( + INamedTypeSymbol typeSymbol, + INamedTypeSymbol iComputeShaderSymbol, + INamedTypeSymbol iPixelShaderSymbol) + { + foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces) + { + if (interfaceSymbol.Name == nameof(IComputeShader) && + SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol)) + { + return typeof(IComputeShader); + } + + if (interfaceSymbol.IsGenericType && + interfaceSymbol.Name == nameof(IPixelShader) && + SymbolEqualityComparer.Default.Equals(interfaceSymbol, interfaceSymbol.ConstructUnboundGenericType())) + { + return typeof(IPixelShader<>); + } + } + + return null; + } + + /// + /// Creates a instance wrapping the given method. + /// + /// The instance for the current type. + /// The item to insert. + /// Whether [SkipLocalsInit] can be used. + /// A object wrapping . + [Pure] + private static CompilationUnitSyntax GetCompilationUnitFromMethod( + HierarchyInfo hierarchyInfo, + MethodDeclarationSyntax methodDeclaration, + bool canUseSkipLocalsInit) + { + // Method attributes + List attributes = new() + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code")))))) + }; + + // Add [SkipLocalsInit] if the target project allows it + if (canUseSkipLocalsInit) + { + attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); + } + + // Create the partial shader type declaration with the given method implementation. + // This code produces a struct declaration as follows: + // + // partial struct + // { + // + // } + StructDeclarationSyntax structDeclarationSyntax = + StructDeclaration(hierarchyInfo.Names[0]) + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray())); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) + { + typeDeclarationSyntax = + ClassDeclaration(parentType) + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(typeDeclarationSyntax); + } + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // #pragma warning disable + // + // namespace ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs new file mode 100644 index 00000000..6d098bed --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model describing the hierarchy info for a specific type. +/// +/// The filename hint for the current type. +/// Gets the namespace for the current type. +/// Gets the sequence of type definitions containing the current type. +internal sealed record HierarchyInfo(string FilenameHint, string Namespace, ImmutableArray Names) +{ + /// + /// Creates a new instance from a given . + /// + /// The input instance to gather info for. + /// A instance describing . + [Pure] + public static HierarchyInfo From(INamedTypeSymbol typeSymbol) + { + ImmutableArray.Builder names = ImmutableArray.CreateBuilder(); + + for (INamedTypeSymbol? parent = typeSymbol; + parent is not null; + parent = parent.ContainingType) + { + names.Add(parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); + } + + return new( + typeSymbol.GetGeneratedFileName(), + typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)), + names.ToImmutable()); + } + + /// + [Pure] + public bool Equals(HierarchyInfo? other) + { + return + other is not null && + (ReferenceEquals(this, other) || + (Namespace == other.Namespace && + (Names == other.Names || + Names.AsSpan().SequenceEqual(other.Names.AsSpan())))); + } + + /// + [Pure] + public override int GetHashCode() + { + return HashCode.Combine(Namespace, Names, Names[0]); + } +} From 4b1180225d7b3e4f952d78f208d369719a35440b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 5 Dec 2021 13:30:18 +0100 Subject: [PATCH 03/36] Fix IPixelShader lookup, switch GetDispatchId() to incremental --- ...derGenerator.Incremental.CreateGetDispatchIdMethod.cs | 2 +- .../IShaderGenerator.Incremental.cs | 9 ++++++--- src/ComputeSharp.SourceGenerators/IShaderGenerator.cs | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs index 53d58a4c..93f92739 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs @@ -13,7 +13,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator +public sealed partial class IShaderGenerator2 { /// /// Extracts the names of all instance fields of a type. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 0f1d1c87..be881c4c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -13,8 +13,11 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; -/// -public sealed partial class IShaderGenerator : IIncrementalGenerator +/// +/// A source generator creating data loaders for and types. +/// +[Generator] +public sealed partial class IShaderGenerator2 : IIncrementalGenerator { /// public void Initialize(IncrementalGeneratorInitializationContext context) @@ -91,7 +94,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator if (interfaceSymbol.IsGenericType && interfaceSymbol.Name == nameof(IPixelShader) && - SymbolEqualityComparer.Default.Equals(interfaceSymbol, interfaceSymbol.ConstructUnboundGenericType())) + SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol)) { return typeof(IPixelShader<>); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index cf231bf6..d76a8e0c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -65,7 +65,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator // Reorder the method declarations to respect the order in the interface definition MethodDeclarationSyntax[] methods = { - getDispatchIdMethod, + // getDispatchIdMethod, loadDispatchDataMethod, loadDispatchMetadataMethod, buildHlslStringMethod, From 1b465e7b9d3237e7ba82e080ea60c8a555dff4ff Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 5 Dec 2021 14:20:15 +0100 Subject: [PATCH 04/36] Switch LoadDispatchData() to incremental --- ...ncremental.CreateLoadDispatchDataMethod.cs | 422 ++++++++++++++++++ .../IShaderGenerator.Incremental.cs | 36 +- .../IShaderGenerator.cs | 2 +- .../Models/FieldInfo.cs | 42 ++ 4 files changed, 495 insertions(+), 7 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs new file mode 100644 index 00000000..e1c56267 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs @@ -0,0 +1,422 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The current type being explored. + /// The type of shader interface urrently being processed. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The sequence of instances for all captured resources and values. + private static ImmutableArray GetCapturedFieldInfos( + ITypeSymbol currentTypeSymbol, + Type shaderInterfaceType, + out int resourceCount, + out int root32BitConstantCount) + { + // Helper method that uses boxes instead of ref-s (illegal in enumerators) + static IEnumerable GetCapturedFieldInfos( + ITypeSymbol currentTypeSymbol, + ImmutableArray fieldPath, + StrongBox resourceOffset, + StrongBox rawDataOffset) + { + bool isFirstField = true; + + foreach ( + IFieldSymbol fieldSymbol in + from fieldSymbol in currentTypeSymbol.GetMembers().OfType() + where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && + !fieldSymbol.IsConst && !fieldSymbol.IsStatic && + !fieldSymbol.IsFixedSizeBuffer + select fieldSymbol) + { + string fieldName = fieldSymbol.Name; + string typeName = fieldSymbol.Type.GetFullMetadataName(); + + // Disambiguates the name of target fields against the current input parameters + if (fieldName is "loader" or "device" or "x" or "y" or "z") + { + fieldName = $"this.{fieldName}"; + } + + // The first item in each nested struct needs to be aligned to 16 bytes + if (isFirstField && fieldPath.Length > 0) + { + rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16); + + isFirstField = false; + } + + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++); + } + else if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value); + } + else if (fieldSymbol.Type.IsUnmanagedType) + { + // Custom struct type defined by the user + foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), resourceOffset, rawDataOffset)) + { + yield return fieldInfo; + } + } + } + } + + // Setup the resource and byte offsets for tracking. Pixel shaders have only two + // implicitly captured int values, as they're always dispatched over a 2D texture. + bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); + StrongBox resourceOffsetAsBox = new(); + StrongBox rawDataOffsetAsBox = new(initialRawDataOffset); + + // Traverse all shader fields and gather info, and update the tracking offsets + ImmutableArray fieldInfos = GetCapturedFieldInfos( + currentTypeSymbol, + ImmutableArray.Empty, + resourceOffsetAsBox, + rawDataOffsetAsBox).ToImmutableArray(); + + resourceCount = resourceOffsetAsBox.Value; + + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to a multiple of a 32 bit value. This is necessary to + // enable loading all the dispatch data after reinterpreting it to a sequence of values + // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. + root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); + + return fieldInfos; + } + + /// + /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix). + /// + /// The current path of the field with respect to the shader instance. + /// The type name currently being read. + /// The current offset within the loaded data buffer. + private static FieldInfo GetHlslKnownTypeFieldInfo( + ImmutableArray fieldPath, + string typeName, + ref int rawDataOffset) + { + // For scalar, vector and linear matrix types, serialize the value normally. + // Only the initial alignment needs to be considered, while data is packed. + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); + + // Check if the current type is a matrix type with more than one row. In this + // case, each row is aligned as if it was a separate array, so the start of + // 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); + + for (int j = 0; j < rows; j++) + { + int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + builder.Add(startingRawDataOffset); + + rawDataOffset = startingRawDataOffset + fieldPack * columns; + } + + return new FieldInfo.NonLinearMatrix( + fieldPath, + typeName, + elementName!, + rows, + columns, + builder.MoveToImmutable()); + } + else + { + // Calculate the right offset with 16-bytes padding (HLSL constant buffer). + // Since we're in a constant buffer, we need to both pad the starting offset + // to be aligned to the packing size of the type, and also to align the initial + // offset to ensure that values do not cross 16 bytes boundaries either. + int startingRawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + rawDataOffset = startingRawDataOffset + fieldSize; + + return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); + } + } + + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The input instance to use. + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting instance for the LoadDispatchDataMethod method. + private static MethodDeclarationSyntax CreateLoadDispatchDataMethod( + SourceProductionContext context, + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TDataLoader")), + Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), + Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(GetDispatchDataLoadingStatements(context, shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader. + /// + /// The current generator context in use. + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchDataLoadingStatements( + SourceProductionContext context, + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + + // Append the statements for the dispatch ranges: + // + // span0[0] = (uint)x; + // span0[1] = (uint)y; + // span0[2] = (uint)z; + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); + + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .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) + { + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); + } + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Resource resource: + + // Validate the resource and get a handle for it. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) = + // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device); + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"), + ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)")))); + break; + case FieldInfo.Primitive primitive: + + // Read a primitive value and serialize it into the target buffer. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.As>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), + ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + + // Declare a local to index into individual rows. This will generate: + // + // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); + for (int j = 0; j < matrix.Rows; j++) + { + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); + } + break; + } + } + + // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. + // Loaded values in the root signature have the following costs: + // - Root constants cost 1 DWORD each, since they are 32-bit values. + // - Descriptor tables cost 1 DWORD each. + // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. + // So here we check whether the current signature respects that constraint, + // and emit a build error otherwise. For more info on this, see the docs here: + // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. + int rootSignatureDwordSize = root32BitConstantsCount + resourceCount; + + if (rootSignatureDwordSize > 64) + { + // TODO + //context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); + context.ReportDiagnostic(Diagnostic.Create(ShaderDispatchDataSizeExceeded, null)); + } + + // 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( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedValues"))) + .AddArgumentListArguments(Argument(IdentifierName("span0"))))); + + 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( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedResources"))) + .AddArgumentListArguments(Argument(IdentifierName("span1"))))); + } + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index be881c4c..74bcf298 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -48,27 +48,51 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.CompilationProvider .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName))!; - // Filter struct declarations that implement a shader interface, and also gather the shader type - IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, Type Type)> shaderDeclarations = + // Filter struct declarations that implement a shader interface, and also gather the hierarchy info and shader type + IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy, Type Type)> shaderDeclarations = structDeclarations .Combine(iComputeShaderSymbol.Combine(iPixelShaderSymbol)) .Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Left, item.Right.Right))) .Where(static item => item.Type is not null) - .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, item.Type!)); + .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol), item.Type!)); // Get the hierarchy info and delegate field names for each shader type - IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray Delegates)> hierarchyInfoAndShaderFieldNames = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray Delegates)> hierarchyInfoAndDelegateFieldNames = shaderDeclarations - .Select(static (item, token) => (HierarchyInfo.From(item.Symbol), GetDelegateFieldNames(item.Symbol))); + .Select(static (item, token) => (item.Hierarchy, GetDelegateFieldNames(item.Symbol))); // Generate the GetDispatchId() methods - context.RegisterSourceOutput(hierarchyInfoAndShaderFieldNames.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(hierarchyInfoAndDelegateFieldNames.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Delegates); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); + + // Get the hierarchy info and captured field infos for each shader type + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Type Type, ImmutableArray FieldInfos, int ResourceCount, int Root32BitConstantCount)> hierarchyInfoAndCaptureFieldInfos = + shaderDeclarations + .Select(static (item, token) => ( + item.Hierarchy, + item.Type, + FieldInfos: GetCapturedFieldInfos(item.Symbol, item.Type, out int resourceCount, out int root32BitConstantCount), + ResourceCount: resourceCount, + Root32BitConstantCount: root32BitConstantCount)); + + // Generate the LoadDispatchData() methods + context.RegisterSourceOutput(hierarchyInfoAndCaptureFieldInfos.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod( + context, + item.Left.Type, + item.Left.FieldInfos, + item.Left.ResourceCount, + item.Left.Root32BitConstantCount); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchData", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index d76a8e0c..59bd0aae 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -66,7 +66,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator MethodDeclarationSyntax[] methods = { // getDispatchIdMethod, - loadDispatchDataMethod, + // loadDispatchDataMethod, loadDispatchMetadataMethod, buildHlslStringMethod, tryGetBytecodeMethod diff --git a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs new file mode 100644 index 00000000..17e3c83e --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A base type for a model describing a given captured field in a shader. +/// +internal abstract record FieldInfo +{ + /// + /// A captured resource (either a buffer or a texture). + /// + /// The name of the resource field. + /// The full metadata name for the resource type. + /// The offset for the resource within the root signature. + public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured primitive value (either a scalar, a vector, or a linear matrix). + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the primitive type. + /// The byte offset of the value within the root signature. + public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured non linear matrix value. + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the matrix type. + /// The name of each element in the matrix type. + /// The number of rows in the matrix. + /// The number of columns in the matrix. + /// The sequence of byte offsets for each row within the root signature. + public sealed record NonLinearMatrix( + ImmutableArray FieldPath, + string TypeName, + string ElementName, + int Rows, + int Columns, + ImmutableArray Offsets) : FieldInfo; +} From b912b4f0760451415ffce09afc5984c071f00284 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 5 Dec 2021 23:25:43 +0100 Subject: [PATCH 05/36] Implement GetNonDynamicHlslSourceInfo() method This includes the data gathering step for the HLSL rewrite pipeline --- .../Diagnostics/DiagnosticsExtensions.cs | 35 +- ...Incremental.GetNonDynamicHlslSourceInfo.cs | 705 ++++++++++++++++++ .../Mappings/HlslKnownTypes.cs | 20 + .../Models/NonDynamicHlslSourceInfo.cs | 87 +++ .../ExecuteMethodRewriter.Incremental.cs | 191 +++++ ...lSourceRewriter.Incremental.Diagnostics.cs | 205 +++++ .../HlslSourceRewriter.Incremental.cs | 342 +++++++++ .../ShaderSourceRewriter.Incremental.cs | 443 +++++++++++ .../StaticFieldRewriter.Incremental.cs | 134 ++++ 9 files changed, 2161 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs create mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs index a5894cd6..5ff64485 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Collections.Immutable; +using System.Linq; using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGenerators.Diagnostics; @@ -39,4 +40,36 @@ internal static class DiagnosticsExtensions { context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args)); } + + /// + /// Adds a new diagnostics to the target builder. + /// + /// The collection of produced instances. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void Add( + this ImmutableArray.Builder diagnostics, + DiagnosticDescriptor descriptor, + ISymbol symbol, + params object[] args) + { + diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); + } + + /// + /// Adds a new diagnostics to the target builder. + /// + /// The collection of produced instances. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void Add( + this ImmutableArray.Builder diagnostics, + DiagnosticDescriptor descriptor, + SyntaxNode node, + params object[] args) + { + diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args)); + } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs new file mode 100644 index 00000000..183ad183 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs @@ -0,0 +1,705 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.Models; +using ComputeSharp.SourceGenerators.SyntaxRewriters; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618, RS1024 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input object currently in use. + /// The node to process. + /// The for . + /// The resulting instance for the BuildHlslString method. + /// + private static ((NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed), ImmutableArray Diagnostics) GetNonDynamicHlslSourceInfo( + Compilation compilation, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol) + { + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + + // Properties are not supported + DetectAndReportPropertyDeclarations(diagnostics, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) + { + diagnostics.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + } + + // Explore the syntax tree and extract the processed info + var semanticModelProvider = new SemanticModelProvider(compilation); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var instanceFields = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader); + var sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); + var declaredTypes = GetDeclaredTypes(discoveredTypes); + var definedConstants = GetDefinedConstants(constantDefinitions); + var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + + // Get the HLSL source data with the intermediate info + NonDynamicHlslSourceInfo sourceInfo = GetNonDynamicHlslSourceInfo( + definedConstants, + declaredTypes, + instanceFields, + staticFields, + sharedBuffers, + processedMethods, + isComputeShader, + implicitTextureType, + isSamplerUsed, + entryPoint); + + return ((sourceInfo, implicitTextureType, isSamplerUsed), diagnostics.ToImmutable()); + } + + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. + /// A sequence of captured fields in . + [Pure] + private static ImmutableArray<(string MetadataName, string Name, string HlslType)> GetInstanceFields( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types, + bool isComputeShader) + { + ImmutableArray<(string, string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string)>(); + bool hlslResourceFound = false; + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (fieldSymbol.IsStatic) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + // Group shared fields must be static + if (attribute is not null) + { + diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + hlslResourceFound = true; + + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } + } + else if (!typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) + { + // Shaders can only capture valid HLSL resource types or unmanaged types + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + + continue; + } + else if (typeSymbol.IsUnmanagedType && + !HlslKnownTypes.IsKnownHlslType(metadataName)) + { + // Track the type if it's a custom struct + types.Add(typeSymbol); + } + + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Yield back the current mapping for the name (if the name used a reserved keyword) + builder.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); + } + + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) + { + diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The collection of produced instances. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + [Pure] + private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + ImmutableArray.Builder diagnostics, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is not null) + { + continue; + } + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter2 staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + diagnostics); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + + builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + } + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is null) + { + continue; + } + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + if (!typeSymbol.ElementType.IsUnmanagedType) + { + diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize)); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The collection of produced instances. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. + /// A sequence of processed methods in , and the entry point. + [Pure] + private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( + ImmutableArray.Builder diagnostics, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + bool isComputeShader) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + string? entryPoint = null; + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + bool isSamplerUsed = false; + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); + + // Create the source rewriter for the current method + ShaderSourceRewriter2 shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + diagnostics, + isShaderEntryPoint); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; + + entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); + } + else + { + methods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + } + + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) + { + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (entryPoint!, methods.ToImmutable(), isSamplerUsed); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + + foreach (var constant in constantDefinitions) + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); + } + + return builder.MoveToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + { + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + builder.Add(( + structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); + } + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of declared types used by the shader. + /// The sequence of instance fields for the current shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of shared buffers declared by the shader. + /// The sequence of processed methods used by the shader. + /// Whether or not the current shader type is a compute shader. + /// The type of the implicit target texture, if present. + /// Whether the static sampler is used by the shader. + /// The body of the entry point of the shader. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static NonDynamicHlslSourceInfo GetNonDynamicHlslSourceInfo( + ImmutableArray<(string Name, string Value)> definedConstants, + ImmutableArray<(string Name, string Definition)> declaredTypes, + ImmutableArray<(string MetadataName, string Name, string HlslType)> instanceFields, + ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, + ImmutableArray<(string Signature, string Definition)> processedMethods, + bool isComputeShader, + string? implicitTextureType, + bool isSamplerUsed, + + string executeMethod) + { + StringBuilder hlslBuilder = new(); + + void AppendLF() + { + hlslBuilder.Append('\n'); + } + + void AppendLine(string text) + { + hlslBuilder.Append(text); + } + + void AppendLineAndLF(string text) + { + hlslBuilder.Append(text); + hlslBuilder.Append('\n'); + } + + void AppendCharacterAndLF(char c) + { + hlslBuilder.Append(c); + hlslBuilder.Append('\n'); + } + + string FlushText() + { + string text = hlslBuilder.ToString(); + + hlslBuilder.Clear(); + + return text; + } + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + + // Group size constants + AppendLF(); + AppendLine("#define __GroupSize__get_X "); + + string headerAndThreadsX = FlushText(); + + AppendLF(); + AppendLine("#define __GroupSize__get_Y "); + + string threadsY = FlushText(); + + AppendLF(); + AppendLine("#define __GroupSize__get_Z "); + + string threadsZ = FlushText(); + + AppendLF(); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + string defines = FlushText(); + + // Static fields + if (staticFields.Any()) + { + AppendLF(); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } + } + } + + // Declared types + foreach (var (_, typeDefinition) in declaredTypes) + { + AppendLF(); + AppendLineAndLF(typeDefinition); + } + + string staticFieldsAndDeclaredTypes = FlushText(); + + // Captured variables + AppendLF(); + AppendLineAndLF("cbuffer _ : register(b0)"); + AppendCharacterAndLF('{'); + AppendLineAndLF(" uint __x;"); + AppendLineAndLF(" uint __y;"); + + if (isComputeShader) + { + AppendLineAndLF(" uint __z;"); + } + + // User-defined values + foreach (var (_, fieldName, fieldType) in instanceFields.Where(static t => !HlslKnownTypes.IsTypedResourceType(t.MetadataName))) + { + AppendLineAndLF($" {fieldType} {fieldName};"); + } + + AppendCharacterAndLF('}'); + + int constantBuffersCount = 1; + int readOnlyBuffersCount = 0; + int readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + AppendLF(); + AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); + } + + // Optional sampler field + if (isSamplerUsed) + { + AppendLF(); + AppendLineAndLF("SamplerState __sampler : register(s);"); + } + + // Resources + foreach (var (metadataName, fieldName, fieldType) in instanceFields) + { + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); + AppendCharacterAndLF('{'); + AppendLineAndLF($" {fieldType} {fieldName}[2];"); + AppendCharacterAndLF('}'); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + } + else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + + AppendLF(); + AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); + } + + // Forward declarations + foreach (var (forwardDeclaration, _) in processedMethods) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); + + // Captured methods + foreach (var (_, method) in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + + string capturedMethods = FlushText(); + + // Entry point + AppendLF(); + AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); + AppendLineAndLF(executeMethod); + + string entryPoint = FlushText(); + + return new( + headerAndThreadsX, + threadsY, + threadsZ, + defines, + staticFieldsAndDeclaredTypes, + capturedFieldsAndResourcesAndForwardDeclarations, + capturedMethods, + entryPoint, + processedMethods.Select(static m => m.Signature).ToImmutableArray()); + } +} diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 25b7ae9d..2b92ca6e 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -149,6 +149,26 @@ internal static class HlslKnownTypes }; } + /// + /// Checks whether or not a given type name matches a writeable typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a writeable typed resource type. + public static bool IsReadWriteTypedResourceType(string typeName) + { + return typeName switch + { + "ComputeSharp.ReadWriteBuffer`1" or + "ComputeSharp.ReadWriteTexture2D`1" or + "ComputeSharp.ReadWriteTexture2D`2" or + "ComputeSharp.ReadWriteTexture3D`1" or + "ComputeSharp.ReadWriteTexture3D`2" or + "ComputeSharp.IReadWriteTexture2D`1" or + "ComputeSharp.IReadWriteTexture3D`1" => true, + _ => false, + }; + } + /// /// Checks whether or not a given type name matches a typed resource type. /// diff --git a/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs new file mode 100644 index 00000000..f479b642 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL shader, excluding dynamic information. +/// +/// The shader generated header and threadsX count declaration. +/// The threadsY count declaration. +/// The threadsZ count declaration. +/// The define statements, if any. +/// The static fields and declared types, if any. +/// The captured fields, and method forward declarations. +/// The captured method implementations. +/// The shader entry point. +/// The signatures for captured methods. +internal sealed record NonDynamicHlslSourceInfo( + string HeaderAndThreadsX, + string ThreadsY, + string ThreadsZ, + string Defines, + string StaticFieldsAndDeclaredTypes, + string CapturedFieldsAndResourcesAndForwardDeclarations, + string CapturedMethods, + string EntryPoint, + ImmutableArray MethodSignatures) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + public bool Equals(NonDynamicHlslSourceInfo? x, NonDynamicHlslSourceInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.HeaderAndThreadsX == y.HeaderAndThreadsX && + x.ThreadsY == y.ThreadsY && + x.ThreadsZ == y.ThreadsZ && + x.Defines == y.Defines && + x.StaticFieldsAndDeclaredTypes == y.StaticFieldsAndDeclaredTypes && + x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations && + x.CapturedMethods == y.CapturedMethods && + x.EntryPoint == y.EntryPoint && + x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()); + } + + /// + public int GetHashCode(NonDynamicHlslSourceInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.HeaderAndThreadsX); + hashCode.Add(obj.ThreadsY); + hashCode.Add(obj.ThreadsZ); + hashCode.Add(obj.Defines); + hashCode.Add(obj.StaticFieldsAndDeclaredTypes); + hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations); + hashCode.Add(obj.CapturedMethods); + hashCode.Add(obj.EntryPoint); + + foreach (string signature in obj.MethodSignatures) + { + hashCode.Add(signature); + } + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs new file mode 100644 index 00000000..7e1f3d36 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs @@ -0,0 +1,191 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.SyntaxRewriters; + +/// +/// A custom type that does postprocessing fixups on the shader main method. +/// +internal abstract class ExecuteMethodRewriter2 : CSharpSyntaxRewriter +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to process the input tree. + public ExecuteMethodRewriter2(ShaderSourceRewriter2 shaderSourceRewriter) + { + ShaderSourceRewriter2 = shaderSourceRewriter; + } + + /// + /// Gets the instance used to process the input tree. + /// + protected ShaderSourceRewriter2 ShaderSourceRewriter2 { get; } + + /// + public TNode? Visit(TNode? node) + where TNode : SyntaxNode + { + return (TNode?)base.Visit(node); + } + + /// + public override SyntaxNode? VisitParameterList(ParameterListSyntax node) + { + var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!; + + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID"))); + + if (ShaderSourceRewriter2.IsGroupIdsUsed) + { + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID"))); + } + + if (ShaderSourceRewriter2.IsGroupIdsIndexUsed) + { + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex"))); + } + + if (ShaderSourceRewriter2.IsGridIdsUsed) + { + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GridIds)} : SV_GroupID"))); + } + + return updatedNode; + } + + /// + /// A custom type specialized for compute shaders. + /// + public sealed class Compute : ExecuteMethodRewriter2 + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to process the input tree. + public Compute(ShaderSourceRewriter2 shaderSourceRewriter) + : base(shaderSourceRewriter) + { + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); + + // When we're rewriting the main compute shader method, we need to insert a range + // check to ensure that invocation outside of the requested range are discarded. + // The following snippet creates this prologue before the user provided body: + // + // if (ThreadIds.x < __x && + // ThreadIds.y < __y && + // ThreadIds.z < __z) + // { + // + // } + BinaryExpressionSyntax rangeCheckExpression = + BinaryExpression(SyntaxKind.LogicalAndExpression, + BinaryExpression(SyntaxKind.LogicalAndExpression, + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("x")), + IdentifierName("__x")), + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("y")), + IdentifierName("__y"))), + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("z")), + IdentifierName("__z"))); + + return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); + } + } + + /// + /// A custom type specialized for compute shaders. + /// + public sealed class Pixel : ExecuteMethodRewriter2 + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to process the input tree. + public Pixel(ShaderSourceRewriter2 shaderSourceRewriter) + : base(shaderSourceRewriter) + { + } + + /// + public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node) + { + var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!; + + // __outputTexture[ThreadIds.xy] = ; + return + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("__outputTexture")) + .AddArgumentListArguments( + Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("ThreadIds"), + IdentifierName("xy")))), + updatedNode.Expression!)); + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); + + // Change the return type to void + updatedNode = updatedNode.WithReturnType(PredefinedType(Token(SyntaxKind.VoidKeyword))); + + // Same as above, but skipping the third check for the Z axis. + // This is because pixel shaders only ever run on 2D textures. + BinaryExpressionSyntax rangeCheckExpression = + BinaryExpression(SyntaxKind.LogicalAndExpression, + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("x")), + IdentifierName("__x")), + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("y")), + IdentifierName("__y"))); + + return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); + } + + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + // Since pixel shaders are only ever executed on 2D textures, the special __z field can + // be removed and replaced with just numeric literal expressions, where the value is 1. + if (updatedNode.Identifier.Text == "__z") + { + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)); + } + + return updatedNode; + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs new file mode 100644 index 00000000..c2aecf1d --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs @@ -0,0 +1,205 @@ +using ComputeSharp.SourceGenerators.Diagnostics; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.SourceGenerators.SyntaxRewriters; + +/// +internal abstract partial class HlslSourceRewriter2 : CSharpSyntaxRewriter +{ + /// + public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) + { + var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; + + Diagnostics.Add(AnonymousObjectCreationExpression, node); + + return updatedNode; + } + + /// + public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) + { + Diagnostics.Add(AwaitExpression, node); + + return base.VisitAwaitExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) + { + Diagnostics.Add(CheckedExpression, node); + + return base.VisitCheckedExpression(node); + } + + /// + public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) + { + Diagnostics.Add(CheckedStatement, node); + + return base.VisitCheckedStatement(node); + } + + /// + public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) + { + Diagnostics.Add(FixedStatement, node); + + return base.VisitFixedStatement(node); + } + + /// + public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) + { + Diagnostics.Add(ForEachStatement, node); + + return base.VisitForEachStatement(node); + } + + /// + public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) + { + Diagnostics.Add(ForEachStatement, node); + + return base.VisitForEachVariableStatement(node); + } + + /// + public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) + { + Diagnostics.Add(LockStatement, node); + + return base.VisitLockStatement(node); + } + + /// + public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) + { + Diagnostics.Add(QueryExpression, node); + + return base.VisitQueryExpression(node); + } + + /// + public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) + { + Diagnostics.Add(RangeExpression, node); + + return base.VisitRangeExpression(node); + } + + /// + public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) + { + Diagnostics.Add(RecursivePattern, node); + + return base.VisitRecursivePattern(node); + } + + /// + public override SyntaxNode? VisitRefType(RefTypeSyntax node) + { + Diagnostics.Add(RefType, node); + + return base.VisitRefType(node); + } + + /// + public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) + { + Diagnostics.Add(RelationalPattern, node); + + return base.VisitRelationalPattern(node); + } + + /// + public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) + { + Diagnostics.Add(SizeOfExpression, node); + + return base.VisitSizeOfExpression(node); + } + + /// + public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) + { + Diagnostics.Add(StackAllocArrayCreationExpression, node); + + return base.VisitStackAllocArrayCreationExpression(node); + } + + /// + public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) + { + Diagnostics.Add(ThrowExpressionOrStatement, node); + + return base.VisitThrowExpression(node); + } + + /// + public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) + { + Diagnostics.Add(ThrowExpressionOrStatement, node); + + return base.VisitThrowStatement(node); + } + + /// + public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) + { + Diagnostics.Add(TryStatement, node); + + return base.VisitTryStatement(node); + } + + /// + public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) + { + Diagnostics.Add(TupleType, node); + + return base.VisitTupleType(node); + } + + /// + public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) + { + Diagnostics.Add(UsingStatementOrDeclaration, node); + + return base.VisitUsingStatement(node); + } + + /// + public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) + { + Diagnostics.Add(YieldStatement, node); + + return base.VisitYieldStatement(node); + } + + /// + public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) + { + Diagnostics.Add(FunctionPointer, node); + + return base.VisitFunctionPointerType(node); + } + + /// + public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) + { + Diagnostics.Add(PointerType, node); + + return base.VisitPointerType(node); + } + + /// + public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) + { + Diagnostics.Add(UnsafeStatement, node); + + return base.VisitUnsafeStatement(node); + } +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs new file mode 100644 index 00000000..16abb6d8 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.SyntaxRewriters; + +/// +/// A base type that processes C# source to convert to HLSL compliant code. +/// This class contains only the shared logic for all derived HLSL source rewriters. +/// +internal abstract partial class HlslSourceRewriter2 : CSharpSyntaxRewriter +{ + /// + /// The instance with semantic info on the target syntax tree. + /// + protected readonly SemanticModelProvider SemanticModel; + + /// + /// The collection of discovered custom types. + /// + protected readonly ICollection DiscoveredTypes; + + /// + /// The collection of discovered constant definitions. + /// + protected readonly IDictionary ConstantDefinitions; + + /// + /// The collection of produced instances. + /// + protected readonly ImmutableArray.Builder Diagnostics; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + protected HlslSourceRewriter2( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + { + SemanticModel = semanticModel; + DiscoveredTypes = discoveredTypes; + ConstantDefinitions = constantDefinitions; + Diagnostics = diagnostics; + } + + /// + /// Gets whether or not the shader uses a texture sampler at least once. + /// + public bool IsSamplerUsed { get; private set; } + + /// + public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) + { + var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; + + return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectDeclaration, node, type); + } + + // If var is used, replace it with the explicit type + if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) + { + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + return updatedNode; + } + + /// + public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectCreationExpression, node, type); + } + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); + + // New objects use the default HLSL cast syntax, eg. (float4)0 + if (updatedNode.ArgumentList!.Arguments.Count == 0) + { + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Add explicit casts for matrix constructors to help the overload resolution + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && + HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) + { + for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) + { + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; + INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + + updatedNode = updatedNode.ReplaceNode( + updatedNode.ArgumentList!.Arguments[i].Expression, + CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + } + } + + return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!); + } + + /// + public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) + { + var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Diagnostics.Add(InvalidObjectCreationExpression, node, type); + } + + TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); + + // Mutate the syntax like with explicit object creation expressions + if (updatedNode.ArgumentList!.Arguments.Count == 0) + { + return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Add explicit casts like with the explicit object creation expressions above + if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && + HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) + { + for (int i = 0; i < node.ArgumentList.Arguments.Count; i++) + { + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; + INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + + updatedNode = updatedNode.ReplaceNode( + updatedNode.ArgumentList.Arguments[i].Expression, + CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + } + } + + return InvocationExpression(explicitType, updatedNode.ArgumentList); + } + + /// + public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) + { + var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + + // A default expression becomes (T)0 in HLSL + return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + /// + public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) + { + var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!; + + if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) + { + TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); + + // Same HLSL-style expression in the form (T)0 + return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && + SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && + operation.Type is INamedTypeSymbol type) + { + // If the expression is a literal floating point value, we need to ensure the proper suffixes are + // used in the HLSL representation. Floating point values accept either f or F, but they don't work + // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default + // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. + if (type.GetFullMetadataName().Equals(typeof(float).FullName)) + { + string literal = updatedNode.Token.ValueText; + + // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix + if (literal.IndexOfAny(new[] { '.', 'E' }) == -1) + { + literal += ".0"; + } + + return updatedNode.WithToken(Literal(literal, 0f)); + } + else if (type.GetFullMetadataName().Equals(typeof(double).FullName)) + { + return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d)); + } + } + else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) + { + Diagnostics.Add(StringLiteralExpression, node); + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) + { + var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) + { + string propertyName = operation.Property.GetFullMetadataName(); + + // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. + // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. + if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) + { + var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); + + return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); + } + + // Rewrite texture resource sampled accesses, if needed + if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) + { + IsSamplerUsed = true; + + // Get the syntax for the argument syntax transformation as described above + ArgumentSyntax coordinateSyntax = mapping switch + { + not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), + null => updatedNode.ArgumentList.Arguments[0] + }; + + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). + return + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName("SampleLevel"))) + .AddArgumentListArguments( + Argument(IdentifierName("__sampler")), + coordinateSyntax, + Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); + } + + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite + // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. + if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName)) + { + bool isValid = true; + + // Validate the arguments + foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) + { + if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || + !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) + { + Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); + + isValid = false; + } + } + + if (isValid) + { + // Rewrite the indexer as a property access + string hlslPropertyName = string.Join("", + from argument in node.ArgumentList.Arguments + let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! + let fieldName = fieldReference.Field.Name + let row = (char)(fieldName[1] - 1) + let column = (char)(fieldName[2] - 1) + select $"_m{row}{column}"); + + return MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName(hlslPropertyName)); + } + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && + operation.Field.IsConst && + operation.Type!.TypeKind != TypeKind.Enum) + { + ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; + + return IdentifierName(constantName); + } + + return updatedNode; + } + + /// + public override SyntaxToken VisitToken(SyntaxToken token) + { + SyntaxToken updatedToken = base.VisitToken(token); + + // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords + if (updatedToken.IsKind(SyntaxKind.IdentifierToken) && + HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped)) + { + return ParseToken(mapped!); + } + + return updatedToken.WithoutTrivia(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs new file mode 100644 index 00000000..1f1ef0d7 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs @@ -0,0 +1,443 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using System.Linq; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.SyntaxRewriters; + +/// +/// A custom type that processes C# methods to convert to HLSL compliant code. +/// +internal sealed class ShaderSourceRewriter2 : HlslSourceRewriter2 +{ + /// + /// The type symbol for the shader type. + /// + private readonly INamedTypeSymbol? shaderType; + + /// + /// The collection of discovered static methods. + /// + private readonly IDictionary staticMethods; + + /// + /// The collection of processed local functions in the current tree. + /// + private readonly Dictionary localFunctions; + + /// + /// The list of implicit variables to declare at the start of the body. + /// + private readonly List implicitVariables; + + /// + /// Whether or not the current instance is processing a shader entry point. + /// + private readonly bool isEntryPoint; + + /// + /// The current tree being visited. + /// + private MethodDeclarationSyntax? currentMethod; + + /// + /// The current depth inside local declarations. + /// + private int localFunctionDepth; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The type symbol for the shader type. + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + /// Whether or not the current instance is processing a shader entry point. + public ShaderSourceRewriter2( + INamedTypeSymbol shaderType, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics, + bool isEntryPoint) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.shaderType = shaderType; + this.staticMethods = staticMethods; + this.localFunctions = new(); + this.implicitVariables = new(); + this.isEntryPoint = isEntryPoint; + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public ShaderSourceRewriter2( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + this.staticMethods = staticMethods; + this.implicitVariables = new(); + this.localFunctions = new(); + } + + /// + /// Gets the collection of processed local functions in the current tree. + /// + public IReadOnlyDictionary LocalFunctions => this.localFunctions; + + /// + /// Gets whether or not the shader uses at least once (except ). + /// + public bool IsGroupIdsUsed { get; private set; } + + /// + /// Gets whether or not the shader uses at least once. + /// + public bool IsGroupIdsIndexUsed { get; private set; } + + /// + /// Gets whether or not the shader uses at least once. + /// + public bool IsGridIdsUsed { get; set; } + + /// + public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) + { + this.currentMethod = node; + + var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) + { + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); + } + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + if (updatedNode is not null) + { + var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); + + // Add the tracked implicit declarations (at the start of the body) + updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); + } + + return updatedNode; + } + + /// + public override SyntaxNode VisitParameter(ParameterSyntax node) + { + var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; + + // Convert the C# parameter modifiers to the HLSL equivalent + SyntaxToken modifier = + node.Modifiers + .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) + .Select(static m => m.Kind() switch + { + SyntaxKind.OutKeyword => m, + SyntaxKind.InKeyword => m, + SyntaxKind.RefKeyword => ParseToken("inout"), + _ => Token(SyntaxKind.None) + }).FirstOrDefault(); + + return updatedNode + .WithAttributeLists(default) + .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) + .WithModifiers(TokenList(modifier)); + } + + /// + public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) + { + var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); + + if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) + { + Diagnostics.Add(UsingStatementOrDeclaration, node); + } + + return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); + } + + /// + public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) + { + var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + + // Add the variable to the list of implicit declarations + this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); + + return IdentifierName(updatedNode.Designation.ToString()); + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + return + ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) + .WithBlockBody() + .WithoutAccessibilityModifiers() + .WithAttributeLists(List()); + } + + /// + public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) + { + this.localFunctionDepth++; + + var updatedNode = + ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) + .WithBlockBody() + .WithAttributeLists(List()) + .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); + + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); + + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) + { + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); + } + + if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + this.localFunctionDepth--; + + // HLSL doesn't support local functions, so we first process them as usual and then remove + // them from the current syntax tree completely. These will be added to the shader source + // as external static method with a special name to avoid conflicts with other methods. + // The name will simply be in the format: "____". + this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); + + return null; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + { + // If the member access is a constant, track it and replace the tree with the processed constant name + if (operation is IFieldReferenceOperation fieldOperation && + fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + // If the current member access is a field or property access, check the lookup table + // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. + if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + { + // Mark which dispatch properties have been used, to optimize the declaration afterwards + if (operation.Member.IsStatic) + { + string typeName = operation.Member.ContainingType.GetFullMetadataName(); + + if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true; + else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true; + else if (typeName == typeof(GridIds).FullName) IsGridIdsUsed = true; + + // Check that the dispatch info types are only used from the main shader body + if (!this.isEntryPoint || this.localFunctionDepth > 0) + { + DiagnosticDescriptor? descriptor = typeName switch + { + _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, + _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, + _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, + _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, + _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, + _ => null + }; + + if (descriptor is not null) + { + Diagnostics.Add(descriptor, node); + } + } + } + + // Static and instance members are handled differently, with static members being + // converted into a literal expression, and instance getting an updated identifier. + // For instance, consider these three cases: + // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) + // - ThreadIds.X (custom) => ThreadIds.x + // - uint3.X (instance) => [arg].x + return operation.Member.IsStatic switch + { + true => ParseExpression(mapping!), + false => updatedNode.WithName(IdentifierName(mapping!)) + }; + } + + // If the current member access is an access to any of the size properties in the available + // resource types (either buffer or texture types), then rewrite the subtree to transform the + // property access into an invocation of an autogenerated static helper method to get the target + // dimension for the buffer in use. The helper method is added to the list of static helpers. + if (operation is IPropertyReferenceOperation propertyOperation && + HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + { + IMethodSymbol key = propertyOperation.Property.GetMethod!; + + if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + methodSyntax = + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceName))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + + this.staticMethods.Add(key, methodSyntax); + } + + return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && + operation.TargetMethod is IMethodSymbol method && + method.IsStatic) + { + // If the invocation consists of invoking a static method that has a direct + // mapping to HLSL, rewrite the expression in the current invocation node. + // For instance: Math.Abs(expr) => abs(expr). + if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) + { + return updatedNode.WithExpression(ParseExpression(mapping!)); + } + + // Update the name if the target is a local function. The exact schema for the + // updated name is detailed in the override handling the local function statement. + if (method.MethodKind == MethodKind.LocalFunction) + { + var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}"; + + return updatedNode.WithExpression(ParseExpression(functionIdentifier)); + } + + // If the method is an external static method, import and rewrite it as well. + // This assumes that the target method is actually part of the same compilation. + // We need to check the declaring type to avoid rewriting static methods in the shader + // type as well, as they will be processed by the generator in a different path. + if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) + { + var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); + + if (!this.staticMethods.ContainsKey(method)) + { + ShaderSourceRewriter2 ShaderSourceRewriter2 = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); + MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(); + MethodDeclarationSyntax processedMethod = ShaderSourceRewriter2.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); + + this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); + } + + return updatedNode.WithExpression(ParseExpression(methodIdentifier)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + // Strip the ref keywords from arguments + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + // Track and rewrite the discarded declaration + if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) + { + TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes); + string identifier = $"__implicit{this.implicitVariables.Count}"; + + // Add the variable to the list of implicit declarations + this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); + + return updatedNode.WithExpression(IdentifierName(identifier)); + } + + return updatedNode; + } +} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs new file mode 100644 index 00000000..ea6bb249 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Globalization; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.SyntaxRewriters; + +/// +/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). +/// +internal sealed class StaticFieldRewriter2 : HlslSourceRewriter2 +{ + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance for the target syntax tree. + /// The set of discovered custom types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + public StaticFieldRewriter2( + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) + { + } + + /// + public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) + { + if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) + { + return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; + } + + return null; + } + + /// + public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; + + if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && + SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) + { + // Track and replace constants + if (operation is IFieldReferenceOperation fieldOperation && + fieldOperation.Field.IsConst && + fieldOperation.Type!.TypeKind != TypeKind.Enum) + { + ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); + } + + if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) + { + if (operation.Member.IsStatic) + { + string typeName = operation.Member.ContainingType.GetFullMetadataName(); + + // Special dispatch types are not supported from static constants + DiagnosticDescriptor? descriptor = typeName switch + { + _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, + _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, + _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, + _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, + _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, + _ => null + }; + + if (descriptor is not null) + { + Diagnostics.Add(descriptor, node); + } + } + + // Rewrite static and instance mapped members + return operation.Member.IsStatic switch + { + true => ParseExpression(mapping!), + false => updatedNode.WithName(IdentifierName(mapping!)) + }; + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) + { + var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; + + if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && + operation.TargetMethod is IMethodSymbol method && + method.IsStatic) + { + // Rewrite HLSL intrinsic methods + if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) + { + return updatedNode.WithExpression(ParseExpression(mapping!)); + } + } + + return updatedNode; + } + + /// + public override SyntaxNode? VisitArgument(ArgumentSyntax node) + { + var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; + + updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); + + return updatedNode; + } +} From 8c0637e363f33b843f6e2bd95bf6877238857ca6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 11:15:45 +0100 Subject: [PATCH 06/36] Enable diagnostics generation for LoadDispatchData() --- .../Diagnostics/DiagnosticsExtensions.cs | 16 +++++++ ...ncremental.CreateLoadDispatchDataMethod.cs | 47 ++++++++++--------- .../IShaderGenerator.Incremental.cs | 36 ++++++++++---- .../Models/DispatchDataInfo.cs | 19 ++++++++ .../Models/Result{T}.cs | 12 +++++ 5 files changed, 101 insertions(+), 29 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/Result{T}.cs diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs index 5ff64485..8584bee1 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs @@ -72,4 +72,20 @@ internal static class DiagnosticsExtensions { diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args)); } + + /// + /// Registers an output node into an to output diagnostics. + /// + /// The input instance. + /// The input sequence of diagnostics. + public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider> diagnostics) + { + context.RegisterSourceOutput(diagnostics, static (context, diagnostics) => + { + foreach (Diagnostic diagnostic in diagnostics) + { + context.ReportDiagnostic(diagnostic); + } + }); + } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs index e1c56267..ca058e47 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Runtime.CompilerServices; using ComputeSharp.__Internals; using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.Models; @@ -24,16 +25,18 @@ public sealed partial class IShaderGenerator2 /// /// Explores a given type hierarchy and generates statements to load fields. /// - /// The current type being explored. + /// The current shader type being explored. /// The type of shader interface urrently being processed. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting diagnostics from the processing operation. /// The sequence of instances for all captured resources and values. private static ImmutableArray GetCapturedFieldInfos( - ITypeSymbol currentTypeSymbol, + ITypeSymbol structDeclarationSymbol, Type shaderInterfaceType, out int resourceCount, - out int root32BitConstantCount) + out int root32BitConstantCount, + out ImmutableArray diagnostics) { // Helper method that uses boxes instead of ref-s (illegal in enumerators) static IEnumerable GetCapturedFieldInfos( @@ -88,6 +91,8 @@ public sealed partial class IShaderGenerator2 } } + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + // Setup the resource and byte offsets for tracking. Pixel shaders have only two // implicitly captured int values, as they're always dispatched over a 2D texture. bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); @@ -97,7 +102,7 @@ public sealed partial class IShaderGenerator2 // Traverse all shader fields and gather info, and update the tracking offsets ImmutableArray fieldInfos = GetCapturedFieldInfos( - currentTypeSymbol, + structDeclarationSymbol, ImmutableArray.Empty, resourceOffsetAsBox, rawDataOffsetAsBox).ToImmutableArray(); @@ -110,6 +115,23 @@ public sealed partial class IShaderGenerator2 // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); + // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. + // Loaded values in the root signature have the following costs: + // - Root constants cost 1 DWORD each, since they are 32-bit values. + // - Descriptor tables cost 1 DWORD each. + // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. + // So here we check whether the current signature respects that constraint, + // and emit a build error otherwise. For more info on this, see the docs here: + // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. + int rootSignatureDwordSize = root32BitConstantCount + resourceCount; + + if (rootSignatureDwordSize > 64) + { + builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); + } + + diagnostics = builder.ToImmutable(); + return fieldInfos; } @@ -319,23 +341,6 @@ public sealed partial class IShaderGenerator2 } } - // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. - // Loaded values in the root signature have the following costs: - // - Root constants cost 1 DWORD each, since they are 32-bit values. - // - Descriptor tables cost 1 DWORD each. - // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. - // So here we check whether the current signature respects that constraint, - // and emit a build error otherwise. For more info on this, see the docs here: - // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. - int rootSignatureDwordSize = root32BitConstantsCount + resourceCount; - - if (rootSignatureDwordSize > 64) - { - // TODO - //context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - context.ReportDiagnostic(Diagnostic.Create(ShaderDispatchDataSizeExceeded, null)); - } - // global::System.Span span0 = stackalloc uint[]; statements.Insert(0, LocalDeclarationStatement( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 74bcf298..303a9307 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -71,17 +72,36 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator }); // Get the hierarchy info and captured field infos for each shader type - IncrementalValuesProvider<(HierarchyInfo Hierarchy, Type Type, ImmutableArray FieldInfos, int ResourceCount, int Root32BitConstantCount)> hierarchyInfoAndCaptureFieldInfos = + IncrementalValuesProvider> dispatchDataInfoWithErrors = shaderDeclarations - .Select(static (item, token) => ( - item.Hierarchy, - item.Type, - FieldInfos: GetCapturedFieldInfos(item.Symbol, item.Type, out int resourceCount, out int root32BitConstantCount), - ResourceCount: resourceCount, - Root32BitConstantCount: root32BitConstantCount)); + .Select(static (item, token) => + { + ImmutableArray fieldInfos = GetCapturedFieldInfos( + item.Symbol, + item.Type, + out int resourceCount, + out int root32BitConstantCount, + out ImmutableArray diagnostics); + + return new Result(new DispatchDataInfo( + item.Hierarchy, + item.Type, + fieldInfos, + resourceCount, + root32BitConstantCount), + diagnostics); + }); + + // Output the diagnostics from the previous step + context.ReportDiagnostics(dispatchDataInfoWithErrors.Select(static (item, token) => item.Errors)); + + // Get a filtered sequence to enable caching + IncrementalValuesProvider dispatchDataInfo = + dispatchDataInfoWithErrors + .Select(static (item, token) => item.Value); // Generate the LoadDispatchData() methods - context.RegisterSourceOutput(hierarchyInfoAndCaptureFieldInfos.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod( context, diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs new file mode 100644 index 00000000..39fc905d --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch data. +/// +/// The hierarchy data for the shader. +/// The shader interface type. +/// The description on shader instance fields. +/// The total number of captured resources. +/// The size of the shader root signature, in 32 bit constants. +internal sealed record DispatchDataInfo( + HierarchyInfo Hierarchy, + Type Type, + ImmutableArray FieldInfos, + int ResourceCount, + int Root32BitConstantCount); diff --git a/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs b/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs new file mode 100644 index 00000000..4bee6af9 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing a value and an associated set of diagnostic errors. +/// +/// The type of the wrapped value. +/// The wrapped value for the current result. +/// The associated diagnostic errors, if any. +internal sealed record Result(TValue Value, ImmutableArray Errors); From 1186dee50fbe99797f2f747cd2c66c9641aebe1e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 11:25:34 +0100 Subject: [PATCH 07/36] Enable diagnostics generation for BuildHlslString() --- ...Incremental.GetNonDynamicHlslSourceInfo.cs | 25 +++++++++++-------- .../IShaderGenerator.Incremental.cs | 20 +++++++++++++++ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs index 183ad183..bae405af 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs @@ -29,17 +29,18 @@ public sealed partial class IShaderGenerator2 /// The input object currently in use. /// The node to process. /// The for . + /// The resulting diagnostics from the processing operation. /// The resulting instance for the BuildHlslString method. - /// - private static ((NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed), ImmutableArray Diagnostics) GetNonDynamicHlslSourceInfo( + private static (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) GetNonDynamicHlslSourceInfo( Compilation compilation, StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol) + INamedTypeSymbol structDeclarationSymbol, + out ImmutableArray diagnostics) { - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); // Properties are not supported - DetectAndReportPropertyDeclarations(diagnostics, structDeclarationSymbol); + DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -49,7 +50,7 @@ public sealed partial class IShaderGenerator2 // A given type can only represent a single shader type if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) { - diagnostics.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); } // Explore the syntax tree and extract the processed info @@ -57,13 +58,13 @@ public sealed partial class IShaderGenerator2 var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var instanceFields = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader); - var sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes); - var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var instanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); var declaredTypes = GetDeclaredTypes(discoveredTypes); var definedConstants = GetDefinedConstants(constantDefinitions); - var staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); // Get the HLSL source data with the intermediate info NonDynamicHlslSourceInfo sourceInfo = GetNonDynamicHlslSourceInfo( @@ -78,7 +79,9 @@ public sealed partial class IShaderGenerator2 isSamplerUsed, entryPoint); - return ((sourceInfo, implicitTextureType, isSamplerUsed), diagnostics.ToImmutable()); + diagnostics = builder.ToImmutable(); + + return (sourceInfo, implicitTextureType, isSamplerUsed); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 303a9307..718576be 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -113,6 +113,26 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchData", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); + + // Get the HLSL source info + IncrementalValuesProvider> hlslSourceInfo = + shaderDeclarations + .Combine(context.CompilationProvider) + .Select(static (item, token) => + { + (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) hlslInfo = GetNonDynamicHlslSourceInfo( + item.Right, + item.Left.Syntax, + item.Left.Symbol, + out ImmutableArray diagnostics); + + return new Result<(NonDynamicHlslSourceInfo, string?, bool)>(hlslInfo, diagnostics); + }); + + // Output the diagnostics + context.ReportDiagnostics(hlslSourceInfo.Select(static (item, token) => item.Errors)); + + } /// From ea9f568ee45d2a86bcf2b97ca56680a347755d4d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 13:01:41 +0100 Subject: [PATCH 08/36] Add HashCode.AddRange(...) extension --- .../Extensions/HashCodeExtensions.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs diff --git a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs new file mode 100644 index 00000000..1fd0d1cc --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class HashCodeExtensions +{ + /// + /// Adds all items from a given instance to an hashcode. + /// + /// The type of items to hash. + /// The target instance. + /// The input items to hash. + public static void AddRange(this ref HashCode hashCode, ImmutableArray items) + { + foreach (T item in items) + { + hashCode.Add(item); + } + } +} From ad45fc1fc94a7b81807ee8fd256d2d6cf963ddf1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 13:02:05 +0100 Subject: [PATCH 09/36] Add IncrementalValuesProvider.WithComparers(...) extension --- .../IncrementalValuesProviderExtensions.cs | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs new file mode 100644 index 00000000..571ef354 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IncrementalValuesProviderExtensions +{ + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of left items in each tuple. + /// The type of right items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers( + this IncrementalValuesProvider<(TLeft Left, TRight Right)> source, + IEqualityComparer comparerLeft, + IEqualityComparer comparerRight) + { + return source.WithComparer(new Comparer(comparerLeft, comparerRight)); + } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(TLeft Left, TRight Right)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparerLeft; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparerRight; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparerLeft, IEqualityComparer comparerRight) + { + this.comparerLeft = comparerLeft; + this.comparerRight = comparerRight; + } + + /// + public bool Equals((TLeft Left, TRight Right) x, (TLeft Left, TRight Right) y) + { + return + this.comparerLeft.Equals(x.Left, y.Left) && + this.comparerRight.Equals(x.Right, y.Right); + } + + /// + public int GetHashCode((TLeft Left, TRight Right) obj) + { + return HashCode.Combine( + this.comparerLeft.GetHashCode(obj.Left), + this.comparerRight.GetHashCode(obj.Right)); + } + } +} From 5210c1ecd9c9e37c74008afb8867f10e8fd5f9d7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 13:03:25 +0100 Subject: [PATCH 10/36] Switch BuildHlslString() to incremental --- ...Incremental.CreateBuildHlslStringMethod.cs | 254 ++++++++++++++++++ ...ncremental.CreateLoadDispatchDataMethod.cs | 6 +- ...Incremental.GetNonDynamicHlslSourceInfo.cs | 31 ++- .../IShaderGenerator.Incremental.cs | 23 +- .../IShaderGenerator.cs | 2 +- .../Models/HierarchyInfo.cs | 53 ++-- ...micHlslSourceInfo.cs => HlslSourceInfo.cs} | 50 +++- 7 files changed, 367 insertions(+), 52 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs rename src/ComputeSharp.SourceGenerators/Models/{NonDynamicHlslSourceInfo.cs => HlslSourceInfo.cs} (59%) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs new file mode 100644 index 00000000..73116592 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs @@ -0,0 +1,254 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618, RS1024 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The resulting instance for the BuildHlslString method. + private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo) + { + ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); + + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements)); + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The input instance to use. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + StringBuilder textBuilder = new(); + int capturedDelegates = 0; + int prologueStatements = 0; + int sizeHint = 64; + + void AppendLF() + { + textBuilder.Append('\n'); + } + + void AppendLine(string text) + { + textBuilder.Append(text); + } + + void AppendParsedStatement(string text) + { + FlushText(); + + statements.Add(ParseStatement(text)); + } + + void FlushText() + { + if (textBuilder.Length > 0) + { + string text = textBuilder.ToString(); + + textBuilder.Append(text); + + sizeHint += textBuilder.Length; + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); + + textBuilder.Clear(); + } + } + + // Declare the hashsets to track imported members and types from delegates, if needed + if (!hlslSourceInfo.Delegates.IsEmpty) + { + void DeclareMapping(int index, string name, IEnumerable items) + { + // global::System.Collections.Generic.HashSet = new(); + statements.Insert(index, + LocalDeclarationStatement(VariableDeclaration( + GenericName(Identifier("global::System.Collections.Generic.HashSet")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .AddVariables( + VariableDeclarator(Identifier(name)) + .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + + prologueStatements++; + + // .Add(""); + foreach (var item in items) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(name), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + + prologueStatements++; + } + } + + DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); + DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); + DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); + + // Go through all existing delegate fields, if any + foreach (string fieldName in hlslSourceInfo.Delegates) + { + // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } + } + + // Header and thread ids + AppendLine(hlslSourceInfo.HeaderAndThreadsX); + AppendParsedStatement("builder.Append(threadsX);"); + AppendLine(hlslSourceInfo.ThreadsY); + AppendParsedStatement("builder.Append(threadsY);"); + AppendLine(hlslSourceInfo.ThreadsZ); + AppendParsedStatement("builder.Append(threadsZ);"); + + // Define declarations + AppendLine(hlslSourceInfo.Defines); + + // Defines from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + } + + // Static fields and declared types + AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); + + // Declared types from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); + } + + // Captured variables + AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); + + // Forward declarations from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) + { + FlushText(); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__methodNames"), + IdentifierName("Remove"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); + } + } + + // Captured methods + AppendLine(hlslSourceInfo.CapturedMethods); + + // Captured methods from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); + } + + // Captured delegate methods + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); + AppendLF(); + } + + // Entry point + AppendLine(hlslSourceInfo.EntryPoint); + + FlushText(); + + // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); + statements.Insert( + prologueStatements, + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("builder"), + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), + IdentifierName("Create"))) + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(sizeHint))))))); + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs index ca058e47..5624caa2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs @@ -194,14 +194,12 @@ public sealed partial class IShaderGenerator2 /// /// Creates a instance for the LoadDispatchDataMethod method. /// - /// The input instance to use. /// The type of shader interface urrently being processed. /// The array of values for all captured fields. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The resulting instance for the LoadDispatchDataMethod method. private static MethodDeclarationSyntax CreateLoadDispatchDataMethod( - SourceProductionContext context, Type shaderInterfaceType, ImmutableArray fieldInfos, int resourceCount, @@ -228,20 +226,18 @@ public sealed partial class IShaderGenerator2 Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(GetDispatchDataLoadingStatements(context, shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); + .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); } /// /// Gets a sequence of statements to load the dispatch data for a given shader. /// - /// The current generator context in use. /// The type of shader interface urrently being processed. /// The array of values for all captured fields. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances to load shader dispatch data. private static ImmutableArray GetDispatchDataLoadingStatements( - SourceProductionContext context, Type shaderInterfaceType, ImmutableArray fieldInfos, int resourceCount, diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs index bae405af..09ad0ef4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs @@ -24,14 +24,14 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator2 { /// - /// Creates a instance for the BuildHlslString method. + /// Gathers all necessary information on a transpiled HLSL source for a given shader type. /// /// The input object currently in use. /// The node to process. /// The for . /// The resulting diagnostics from the processing operation. - /// The resulting instance for the BuildHlslString method. - private static (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) GetNonDynamicHlslSourceInfo( + /// The resulting info on the processed shader. + private static HlslSourceInfo GetNonDynamicHlslSourceInfo( Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -58,7 +58,8 @@ public sealed partial class IShaderGenerator2 var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var instanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var nonDelegateInstanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol); var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); @@ -66,11 +67,14 @@ public sealed partial class IShaderGenerator2 var definedConstants = GetDefinedConstants(constantDefinitions); var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + diagnostics = builder.ToImmutable(); + // Get the HLSL source data with the intermediate info - NonDynamicHlslSourceInfo sourceInfo = GetNonDynamicHlslSourceInfo( + return GetNonDynamicHlslSourceInfo( definedConstants, declaredTypes, - instanceFields, + nonDelegateInstanceFields, + delegateInstanceFields, staticFields, sharedBuffers, processedMethods, @@ -78,10 +82,6 @@ public sealed partial class IShaderGenerator2 implicitTextureType, isSamplerUsed, entryPoint); - - diagnostics = builder.ToImmutable(); - - return (sourceInfo, implicitTextureType, isSamplerUsed); } /// @@ -485,6 +485,7 @@ public sealed partial class IShaderGenerator2 /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. /// The sequence of instance fields for the current shader. + /// The sequence of delegate fields for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of shared buffers declared by the shader. /// The sequence of processed methods used by the shader. @@ -493,10 +494,11 @@ public sealed partial class IShaderGenerator2 /// Whether the static sampler is used by the shader. /// The body of the entry point of the shader. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static NonDynamicHlslSourceInfo GetNonDynamicHlslSourceInfo( + private static HlslSourceInfo GetNonDynamicHlslSourceInfo( ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> instanceFields, + ImmutableArray delegateInstanceFields, ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, ImmutableArray<(string Signature, string Definition)> processedMethods, @@ -703,6 +705,11 @@ public sealed partial class IShaderGenerator2 capturedFieldsAndResourcesAndForwardDeclarations, capturedMethods, entryPoint, - processedMethods.Select(static m => m.Signature).ToImmutableArray()); + implicitTextureType, + isSamplerUsed, + declaredTypes.Select(static t => t.Name).ToImmutableArray(), + definedConstants.Select(static c => c.Name).ToImmutableArray(), + processedMethods.Select(static m => m.Signature).ToImmutableArray(), + delegateInstanceFields); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 718576be..92484930 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -5,6 +5,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -104,7 +105,6 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod( - context, item.Left.Type, item.Left.FieldInfos, item.Left.ResourceCount, @@ -115,24 +115,37 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator }); // Get the HLSL source info - IncrementalValuesProvider> hlslSourceInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Result)> hlslSourceInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => { - (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) hlslInfo = GetNonDynamicHlslSourceInfo( + HlslSourceInfo hlslInfo = GetNonDynamicHlslSourceInfo( item.Right, item.Left.Syntax, item.Left.Symbol, out ImmutableArray diagnostics); - return new Result<(NonDynamicHlslSourceInfo, string?, bool)>(hlslInfo, diagnostics); + return (item.Left.Hierarchy, new Result(hlslInfo, diagnostics)); }); // Output the diagnostics - context.ReportDiagnostics(hlslSourceInfo.Select(static (item, token) => item.Errors)); + context.ReportDiagnostics(hlslSourceInfoWithErrors.Select(static (item, token) => item.Result.Errors)); + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> dynamicSourceInfo = + hlslSourceInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Result.Value)) + .WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); + // Generate the BuildHlslString() methods + context.RegisterSourceOutput(dynamicSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(item.Left.SourceInfo); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 59bd0aae..5cee1604 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -68,7 +68,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator // getDispatchIdMethod, // loadDispatchDataMethod, loadDispatchMetadataMethod, - buildHlslStringMethod, + //buildHlslStringMethod, tryGetBytecodeMethod }; diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs index 6d098bed..dda30c69 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using ComputeSharp.SourceGenerators.Extensions; @@ -38,22 +39,44 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu names.ToImmutable()); } - /// - [Pure] - public bool Equals(HierarchyInfo? other) + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer { - return - other is not null && - (ReferenceEquals(this, other) || - (Namespace == other.Namespace && - (Names == other.Names || - Names.AsSpan().SequenceEqual(other.Names.AsSpan())))); - } + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); - /// - [Pure] - public override int GetHashCode() - { - return HashCode.Combine(Namespace, Names, Names[0]); + /// + public bool Equals(HierarchyInfo? x, HierarchyInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.FilenameHint == y.FilenameHint && + x.Namespace == y.Namespace && + x.Names.AsSpan().SequenceEqual(y.Names.AsSpan()); + } + + /// + public int GetHashCode(HierarchyInfo obj) + { + return HashCode.Combine(obj.Namespace, obj.Names, obj.Names[0]); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs similarity index 59% rename from src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs rename to src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs index f479b642..3af250f0 100644 --- a/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs @@ -1,11 +1,12 @@ -using System; +using ComputeSharp.SourceGenerators.Extensions; +using System; using System.Collections.Generic; using System.Collections.Immutable; namespace ComputeSharp.SourceGenerators.Models; /// -/// A model for extracted info on a processed HLSL shader, excluding dynamic information. +/// A model for extracted info on a processed HLSL shader. /// /// The shader generated header and threadsX count declaration. /// The threadsY count declaration. @@ -15,8 +16,13 @@ namespace ComputeSharp.SourceGenerators.Models; /// The captured fields, and method forward declarations. /// The captured method implementations. /// The shader entry point. +/// The type of the implicit texture type, if any. +/// Whether or not the static sampler is used. +/// The names of declared types. +/// The names of defined constants. /// The signatures for captured methods. -internal sealed record NonDynamicHlslSourceInfo( +/// The list of delegate fields. +internal sealed record HlslSourceInfo( string HeaderAndThreadsX, string ThreadsY, string ThreadsZ, @@ -25,15 +31,25 @@ internal sealed record NonDynamicHlslSourceInfo( string CapturedFieldsAndResourcesAndForwardDeclarations, string CapturedMethods, string EntryPoint, - ImmutableArray MethodSignatures) + string? ImplicitTextureType, + bool IsSamplerUsed, + ImmutableArray DefinedTypes, + ImmutableArray DefinedConstants, + ImmutableArray MethodSignatures, + ImmutableArray Delegates) { /// - /// An implementation for . + /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : IEqualityComparer { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + /// - public bool Equals(NonDynamicHlslSourceInfo? x, NonDynamicHlslSourceInfo? y) + public bool Equals(HlslSourceInfo? x, HlslSourceInfo? y) { if (x is null && y is null) { @@ -59,11 +75,16 @@ internal sealed record NonDynamicHlslSourceInfo( x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations && x.CapturedMethods == y.CapturedMethods && x.EntryPoint == y.EntryPoint && - x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()); + x.ImplicitTextureType == y.ImplicitTextureType && + x.IsSamplerUsed == y.IsSamplerUsed && + x.DefinedTypes.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) && + x.DefinedConstants.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) && + x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()) && + x.Delegates.AsSpan().SequenceEqual(y.Delegates.AsSpan()); } /// - public int GetHashCode(NonDynamicHlslSourceInfo obj) + public int GetHashCode(HlslSourceInfo obj) { HashCode hashCode = default; @@ -75,11 +96,12 @@ internal sealed record NonDynamicHlslSourceInfo( hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations); hashCode.Add(obj.CapturedMethods); hashCode.Add(obj.EntryPoint); - - foreach (string signature in obj.MethodSignatures) - { - hashCode.Add(signature); - } + hashCode.Add(obj.ImplicitTextureType); + hashCode.Add(obj.IsSamplerUsed); + hashCode.AddRange(obj.DefinedTypes); + hashCode.AddRange(obj.DefinedConstants); + hashCode.AddRange(obj.MethodSignatures); + hashCode.AddRange(obj.Delegates); return hashCode.ToHashCode(); } From ed75dd4b5a2593693ad59974f44a729f8334edee Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 13:28:14 +0100 Subject: [PATCH 11/36] Implement comparers for all model types --- .../Extensions/HashCodeExtensions.cs | 16 +++ .../Extensions/ImmutableArrayExtensions.cs | 50 ++++++++++ .../Models/DispatchDataInfo.cs | 58 ++++++++++- .../Models/FieldInfo.cs | 97 ++++++++++++++++++- .../Models/HierarchyInfo.cs | 2 +- .../Models/HlslSourceInfo.cs | 8 +- 6 files changed, 223 insertions(+), 8 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs diff --git a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs index 1fd0d1cc..31c57b6c 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; namespace ComputeSharp.SourceGenerators.Extensions; @@ -21,4 +22,19 @@ internal static class HashCodeExtensions hashCode.Add(item); } } + + /// + /// Adds all items from a given instance to an hashcode. + /// + /// The type of items to hash. + /// The target instance. + /// A comparer to get hashcodes for items. + /// The input items to hash. + public static void AddRange(this ref HashCode hashCode, ImmutableArray items, IEqualityComparer comparer) + { + foreach (T item in items) + { + hashCode.Add(comparer.GetHashCode(item)); + } + } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs new file mode 100644 index 00000000..e4100441 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class ImmutableArrayExtensions +{ + /// + /// Compares two sequences for equality. + /// + /// The items to compare. + /// The left sequence of items. + /// The right sequence of items. + /// Whether or not equals . + public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right) + where T : IEquatable + { + return left.AsSpan().SequenceEqual(right.AsSpan()); + } + + /// + /// Compares two sequences for equality. + /// + /// The items to compare. + /// The left sequence of items. + /// The right sequence of items. + /// The instance used to compare items. + /// Whether or not equals . + public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right, IEqualityComparer comparer) + { + if (left.Length != right.Length) + { + return false; + } + + for (int i = 0; i < left.Length; i++) + { + if (!comparer.Equals(left[i], right[i])) + { + return false; + } + } + + return true; + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs index 39fc905d..fdf4a04a 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -1,4 +1,6 @@ -using System; +using ComputeSharp.SourceGenerators.Extensions; +using System; +using System.Collections.Generic; using System.Collections.Immutable; namespace ComputeSharp.SourceGenerators.Models; @@ -16,4 +18,56 @@ internal sealed record DispatchDataInfo( Type Type, ImmutableArray FieldInfos, int ResourceCount, - int Root32BitConstantCount); + int Root32BitConstantCount) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(DispatchDataInfo? x, DispatchDataInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + HierarchyInfo.Comparer.Default.Equals(x.Hierarchy, y.Hierarchy) && + x.Type == y.Type && + x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) && + x.ResourceCount == y.ResourceCount && + x.Root32BitConstantCount == y.Root32BitConstantCount; + } + + /// + public int GetHashCode(DispatchDataInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy)); + hashCode.Add(obj.Type); + hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default); + hashCode.Add(obj.ResourceCount); + hashCode.Add(obj.Root32BitConstantCount); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs index 17e3c83e..f177ca4b 100644 --- a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs @@ -1,4 +1,7 @@ -using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; +using System; +using System.Collections.Generic; +using System.Collections.Immutable; namespace ComputeSharp.SourceGenerators.Models; @@ -39,4 +42,96 @@ internal abstract record FieldInfo int Rows, int Columns, ImmutableArray Offsets) : FieldInfo; + + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(FieldInfo? x, FieldInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + if (x is Resource resourceX && y is Resource resourceY) + { + return + resourceX.FieldName == resourceY.FieldName && + resourceX.TypeName == resourceY.TypeName && + resourceX.Offset == resourceY.Offset; + } + else if (x is Primitive primitiveX && y is Primitive primitiveY) + { + return + primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) && + primitiveX.TypeName == primitiveY.TypeName && + primitiveX.Offset == primitiveY.Offset; + } + else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY) + { + return + matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) && + matrixX.TypeName == matrixY.TypeName && + matrixX.ElementName == matrixY.ElementName && + matrixX.Rows == matrixY.Rows && + matrixY.Columns == matrixY.Columns && + matrixX.Offsets.SequenceEqual(matrixY.Offsets); + } + + return false; + } + + /// + public int GetHashCode(FieldInfo obj) + { + switch (obj) + { + case Resource resource: + return HashCode.Combine(resource.FieldName, resource.TypeName, resource.Offset); + case Primitive primitive: + { + HashCode hashCode = default; + + hashCode.AddRange(primitive.FieldPath); + hashCode.Add(primitive.TypeName); + hashCode.Add(primitive.Offset); + + return hashCode.ToHashCode(); + } + case NonLinearMatrix matrix: + { + HashCode hashCode = default; + + hashCode.AddRange(matrix.FieldPath); + hashCode.Add(matrix.TypeName); + hashCode.Add(matrix.ElementName); + hashCode.Add(matrix.Rows); + hashCode.Add(matrix.Columns); + hashCode.AddRange(matrix.Offsets); + + return hashCode.ToHashCode(); + } + default: + return 0; + } + } + } } diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs index dda30c69..0842eb94 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -70,7 +70,7 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu return x.FilenameHint == y.FilenameHint && x.Namespace == y.Namespace && - x.Names.AsSpan().SequenceEqual(y.Names.AsSpan()); + x.Names.SequenceEqual(y.Names); } /// diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs index 3af250f0..702e1eb3 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs @@ -77,10 +77,10 @@ internal sealed record HlslSourceInfo( x.EntryPoint == y.EntryPoint && x.ImplicitTextureType == y.ImplicitTextureType && x.IsSamplerUsed == y.IsSamplerUsed && - x.DefinedTypes.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) && - x.DefinedConstants.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) && - x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()) && - x.Delegates.AsSpan().SequenceEqual(y.Delegates.AsSpan()); + x.DefinedTypes.SequenceEqual(y.DefinedTypes) && + x.DefinedConstants.SequenceEqual(y.DefinedTypes) && + x.MethodSignatures.SequenceEqual(y.MethodSignatures) && + x.Delegates.SequenceEqual(y.Delegates); } /// From be614c5af5e2204609918f21b0c59e66ade2df98 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 13:33:29 +0100 Subject: [PATCH 12/36] Enable caching for DispatchId info --- .../IShaderGenerator.Incremental.cs | 12 ++-- .../Models/DispatchIdInfo.cs | 55 +++++++++++++++++++ 2 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 92484930..9afca133 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -59,14 +59,15 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol), item.Type!)); // Get the hierarchy info and delegate field names for each shader type - IncrementalValuesProvider<(HierarchyInfo Hierarchy, ImmutableArray Delegates)> hierarchyInfoAndDelegateFieldNames = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo Info)> hierarchyAndDispatchIdInfo = shaderDeclarations - .Select(static (item, token) => (item.Hierarchy, GetDelegateFieldNames(item.Symbol))); + .Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDelegateFieldNames(item.Symbol)))) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default); // Generate the GetDispatchId() methods - context.RegisterSourceOutput(hierarchyInfoAndDelegateFieldNames.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(hierarchyAndDispatchIdInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Delegates); + MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Info.Delegates); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); @@ -99,7 +100,8 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = dispatchDataInfoWithErrors - .Select(static (item, token) => item.Value); + .Select(static (item, token) => item.Value) + .WithComparer(DispatchDataInfo.Comparer.Default); // Generate the LoadDispatchData() methods context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs new file mode 100644 index 00000000..772a9516 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs @@ -0,0 +1,55 @@ +using ComputeSharp.SourceGenerators.Extensions; +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch id. +/// +/// The list of delegate field names for the shader. +internal sealed record DispatchIdInfo(ImmutableArray Delegates) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(DispatchIdInfo? x, DispatchIdInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return x.Delegates.SequenceEqual(y.Delegates); + } + + /// + public int GetHashCode(DispatchIdInfo obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj.Delegates); + + return hashCode.ToHashCode(); + } + } +} From f2a556e63bf6b8d52a1a142212a4e6fa470dd143 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 14:13:34 +0100 Subject: [PATCH 13/36] Fix HLSL source generation when capturing delegates --- ...Incremental.GetNonDynamicHlslSourceInfo.cs | 56 +++++++++++-------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs index 09ad0ef4..5f153721 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs @@ -58,7 +58,7 @@ public sealed partial class IShaderGenerator2 var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var nonDelegateInstanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol); var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); @@ -73,7 +73,8 @@ public sealed partial class IShaderGenerator2 return GetNonDynamicHlslSourceInfo( definedConstants, declaredTypes, - nonDelegateInstanceFields, + resourceFields, + valueFields, delegateInstanceFields, staticFields, sharedBuffers, @@ -93,13 +94,17 @@ public sealed partial class IShaderGenerator2 /// Indicates whether or not represents a compute shader. /// A sequence of captured fields in . [Pure] - private static ImmutableArray<(string MetadataName, string Name, string HlslType)> GetInstanceFields( - ImmutableArray.Builder diagnostics, - INamedTypeSymbol structDeclarationSymbol, - ICollection types, - bool isComputeShader) + private static ( + ImmutableArray<(string MetadataName, string Name, string HlslType)>, + ImmutableArray<(string Name, string HlslType)>) + GetInstanceFields( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types, + bool isComputeShader) { - ImmutableArray<(string, string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string)>(); + ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>(); + ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); bool hlslResourceFound = false; foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) @@ -126,6 +131,9 @@ public sealed partial class IShaderGenerator2 } string metadataName = typeSymbol.GetFullMetadataName(); + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); // Allowed fields must be either resources, unmanaged values or delegates if (HlslKnownTypes.IsTypedResourceType(metadataName)) @@ -137,6 +145,9 @@ public sealed partial class IShaderGenerator2 { types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); } + + // Add the current mapping for the name (if the name used a reserved keyword) + resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); } else if (!typeSymbol.IsUnmanagedType && typeSymbol.TypeKind != TypeKind.Delegate) @@ -146,19 +157,16 @@ public sealed partial class IShaderGenerator2 continue; } - else if (typeSymbol.IsUnmanagedType && - !HlslKnownTypes.IsKnownHlslType(metadataName)) + else if (typeSymbol.IsUnmanagedType) { // Track the type if it's a custom struct - types.Add(typeSymbol); - } + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + types.Add(typeSymbol); + } - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Yield back the current mapping for the name (if the name used a reserved keyword) - builder.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); + values.Add((mapping ?? fieldSymbol.Name, typeName)); + } } // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource @@ -167,7 +175,7 @@ public sealed partial class IShaderGenerator2 diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); } - return builder.ToImmutable(); + return (resources.ToImmutable(), values.ToImmutable()); } /// @@ -484,7 +492,8 @@ public sealed partial class IShaderGenerator2 /// /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. - /// The sequence of instance fields for the current shader. + /// The sequence of resource instance fields for the current shader. + /// The sequence of value instance fields for the current shader. /// The sequence of delegate fields for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of shared buffers declared by the shader. @@ -497,7 +506,8 @@ public sealed partial class IShaderGenerator2 private static HlslSourceInfo GetNonDynamicHlslSourceInfo( ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, - ImmutableArray<(string MetadataName, string Name, string HlslType)> instanceFields, + ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, + ImmutableArray<(string Name, string HlslType)> valueFields, ImmutableArray delegateInstanceFields, ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, @@ -614,7 +624,7 @@ public sealed partial class IShaderGenerator2 } // User-defined values - foreach (var (_, fieldName, fieldType) in instanceFields.Where(static t => !HlslKnownTypes.IsTypedResourceType(t.MetadataName))) + foreach (var (fieldName, fieldType) in valueFields) { AppendLineAndLF($" {fieldType} {fieldName};"); } @@ -640,7 +650,7 @@ public sealed partial class IShaderGenerator2 } // Resources - foreach (var (metadataName, fieldName, fieldType) in instanceFields) + foreach (var (metadataName, fieldName, fieldType) in resourceFields) { if (HlslKnownTypes.IsConstantBufferType(metadataName)) { From c6172032bd92978d077da701932ebfbf5bab0d39 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 16:48:43 +0100 Subject: [PATCH 14/36] Switch LoadDispatchMetadata() to incremental --- ...mental.CreateLoadDispatchMetadataMethod.cs | 182 ++++++++++++++++++ .../IShaderGenerator.Incremental.cs | 24 +++ .../IShaderGenerator.cs | 2 +- .../Models/DispatchMetadataInfo.cs | 65 +++++++ .../Models/ResourceDescriptor.cs | 54 ++++++ 5 files changed, 326 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs new file mode 100644 index 00000000..06531460 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Gets the data related to the shader metadata for a given shader type. + /// + /// The total number of needed 32 bit constants in the shader root signature. + /// Indicates whether the current shader uses an implicit texture. + /// Whether the static sampler is used by the shader. + /// The sequence of captured fields for the shader. + /// The metadata info for the shader. + private static DispatchMetadataInfo GetDispatchMetadataInfo( + int root32BitConstantCount, + bool isImplicitTextureUsed, + bool isSamplerUsed, + ImmutableArray capturedFields) + { + ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); + int constantBufferOffset = 1; + int readOnlyResourceOffset = 0; + int readWriteResourceOffset = 0; + int resourceOffset = 0; + + // Add the implicit texture descriptor, if needed + if (isImplicitTextureUsed) + { + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + } + + // Populate the sequence of resource descriptors + foreach (FieldInfo.Resource resource in capturedFields.OfType()) + { + if (HlslKnownTypes.IsConstantBufferType(resource.TypeName)) + { + descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++)); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName)) + { + descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++)); + } + else + { + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + } + } + + return new( + root32BitConstantCount, + isSamplerUsed, + descriptors.ToImmutable()); + } + + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The dispatch metadata for the current shader.. + /// The resulting instance for the LoadDispatchMetadata method. + private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchMetadata")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TMetadataLoader")), + Parameter(Identifier("result")) + .AddModifiers(Token(SyntaxKind.OutKeyword)) + .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) + .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); + } + + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The dispatch metadata for the current shader.. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // global::System.Span span0 = stackalloc byte[5]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); + + // Compute the total number of resources + int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; + + // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); + + // ref byte r0 = ref span0[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // Serialized shader metadata + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});")); + + + // Populate the sequence of resource descriptors + foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) + { + statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); + } + + // Invoke the value delegate to create the opaque root signature handle + statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 9afca133..178bb83d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -148,6 +148,30 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); + + // Get the dispatch metadata info + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo = + dispatchDataInfo + .Collect() + .Combine(dynamicSourceInfo.Collect()) + .SelectMany(static (item, token) => item.Left.Zip(item.Right, static (left, right) => (DataInfo: left, right.SourceInfo))) + .Select(static (item, token) => ( + item.DataInfo.Hierarchy, + GetDispatchMetadataInfo( + item.DataInfo.Root32BitConstantCount, + item.SourceInfo.ImplicitTextureType is not null, + item.SourceInfo.IsSamplerUsed, + item.DataInfo.FieldInfos))) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default); + + // Generate the LoadDispatchMetadata() methods + context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax buildHlslStringMethod = CreateLoadDispatchMetadataMethod(item.Left.MetadataInfo); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 5cee1604..a8f28918 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -67,7 +67,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator { // getDispatchIdMethod, // loadDispatchDataMethod, - loadDispatchMetadataMethod, + //loadDispatchMetadataMethod, //buildHlslStringMethod, tryGetBytecodeMethod }; diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs new file mode 100644 index 00000000..cbf3bc4f --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model containing info on shader dispatch metadata. +/// +/// The size of the shader root signature, in 32 bit constants. +/// Whether or not the static sampler is used. +/// The sequence of resource descriptors for the shader. +internal sealed record DispatchMetadataInfo( + int Root32BitConstantCount, + bool IsSamplerUsed, + ImmutableArray ResourceDescriptors) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(DispatchMetadataInfo? x, DispatchMetadataInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.Root32BitConstantCount == y.Root32BitConstantCount && + x.IsSamplerUsed == y.IsSamplerUsed && + x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors, ResourceDescriptor.Comparer.Default); + } + + /// + public int GetHashCode(DispatchMetadataInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.Root32BitConstantCount); + hashCode.Add(obj.IsSamplerUsed); + hashCode.AddRange(obj.ResourceDescriptors, ResourceDescriptor.Comparer.Default); + + return hashCode.ToHashCode(); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs new file mode 100644 index 00000000..bb5070c4 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A resource descriptor for a captured resource in a shader. +/// +/// The type id for the resource. +/// The offset of the resource in its containing register. +/// The offset of the resource descriptor in the shader root signature. +internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(ResourceDescriptor? x, ResourceDescriptor? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.TypeId == y.TypeId && + x.RegisterOffset == y.RegisterOffset && + x.Offset == y.Offset; + } + + /// + public int GetHashCode(ResourceDescriptor obj) + { + return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset); + } + } +} From dcb70f740d743f6a8748f3a0587e8a89f7078ade Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 20:22:06 +0100 Subject: [PATCH 15/36] Remove Collect() calls, restructure incremental pipeline --- .../IncrementalValuesProviderExtensions.cs | 72 +++++++++++++++ .../IShaderGenerator.Incremental.cs | 90 +++++++++---------- 2 files changed, 117 insertions(+), 45 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs index 571ef354..bdcd5290 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs @@ -26,6 +26,26 @@ internal static class IncrementalValuesProviderExtensions return source.WithComparer(new Comparer(comparerLeft, comparerRight)); } + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of first items in each tuple. + /// The type of second items in each tuple. + /// The type of third items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers( + this IncrementalValuesProvider<(T1, T2, T3)> source, + IEqualityComparer comparer1, + IEqualityComparer comparer2, + IEqualityComparer comparer3) + { + return source.WithComparer(new Comparer(comparer1, comparer2, comparer3)); + } + /// /// An implementation for a value tuple. /// @@ -68,4 +88,56 @@ internal static class IncrementalValuesProviderExtensions this.comparerRight.GetHashCode(obj.Right)); } } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(T1, T2, T3)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer1; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer2; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer3; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3) + { + this.comparer1 = comparer1; + this.comparer2 = comparer2; + this.comparer3 = comparer3; + } + + /// + public bool Equals((T1, T2, T3) x, (T1, T2, T3) y) + { + return + this.comparer1.Equals(x.Item1, y.Item1) && + this.comparer2.Equals(x.Item2, y.Item2) && + this.comparer3.Equals(x.Item3, y.Item3); + } + + /// + public int GetHashCode((T1, T2, T3) obj) + { + return HashCode.Combine( + this.comparer1.GetHashCode(obj.Item1), + this.comparer2.GetHashCode(obj.Item2), + this.comparer3.GetHashCode(obj.Item3)); + } + } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 178bb83d..51697582 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -73,34 +73,55 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); - // Get the hierarchy info and captured field infos for each shader type - IncrementalValuesProvider> dispatchDataInfoWithErrors = + // Get the dispatch data and HLSL source info. This info is computed on the same step + // as parts are shared in following sub-branches in the incremental generator pipeline. + IncrementalValuesProvider<(Result Dispatch, Result Hlsl)> shaderInfoWithErrors = shaderDeclarations + .Combine(context.CompilationProvider) .Select(static (item, token) => { + // GetDispatchId() data ImmutableArray fieldInfos = GetCapturedFieldInfos( - item.Symbol, - item.Type, + item.Left.Symbol, + item.Left.Type, out int resourceCount, out int root32BitConstantCount, - out ImmutableArray diagnostics); + out ImmutableArray dispatchDataDiagnostics); - return new Result(new DispatchDataInfo( - item.Hierarchy, - item.Type, + Result dispatchDataInfo = new(new DispatchDataInfo( + item.Left.Hierarchy, + item.Left.Type, fieldInfos, resourceCount, root32BitConstantCount), - diagnostics); + dispatchDataDiagnostics); + + // BuildHlslString() info + HlslSourceInfo hlslSourceInfo = GetNonDynamicHlslSourceInfo( + item.Right, + item.Left.Syntax, + item.Left.Symbol, + out ImmutableArray hlslSourceDiagnostics); + + return ( + dispatchDataInfo, + new Result(hlslSourceInfo, hlslSourceDiagnostics)); }); - // Output the diagnostics from the previous step - context.ReportDiagnostics(dispatchDataInfoWithErrors.Select(static (item, token) => item.Errors)); + // Output the diagnostics + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Hlsl.Errors)); + + // Filter all items to enable caching at a coarse level, and remove diagnostics + IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslSourceInfo Hlsl)> shaderInfo = + shaderInfoWithErrors + .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value)) + .WithComparers(DispatchDataInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = - dispatchDataInfoWithErrors - .Select(static (item, token) => item.Value) + shaderInfo + .Select(static (item, token) => item.Dispatch) .WithComparer(DispatchDataInfo.Comparer.Default); // Generate the LoadDispatchData() methods @@ -114,34 +135,16 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchData", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); - }); - - // Get the HLSL source info - IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Result)> hlslSourceInfoWithErrors = - shaderDeclarations - .Combine(context.CompilationProvider) - .Select(static (item, token) => - { - HlslSourceInfo hlslInfo = GetNonDynamicHlslSourceInfo( - item.Right, - item.Left.Syntax, - item.Left.Symbol, - out ImmutableArray diagnostics); - - return (item.Left.Hierarchy, new Result(hlslInfo, diagnostics)); - }); - - // Output the diagnostics - context.ReportDiagnostics(hlslSourceInfoWithErrors.Select(static (item, token) => item.Result.Errors)); + }); // Get the filtered sequence to enable caching - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> dynamicSourceInfo = - hlslSourceInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.Result.Value)) + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> hlslSourceInfo = + shaderInfo + .Select(static (item, token) => (item.Dispatch.Hierarchy, item.Hlsl)) .WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); // Generate the BuildHlslString() methods - context.RegisterSourceOutput(dynamicSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(item.Left.SourceInfo); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); @@ -151,17 +154,14 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator // Get the dispatch metadata info IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo = - dispatchDataInfo - .Collect() - .Combine(dynamicSourceInfo.Collect()) - .SelectMany(static (item, token) => item.Left.Zip(item.Right, static (left, right) => (DataInfo: left, right.SourceInfo))) + shaderInfo .Select(static (item, token) => ( - item.DataInfo.Hierarchy, + item.Dispatch.Hierarchy, GetDispatchMetadataInfo( - item.DataInfo.Root32BitConstantCount, - item.SourceInfo.ImplicitTextureType is not null, - item.SourceInfo.IsSamplerUsed, - item.DataInfo.FieldInfos))) + item.Dispatch.Root32BitConstantCount, + item.Hlsl.ImplicitTextureType is not null, + item.Hlsl.IsSamplerUsed, + item.Dispatch.FieldInfos))) .WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default); // Generate the LoadDispatchMetadata() methods From e49e16bd1c77f5c11afdb9c45cd88185e7258a13 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 21:25:10 +0100 Subject: [PATCH 16/36] Minor code style tweaks --- .../Extensions/HashCodeExtensions.cs | 2 +- .../Helpers/HashCode.cs | 192 ++++++++++++++---- 2 files changed, 155 insertions(+), 39 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs index 31c57b6c..7d486566 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs @@ -34,7 +34,7 @@ internal static class HashCodeExtensions { foreach (T item in items) { - hashCode.Add(comparer.GetHashCode(item)); + hashCode.Add(item, comparer); } } } diff --git a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs index 19030b40..94ea71f0 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -30,7 +29,6 @@ internal struct HashCode /// Initializes the default seed. /// /// A random seed. - [Pure] private static unsafe uint GenerateGlobalSeed() { byte[] bytes = new byte[4]; @@ -40,9 +38,15 @@ internal struct HashCode return BitConverter.ToUInt32(bytes, 0); } - public static int Combine(T1 value1) + /// + /// Combines a value into a hash code. + /// + /// The type of the value to combine into the hash code. + /// The value to combine into the hash code. + /// The hash code that represents the value. + public static int Combine(T1 value) { - uint hc1 = (uint)(value1?.GetHashCode() ?? 0); + uint hc1 = (uint)(value?.GetHashCode() ?? 0); uint hash = MixEmptyState(); hash += 4; @@ -52,6 +56,14 @@ internal struct HashCode return (int)hash; } + /// + /// Combines two values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -66,6 +78,16 @@ internal struct HashCode return (int)hash; } + /// + /// Combines three values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2, T3 value3) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -82,6 +104,18 @@ internal struct HashCode return (int)hash; } + /// + /// Combines four values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -104,6 +138,20 @@ internal struct HashCode return (int)hash; } + /// + /// Combines five values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -128,6 +176,22 @@ internal struct HashCode return (int)hash; } + /// + /// Combines six values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The type of the sixth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The sixth value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -154,6 +218,24 @@ internal struct HashCode return (int)hash; } + /// + /// Combines seven values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The type of the sixth value to combine into the hash code. + /// The type of the seventh value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The sixth value to combine into the hash code. + /// The seventh value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -182,6 +264,26 @@ internal struct HashCode return (int)hash; } + /// + /// Combines eight values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The type of the sixth value to combine into the hash code. + /// The type of the seventh value to combine into the hash code. + /// The type of the eigth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The sixth value to combine into the hash code. + /// The seventh value to combine into the hash code. + /// The eigth value to combine into the hash code. + /// The hash code that represents the values. public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) { uint hc1 = (uint)(value1?.GetHashCode() ?? 0); @@ -213,6 +315,49 @@ internal struct HashCode return (int)hash; } + /// + /// Adds a single value to the current hash. + /// + /// The type of the value to add into the hash code. + /// The value to add into the hash code. + public void Add(T value) + { + Add(value?.GetHashCode() ?? 0); + } + + /// + /// Adds a single value to the current hash. + /// + /// The type of the value to add into the hash code. + /// The value to add into the hash code. + /// The instance to use. + public void Add(T value, IEqualityComparer? comparer) + { + Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode())); + } + + /// + /// Adds a span of bytes to the hash code. + /// + /// The span. + public void AddBytes(ReadOnlySpan value) + { + ref byte pos = ref MemoryMarshal.GetReference(value); + ref byte end = ref Unsafe.Add(ref pos, value.Length); + + while ((nint)Unsafe.ByteOffset(ref pos, ref end) >= sizeof(int)) + { + Add(Unsafe.ReadUnaligned(ref pos)); + pos = ref Unsafe.Add(ref pos, sizeof(int)); + } + + while (Unsafe.IsAddressLessThan(ref pos, ref end)) + { + Add((int)pos); + pos = ref Unsafe.Add(ref pos, 1); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) { @@ -240,6 +385,7 @@ internal struct HashCode return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint MixEmptyState() { return seed + Prime5; @@ -257,40 +403,6 @@ internal struct HashCode return hash; } - public void Add(T value) - { - Add(value?.GetHashCode() ?? 0); - } - - public void Add(T value, IEqualityComparer? comparer) - { - Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode())); - } - - /// Adds a span of bytes to the hash code. - /// The span. - /// - /// This method does not guarantee that the result of adding a span of bytes will match - /// the result of adding the same bytes individually. - /// - public void AddBytes(ReadOnlySpan value) - { - ref byte pos = ref MemoryMarshal.GetReference(value); - ref byte end = ref Unsafe.Add(ref pos, value.Length); - - while ((nint)Unsafe.ByteOffset(ref pos, ref end) >= sizeof(int)) - { - Add(Unsafe.ReadUnaligned(ref pos)); - pos = ref Unsafe.Add(ref pos, sizeof(int)); - } - - while (Unsafe.IsAddressLessThan(ref pos, ref end)) - { - Add((int)pos); - pos = ref Unsafe.Add(ref pos, 1); - } - } - private void Add(int value) { uint val = (uint)value; @@ -323,6 +435,10 @@ internal struct HashCode } } + /// + /// Gets the resulting hashcode from the current instance. + /// + /// The resulting hashcode from the current instance. public int ToHashCode() { uint length = this.length; From b25f6151f92e4d722eb384527eda9900e0217b09 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 23:08:38 +0100 Subject: [PATCH 17/36] Switch TryGetBytecode() to incremental --- ...Incremental.CreateBuildHlslStringMethod.cs | 18 + ....Incremental.CreateTryGetBytecodeMethod.cs | 394 ++++++++++++++++++ .../IShaderGenerator.Incremental.cs | 92 +++- .../IShaderGenerator.cs | 2 +- .../Models/EmbeddedBytecodeInfo.cs | 65 +++ .../Models/ThreadIdsInfo.cs | 56 +++ 6 files changed, 608 insertions(+), 19 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs index 73116592..db244bee 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs @@ -251,4 +251,22 @@ public sealed partial class IShaderGenerator2 return statements.ToImmutable(); } + + /// + /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). + /// + /// The input instance to use. + /// The non dynamic HLSL source code. + private static string GetNonDynamicHlslSource(HlslSourceInfo hlslSourceInfo) + { + return + hlslSourceInfo.HeaderAndThreadsX + "" + + hlslSourceInfo.ThreadsY + "" + + hlslSourceInfo.ThreadsZ + "" + + hlslSourceInfo.Defines + + hlslSourceInfo.StaticFieldsAndDeclaredTypes + + hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations + + hlslSourceInfo.CapturedMethods + + hlslSourceInfo.EntryPoint; + } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs new file mode 100644 index 00000000..7cc33038 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs @@ -0,0 +1,394 @@ +using System; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics.Contracts; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Shaders.Translation; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Gets the thread ids values for a given shader type, if available. + /// + /// The instance for the attribute. + /// The input instance to process. + /// Indicates whether or not the shader is dynamic (ie. captures delegates). + /// The resulting diagnostics from the processing operation. + /// The thread ids for the precompiled shader, if available. + private static ThreadIdsInfo GetThreadIdsForEmbeddedShader( + INamedTypeSymbol embeddedBytecodeAttribute, + INamedTypeSymbol structDeclarationSymbol, + bool isDynamicShader, + out ImmutableArray diagnostics) + { + AttributeData? attribute = structDeclarationSymbol + .GetAttributes() + .FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, embeddedBytecodeAttribute)); + + if (attribute is null) + { + diagnostics = ImmutableArray.Empty; + + return new(true, 0, 0, 0); + } + + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // Validate the thread number arguments + if (attribute.ConstructorArguments[0].Value is not int threadsX || + attribute.ConstructorArguments[1].Value is not int threadsY || + attribute.ConstructorArguments[2].Value is not int threadsZ || + threadsX is < 1 or > 1024 || + threadsY is < 1 or > 1024 || + threadsZ is < 1 or > 64) + { + builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); + + diagnostics = builder.ToImmutable(); + + return new(true, 0, 0, 0); + } + + // If the current shader is dynamic, emit a diagnostic error + if (isDynamicShader) + { + builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); + + diagnostics = builder.ToImmutable(); + + return new(true, 0, 0, 0); + } + + diagnostics = builder.ToImmutable(); + + return new(false, threadsX, threadsY, threadsZ); + } + + /// + /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// + private static bool areDxcLibrariesLoaded; + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance to process. + /// The generated HLSL source code (ignoring captured delegates, if present). + /// The resulting diagnostics from the processing operation. + /// The instance with the compiled shader bytecode. + [Pure] + private static unsafe ImmutableArray GetShaderBytecode( + ThreadIdsInfo threadIds, + string hlslSource, + out ImmutableArray diagnostics) + { + ImmutableArray bytecode = ImmutableArray.Empty; + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // No embedded shader was requested + if (threadIds.IsDefault) + { + goto End; + } + + try + { + // Try to load dxcompiler.dll and dxil.dll + LoadNativeDxcLibraries(); + + // Replace the actual thread num values + hlslSource = hlslSource + .Replace("", threadIds.X.ToString()) + .Replace("", threadIds.Y.ToString()) + .Replace("", threadIds.Z.ToString()); + + // Compile the shader bytecode + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + bytecode = Unsafe.As>(ref array); + } + catch (Win32Exception) + { + // TODO + //builder.Add( + // EmbeddedBytecodeFailedWithWin32Exception, + // structDeclarationSymbol, + // structDeclarationSymbol, + // e.HResult, + // e.Message); + } + catch (HlslCompilationException) + { + // TODO + //builder.Add( + // EmbeddedBytecodeFailedWithHlslCompilationException, + // structDeclarationSymbol, + // structDeclarationSymbol, + // e.Message); + } + + End: + diagnostics = builder.ToImmutable(); + + return bytecode; + } + + /// + /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. + /// + /// Thrown if the CPU architecture is not supported. + /// Thrown if a library fails to load. + private static void LoadNativeDxcLibraries() + { + // Extracts a specified native library for a given runtime identifier + static string ExtractLibrary(string rid, string name) + { + string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; + string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll"); + + Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); + + using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); + + try + { + using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write); + + sourceStream.CopyTo(destinationStream); + } + catch (IOException) + { + } + + return targetFilename; + } + + // Loads a target native library + static unsafe void LoadLibrary(string filename) + { + [DllImport("kernel32", ExactSpelling = true, SetLastError = true)] + static extern void* LoadLibraryW(ushort* lpLibFileName); + + fixed (char* p = filename) + { + if (LoadLibraryW((ushort*)p) is null) + { + int hresult = Marshal.GetLastWin32Error(); + + throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}."); + } + } + } + + if (!areDxcLibrariesLoaded) + { + string rid = RuntimeInformation.ProcessArchitecture switch + { + Architecture.X64 => "x64", + Architecture.Arm64 => "arm64", + _ => throw new NotSupportedException("Invalid process architecture") + }; + + LoadLibrary(ExtractLibrary(rid, "dxil")); + LoadLibrary(ExtractLibrary(rid, "dxcompiler")); + } + + areDxcLibrariesLoaded = true; + } + + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input instance. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the BuildHlslString method. + private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) + { + BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); + + if (bytecodeLiterals is not null) + { + fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); + } + else + { + fixup = static tree => tree.ToFullString(); + } + + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.BoolKeyword)), + Identifier("TryGetBytecode")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) + .WithBody(block); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance. + /// The resulting bytecode literals to insert into the final source code. + /// The instance trying to retrieve the precompiled shader. + [Pure] + private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) + { + if (bytecodeInfo.Bytecode.IsEmpty) + { + bytecodeLiterals = null; + + // This code produces a method declaration as follows: + // + // bytecode = default; + // + // return false; + return + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement( + LiteralExpression( + SyntaxKind.FalseLiteralExpression))); + } + + bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // This code produces a method declaration as follows: + // + // if (threadsX == && threadsY == && threadsZ == ) + // { + // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // + // return true; + // } + // + // bytecode = default; + // + // return false; + // + // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string + // is created by the generator. This greatly speeds up the code generation, as it avoids + // having to create/parse tens of thousands of literal expression nodes for every shader. + return + Block( + IfStatement( + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsX"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsY"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsZ"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))), + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), + ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); + } + + /// + /// A mapping of precomputed literals for all values. + /// + private static readonly string[] formattedBytes = + { + "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", + "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", + "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", + "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", + "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", + "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", + "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", + "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", + "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", + "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", + "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", + "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", + "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", + "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", + "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", + "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" + }; + + /// + /// Creates a formatted expression to initialize a with a given shader data. + /// + /// The input shader bytecode to serialize. + /// A formatted with the serialized data. + private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) + { + //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values + using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); + + builder.Append(formattedBytes[bytecode[0]]); + + foreach (byte b in bytecode.Slice(1)) + { + builder.Append(", "); + builder.Append(formattedBytes[b]); + } + + return builder.WrittenSpan.ToString(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 51697582..1ee1527f 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -65,32 +65,38 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator .WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default); // Generate the GetDispatchId() methods - context.RegisterSourceOutput(hierarchyAndDispatchIdInfo.Combine(canUseSkipLocalsInit), static (context, item) => + context.RegisterSourceOutput(hierarchyAndDispatchIdInfo, static (context, item) => { - MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Left.Info.Delegates); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, item.Right); + MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Info.Delegates); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, false); - context.AddSource($"{item.Left.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); - // Get the dispatch data and HLSL source info. This info is computed on the same step - // as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(Result Dispatch, Result Hlsl)> shaderInfoWithErrors = + // Get the [EmbeddedBytecode] attribute + IncrementalValueProvider embeddedBytecodeSymbol = + context.CompilationProvider + .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(EmbeddedBytecodeAttribute).FullName)!); + + // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the + // same step as parts are shared in following sub-branches in the incremental generator pipeline. + IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) + .Combine(embeddedBytecodeSymbol) .Select(static (item, token) => { // GetDispatchId() data ImmutableArray fieldInfos = GetCapturedFieldInfos( - item.Left.Symbol, - item.Left.Type, + item.Left.Left.Symbol, + item.Left.Left.Type, out int resourceCount, out int root32BitConstantCount, out ImmutableArray dispatchDataDiagnostics); Result dispatchDataInfo = new(new DispatchDataInfo( - item.Left.Hierarchy, - item.Left.Type, + item.Left.Left.Hierarchy, + item.Left.Left.Type, fieldInfos, resourceCount, root32BitConstantCount), @@ -98,25 +104,34 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator // BuildHlslString() info HlslSourceInfo hlslSourceInfo = GetNonDynamicHlslSourceInfo( - item.Right, - item.Left.Syntax, - item.Left.Symbol, + item.Left.Right, + item.Left.Left.Syntax, + item.Left.Left.Symbol, out ImmutableArray hlslSourceDiagnostics); + // TryGetBytecode() info + ThreadIdsInfo threadIds = GetThreadIdsForEmbeddedShader( + item.Right, + item.Left.Left.Symbol, + !hlslSourceInfo.Delegates.IsEmpty, + out ImmutableArray threadIdsDiagnostics); + return ( dispatchDataInfo, - new Result(hlslSourceInfo, hlslSourceDiagnostics)); + new Result(hlslSourceInfo, hlslSourceDiagnostics), + new Result(threadIds, threadIdsDiagnostics)); }); // Output the diagnostics context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors)); context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Hlsl.Errors)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslSourceInfo Hlsl)> shaderInfo = + IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value)) - .WithComparers(DispatchDataInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); + .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)) + .WithComparers(DispatchDataInfo.Comparer.Default, HlslSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = @@ -172,6 +187,47 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); + + // Transform the raw HLSL source to compile + IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = + shaderInfo + .Select(static (item, token) => (item.Dispatch.Hierarchy, GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, ThreadIdsInfo.Comparer.Default); + + // Compile the requested shader bytecodes + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result BytecodeInfo)> embeddedBytecodeWithErrors = + shaderBytecodeInfo + .Select(static (item, token) => + { + ImmutableArray bytecode = GetShaderBytecode(item.ThreadIds, item.Hlsl, out ImmutableArray diagnostics); + + EmbeddedBytecodeInfo bytecodeInfo = new( + item.ThreadIds.X, + item.ThreadIds.Y, + item.ThreadIds.Z, + bytecode); + + return (item.Hierarchy, new Result(bytecodeInfo, diagnostics)); + }); + + // Output the diagnostics + context.ReportDiagnostics(embeddedBytecodeWithErrors.Select(static (item, token) => item.BytecodeInfo.Errors)); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo.Value)) + .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default); + + // Generate the TryGetBytecode() methods + context.RegisterSourceOutput(embeddedBytecode, static (context, item) => + { + MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(item.BytecodeInfo, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, false); + string text = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FilenameHint}.TryGetBytecode", SourceText.From(text, Encoding.UTF8)); + }); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index a8f28918..52f01b52 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -69,7 +69,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator // loadDispatchDataMethod, //loadDispatchMetadataMethod, //buildHlslStringMethod, - tryGetBytecodeMethod + //tryGetBytecodeMethod }; // Method attributes diff --git a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs new file mode 100644 index 00000000..df208415 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing a compiled shader bytecode, or none. +/// +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +/// The compiled shader bytecode, if available. +internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray Bytecode) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(EmbeddedBytecodeInfo? x, EmbeddedBytecodeInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.X == y.X && + x.Y == y.Y && + x.Z == y.Z && + x.Bytecode.SequenceEqual(y.Bytecode); + } + + /// + public int GetHashCode(EmbeddedBytecodeInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.X); + hashCode.Add(obj.Y); + hashCode.Add(obj.Z); + hashCode.AddBytes(obj.Bytecode.AsSpan()); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs new file mode 100644 index 00000000..dfcd72b8 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing gathered info on a embedded thread ids. +/// +/// Whether the values are diascarded. +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(ThreadIdsInfo? x, ThreadIdsInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.IsDefault == y.IsDefault && + x.X == y.X && + x.Y == y.Y && + x.Z == y.Y; + } + + /// + public int GetHashCode(ThreadIdsInfo obj) + { + return HashCode.Combine(obj.IsDefault, obj.X, obj.Y, obj.Z); + } + } +} From 07c0801911554dee712ac2418aab594ed5cdcabb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 23:52:21 +0100 Subject: [PATCH 18/36] Rename incremental generator files --- ...ntal.CreateBuildHlslStringMethod.Syntax.cs | 254 ++++++ ...Incremental.CreateBuildHlslStringMethod.cs | 845 ++++++++++++++---- ...mental.CreateGetDispatchIdMethod.Syntax.cs | 94 ++ ...r.Incremental.CreateGetDispatchIdMethod.cs | 88 +- ...tal.CreateLoadDispatchDataMethod.Syntax.cs | 245 +++++ ...ncremental.CreateLoadDispatchDataMethod.cs | 236 ----- ...CreateLoadDispatchMetadataMethod.Syntax.cs | 132 +++ ...mental.CreateLoadDispatchMetadataMethod.cs | 126 +-- ...ental.CreateTryGetBytecodeMethod.Syntax.cs | 187 ++++ ....Incremental.CreateTryGetBytecodeMethod.cs | 176 ---- ...Incremental.GetNonDynamicHlslSourceInfo.cs | 725 --------------- 11 files changed, 1572 insertions(+), 1536 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs new file mode 100644 index 00000000..73116592 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs @@ -0,0 +1,254 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618, RS1024 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The resulting instance for the BuildHlslString method. + private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo) + { + ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); + + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements)); + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The input instance to use. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + StringBuilder textBuilder = new(); + int capturedDelegates = 0; + int prologueStatements = 0; + int sizeHint = 64; + + void AppendLF() + { + textBuilder.Append('\n'); + } + + void AppendLine(string text) + { + textBuilder.Append(text); + } + + void AppendParsedStatement(string text) + { + FlushText(); + + statements.Add(ParseStatement(text)); + } + + void FlushText() + { + if (textBuilder.Length > 0) + { + string text = textBuilder.ToString(); + + textBuilder.Append(text); + + sizeHint += textBuilder.Length; + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); + + textBuilder.Clear(); + } + } + + // Declare the hashsets to track imported members and types from delegates, if needed + if (!hlslSourceInfo.Delegates.IsEmpty) + { + void DeclareMapping(int index, string name, IEnumerable items) + { + // global::System.Collections.Generic.HashSet = new(); + statements.Insert(index, + LocalDeclarationStatement(VariableDeclaration( + GenericName(Identifier("global::System.Collections.Generic.HashSet")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .AddVariables( + VariableDeclarator(Identifier(name)) + .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + + prologueStatements++; + + // .Add(""); + foreach (var item in items) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(name), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + + prologueStatements++; + } + } + + DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); + DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); + DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); + + // Go through all existing delegate fields, if any + foreach (string fieldName in hlslSourceInfo.Delegates) + { + // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } + } + + // Header and thread ids + AppendLine(hlslSourceInfo.HeaderAndThreadsX); + AppendParsedStatement("builder.Append(threadsX);"); + AppendLine(hlslSourceInfo.ThreadsY); + AppendParsedStatement("builder.Append(threadsY);"); + AppendLine(hlslSourceInfo.ThreadsZ); + AppendParsedStatement("builder.Append(threadsZ);"); + + // Define declarations + AppendLine(hlslSourceInfo.Defines); + + // Defines from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + } + + // Static fields and declared types + AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); + + // Declared types from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); + } + + // Captured variables + AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); + + // Forward declarations from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) + { + FlushText(); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__methodNames"), + IdentifierName("Remove"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); + } + } + + // Captured methods + AppendLine(hlslSourceInfo.CapturedMethods); + + // Captured methods from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); + } + + // Captured delegate methods + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); + AppendLF(); + } + + // Entry point + AppendLine(hlslSourceInfo.EntryPoint); + + FlushText(); + + // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); + statements.Insert( + prologueStatements, + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("builder"), + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), + IdentifierName("Create"))) + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(sizeHint))))))); + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs index db244bee..e5ecf8c2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs @@ -1,10 +1,19 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; using System.Text; -using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.Models; +using ComputeSharp.SourceGenerators.SyntaxRewriters; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; #pragma warning disable CS0618, RS1024 @@ -15,241 +24,703 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator2 { /// - /// Creates a instance for the BuildHlslString method. + /// Gathers all necessary information on a transpiled HLSL source for a given shader type. /// - /// The input instance to use. - /// The resulting instance for the BuildHlslString method. - private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo) + /// The input object currently in use. + /// The node to process. + /// The for . + /// The resulting diagnostics from the processing operation. + /// The resulting info on the processed shader. + private static HlslSourceInfo GetNonDynamicHlslSourceInfo( + Compilation compilation, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out ImmutableArray diagnostics) { - ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("BuildHlslString")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(bodyStatements)); + // Properties are not supported + DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) + { + builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + } + + // Explore the syntax tree and extract the processed info + var semanticModelProvider = new SemanticModelProvider(compilation); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol); + var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); + var declaredTypes = GetDeclaredTypes(discoveredTypes); + var definedConstants = GetDefinedConstants(constantDefinitions); + var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + + diagnostics = builder.ToImmutable(); + + // Get the HLSL source data with the intermediate info + return GetNonDynamicHlslSourceInfo( + definedConstants, + declaredTypes, + resourceFields, + valueFields, + delegateInstanceFields, + staticFields, + sharedBuffers, + processedMethods, + isComputeShader, + implicitTextureType, + isSamplerUsed, + entryPoint); + } + + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. + /// A sequence of captured fields in . + [Pure] + private static ( + ImmutableArray<(string MetadataName, string Name, string HlslType)>, + ImmutableArray<(string Name, string HlslType)>) + GetInstanceFields( + ImmutableArray.Builder 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)>(); + bool hlslResourceFound = false; + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (fieldSymbol.IsStatic) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + // Group shared fields must be static + if (attribute is not null) + { + diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + hlslResourceFound = true; + + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } + + // Add the current mapping for the name (if the name used a reserved keyword) + resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); + } + else if (!typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) + { + // Shaders can only capture valid HLSL resource types or unmanaged types + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + + continue; + } + else if (typeSymbol.IsUnmanagedType) + { + // Track the type if it's a custom struct + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + types.Add(typeSymbol); + } + + values.Add((mapping ?? fieldSymbol.Name, typeName)); + } + } + + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) + { + diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); + } + + return (resources.ToImmutable(), values.ToImmutable()); + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The collection of produced instances. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + [Pure] + private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + ImmutableArray.Builder diagnostics, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is not null) + { + continue; + } + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter2 staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + diagnostics); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + + builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + } + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is null) + { + continue; + } + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + if (!typeSymbol.ElementType.IsUnmanagedType) + { + diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize)); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The collection of produced instances. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. + /// A sequence of processed methods in , and the entry point. + [Pure] + private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( + ImmutableArray.Builder diagnostics, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + bool isComputeShader) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + string? entryPoint = null; + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + bool isSamplerUsed = false; + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); + + // Create the source rewriter for the current method + ShaderSourceRewriter2 shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + diagnostics, + isShaderEntryPoint); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; + + entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); + } + else + { + methods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + } + + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) + { + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (entryPoint!, methods.ToImmutable(), isSamplerUsed); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + + foreach (var constant in constantDefinitions) + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); + } + + return builder.MoveToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + { + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + builder.Add(( + structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); + } } /// /// Produces the series of statements to build the current HLSL source. /// - /// The input instance to use. + /// The sequence of defined constants for the shader. + /// The sequence of declared types used by the shader. + /// The sequence of resource instance fields for the current shader. + /// The sequence of value instance fields for the current shader. + /// The sequence of delegate fields for the current shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of shared buffers declared by the shader. + /// The sequence of processed methods used by the shader. + /// Whether or not the current shader type is a compute shader. + /// The type of the implicit target texture, if present. + /// Whether the static sampler is used by the shader. + /// The body of the entry point of the shader. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) + private static HlslSourceInfo GetNonDynamicHlslSourceInfo( + ImmutableArray<(string Name, string Value)> definedConstants, + ImmutableArray<(string Name, string Definition)> declaredTypes, + ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, + ImmutableArray<(string Name, string HlslType)> valueFields, + ImmutableArray delegateInstanceFields, + ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, + ImmutableArray<(string Signature, string Definition)> processedMethods, + bool isComputeShader, + string? implicitTextureType, + bool isSamplerUsed, + + string executeMethod) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - StringBuilder textBuilder = new(); - int capturedDelegates = 0; - int prologueStatements = 0; - int sizeHint = 64; + StringBuilder hlslBuilder = new(); void AppendLF() { - textBuilder.Append('\n'); + hlslBuilder.Append('\n'); } void AppendLine(string text) { - textBuilder.Append(text); + hlslBuilder.Append(text); } - void AppendParsedStatement(string text) + void AppendLineAndLF(string text) { - FlushText(); - - statements.Add(ParseStatement(text)); + hlslBuilder.Append(text); + hlslBuilder.Append('\n'); } - void FlushText() + void AppendCharacterAndLF(char c) { - if (textBuilder.Length > 0) - { - string text = textBuilder.ToString(); - - textBuilder.Append(text); - - sizeHint += textBuilder.Length; - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); - - textBuilder.Clear(); - } + hlslBuilder.Append(c); + hlslBuilder.Append('\n'); } - // Declare the hashsets to track imported members and types from delegates, if needed - if (!hlslSourceInfo.Delegates.IsEmpty) + string FlushText() { - void DeclareMapping(int index, string name, IEnumerable items) - { - // global::System.Collections.Generic.HashSet = new(); - statements.Insert(index, - LocalDeclarationStatement(VariableDeclaration( - GenericName(Identifier("global::System.Collections.Generic.HashSet")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) - .AddVariables( - VariableDeclarator(Identifier(name)) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + string text = hlslBuilder.ToString(); - prologueStatements++; + hlslBuilder.Clear(); - // .Add(""); - foreach (var item in items) - { - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(name), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); - - prologueStatements++; - } - } - - DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); - DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); - DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); - - // Go through all existing delegate fields, if any - foreach (string fieldName in hlslSourceInfo.Delegates) - { - // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - prologueStatements++; - } + return text; } - // Header and thread ids - AppendLine(hlslSourceInfo.HeaderAndThreadsX); - AppendParsedStatement("builder.Append(threadsX);"); - AppendLine(hlslSourceInfo.ThreadsY); - AppendParsedStatement("builder.Append(threadsY);"); - AppendLine(hlslSourceInfo.ThreadsZ); - AppendParsedStatement("builder.Append(threadsZ);"); + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + + // Group size constants + AppendLF(); + AppendLine("#define __GroupSize__get_X "); + + string headerAndThreadsX = FlushText(); + + AppendLF(); + AppendLine("#define __GroupSize__get_Y "); + + string threadsY = FlushText(); + + AppendLF(); + AppendLine("#define __GroupSize__get_Z "); + + string threadsZ = FlushText(); + + AppendLF(); // Define declarations - AppendLine(hlslSourceInfo.Defines); - - // Defines from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) + foreach (var (name, value) in definedConstants) { - AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + AppendLineAndLF($"#define {name} {value}"); } - // Static fields and declared types - AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); + string defines = FlushText(); - // Declared types from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) + // Static fields + if (staticFields.Any()) { - AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - } + AppendLF(); - // Captured variables - AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); - - // Forward declarations from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); - } - - // Remove all forward declarations from methods that are embedded into the shader. - // This is necessary to avoid duplicate definitions from methods from delegates. - if (capturedDelegates > 0) - { - // .Add(""); - foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) + foreach (var field in staticFields) { - FlushText(); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("__methodNames"), - IdentifierName("Remove"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } } } + // Declared types + foreach (var (_, typeDefinition) in declaredTypes) + { + AppendLF(); + AppendLineAndLF(typeDefinition); + } + + string staticFieldsAndDeclaredTypes = FlushText(); + + // Captured variables + AppendLF(); + AppendLineAndLF("cbuffer _ : register(b0)"); + AppendCharacterAndLF('{'); + AppendLineAndLF(" uint __x;"); + AppendLineAndLF(" uint __y;"); + + if (isComputeShader) + { + AppendLineAndLF(" uint __z;"); + } + + // User-defined values + foreach (var (fieldName, fieldType) in valueFields) + { + AppendLineAndLF($" {fieldType} {fieldName};"); + } + + AppendCharacterAndLF('}'); + + int constantBuffersCount = 1; + int readOnlyBuffersCount = 0; + int readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + AppendLF(); + AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); + } + + // Optional sampler field + if (isSamplerUsed) + { + AppendLF(); + AppendLineAndLF("SamplerState __sampler : register(s);"); + } + + // Resources + foreach (var (metadataName, fieldName, fieldType) in resourceFields) + { + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); + AppendCharacterAndLF('{'); + AppendLineAndLF($" {fieldType} {fieldName}[2];"); + AppendCharacterAndLF('}'); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + } + else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + + AppendLF(); + AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); + } + + // Forward declarations + foreach (var (forwardDeclaration, _) in processedMethods) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); + // Captured methods - AppendLine(hlslSourceInfo.CapturedMethods); - - // Captured methods from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); - } - - // Captured delegate methods - foreach (string fieldName in hlslSourceInfo.Delegates) + foreach (var (_, method) in processedMethods) { AppendLF(); - AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); - AppendLF(); + AppendLineAndLF(method); } + string capturedMethods = FlushText(); + // Entry point - AppendLine(hlslSourceInfo.EntryPoint); + AppendLF(); + AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); + AppendLineAndLF(executeMethod); - FlushText(); + string entryPoint = FlushText(); - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - statements.Insert( - prologueStatements, - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("builder"), - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), - IdentifierName("Create"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(sizeHint))))))); - - return statements.ToImmutable(); + return new( + headerAndThreadsX, + threadsY, + threadsZ, + defines, + staticFieldsAndDeclaredTypes, + capturedFieldsAndResourcesAndForwardDeclarations, + capturedMethods, + entryPoint, + implicitTextureType, + isSamplerUsed, + declaredTypes.Select(static t => t.Name).ToImmutableArray(), + definedConstants.Select(static c => c.Name).ToImmutableArray(), + processedMethods.Select(static m => m.Signature).ToImmutableArray(), + delegateInstanceFields); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs new file mode 100644 index 00000000..fe0e9a61 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs @@ -0,0 +1,94 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the GetDispatchId method. + /// + ///The names of all instance fields within the current shader type. + /// The resulting instance for the GetDispatchId method. + private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames) + { + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(delegateFieldNames)); + } + + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The names of all instance fields within the current shader type. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) + { + if (delegateFieldNames.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List blockStatements = new(4); + + // global::System.HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("global::System.HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + foreach (string fieldName in delegateFieldNames) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(fieldName), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs index 93f92739..9ea1324f 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs @@ -1,14 +1,7 @@ -using System.Collections.Generic; -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; -using ComputeSharp.__Internals; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -31,83 +24,4 @@ public sealed partial class IShaderGenerator2 .Select(static member => member.Name) .ToImmutableArray(); } - - /// - /// Creates a instance for the GetDispatchId method. - /// - ///The names of all instance fields within the current shader type. - /// The resulting instance for the GetDispatchId method. - private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames) - { - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("GetDispatchId")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(delegateFieldNames)); - } - - /// - /// Gets a instance with the logic to compute the hashcode of a given shader type. - /// - /// The names of all instance fields within the current shader type. - /// The instance to hash the input shader. - [Pure] - private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) - { - if (delegateFieldNames.Length == 0) - { - // return 0; - return - Block(ReturnStatement( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))); - } - - List blockStatements = new(4); - - // global::System.HashCode hashCode = default; - blockStatements.Add(LocalDeclarationStatement( - VariableDeclaration(IdentifierName("global::System.HashCode")) - .AddVariables( - VariableDeclarator(Identifier("hashCode")) - .WithInitializer(EqualsValueClause( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))))); - - foreach (string fieldName in delegateFieldNames) - { - // hashCode.Add(delegateField.Method); - blockStatements.Add(ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(fieldName), - IdentifierName("Method")))))); - } - - // return hashCode.ToHashCode(); - blockStatements.Add(ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("ToHashCode"))))); - - return Block(blockStatements); - } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs new file mode 100644 index 00000000..65e63abb --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting instance for the LoadDispatchDataMethod method. + private static MethodDeclarationSyntax CreateLoadDispatchDataMethod( + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TDataLoader")), + Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), + Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader. + /// + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchDataLoadingStatements( + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + + // Append the statements for the dispatch ranges: + // + // span0[0] = (uint)x; + // span0[1] = (uint)y; + // span0[2] = (uint)z; + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); + + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .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) + { + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); + } + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Resource resource: + + // Validate the resource and get a handle for it. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) = + // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device); + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"), + ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)")))); + break; + case FieldInfo.Primitive primitive: + + // Read a primitive value and serialize it into the target buffer. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.As>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), + ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + + // Declare a local to index into individual rows. This will generate: + // + // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); + for (int j = 0; j < matrix.Rows; j++) + { + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); + } + break; + } + } + + // 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( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedValues"))) + .AddArgumentListArguments(Argument(IdentifierName("span0"))))); + + 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( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedResources"))) + .AddArgumentListArguments(Argument(IdentifierName("span1"))))); + } + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs index 5624caa2..579581de 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs @@ -3,19 +3,13 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; -using ComputeSharp.__Internals; using ComputeSharp.Core.Helpers; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -190,234 +184,4 @@ public sealed partial class IShaderGenerator2 return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); } } - - /// - /// Creates a instance for the LoadDispatchDataMethod method. - /// - /// The type of shader interface urrently being processed. - /// The array of values for all captured fields. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The resulting instance for the LoadDispatchDataMethod method. - private static MethodDeclarationSyntax CreateLoadDispatchDataMethod( - Type shaderInterfaceType, - ImmutableArray fieldInfos, - int resourceCount, - int root32BitConstantsCount) - { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchData")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TDataLoader")), - Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), - Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. - /// - /// The type of shader interface urrently being processed. - /// The array of values for all captured fields. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The sequence of instances to load shader dispatch data. - private static ImmutableArray GetDispatchDataLoadingStatements( - Type shaderInterfaceType, - ImmutableArray fieldInfos, - int resourceCount, - int root32BitConstantsCount) - { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); - - // Append the statements for the dispatch ranges: - // - // span0[0] = (uint)x; - // span0[1] = (uint)y; - // span0[2] = (uint)z; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); - - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .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) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); - } - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) - { - case FieldInfo.Resource resource: - - // Validate the resource and get a handle for it. This will generate: - // - // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) = - // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device); - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"), - ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)")))); - break; - case FieldInfo.Primitive primitive: - - // Read a primitive value and serialize it into the target buffer. This will generate: - // - // global::System.Runtime.CompilerServices.Unsafe.As>( - // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), - ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; - string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; - - // Declare a local to index into individual rows. This will generate: - // - // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( - // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); - - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < matrix.Rows; j++) - { - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); - } - break; - } - } - - // 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( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedValues"))) - .AddArgumentListArguments(Argument(IdentifierName("span0"))))); - - 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( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedResources"))) - .AddArgumentListArguments(Argument(IdentifierName("span1"))))); - } - - return statements.ToImmutable(); - } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs new file mode 100644 index 00000000..d5ad9351 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The dispatch metadata for the current shader.. + /// The resulting instance for the LoadDispatchMetadata method. + private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchMetadata")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TMetadataLoader")), + Parameter(Identifier("result")) + .AddModifiers(Token(SyntaxKind.OutKeyword)) + .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) + .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); + } + + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The dispatch metadata for the current shader.. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // global::System.Span span0 = stackalloc byte[5]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); + + // Compute the total number of resources + int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; + + // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); + + // ref byte r0 = ref span0[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // Serialized shader metadata + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});")); + + + // Populate the sequence of resource descriptors + foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) + { + statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); + } + + // Invoke the value delegate to create the opaque root signature handle + statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs index 06531460..6e671a19 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs @@ -1,13 +1,6 @@ -using System; -using System.Collections.Immutable; -using ComputeSharp.__Internals; +using System.Collections.Immutable; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -62,121 +55,4 @@ public sealed partial class IShaderGenerator2 isSamplerUsed, descriptors.ToImmutable()); } - - /// - /// Creates a instance for the LoadDispatchMetadata method. - /// - /// The dispatch metadata for the current shader.. - /// The resulting instance for the LoadDispatchMetadata method. - private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo) - { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchMetadata")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TMetadataLoader")), - Parameter(Identifier("result")) - .AddModifiers(Token(SyntaxKind.OutKeyword)) - .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) - .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); - } - - /// - /// Gets a sequence of statements to load the dispatch metadata for a given shader type. - /// - /// The dispatch metadata for the current shader.. - /// The sequence of instances to load shader dispatch data. - private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) - { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - - // global::System.Span span0 = stackalloc byte[5]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); - - // Compute the total number of resources - int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; - - // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); - - // ref byte r0 = ref span0[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // Serialized shader metadata - statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); - statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});")); - - - // Populate the sequence of resource descriptors - foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) - { - statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); - } - - // Invoke the value delegate to create the opaque root signature handle - statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); - - return statements.ToImmutable(); - } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs new file mode 100644 index 00000000..a4917459 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs @@ -0,0 +1,187 @@ +using System; +using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input instance. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the BuildHlslString method. + private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) + { + BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); + + if (bytecodeLiterals is not null) + { + fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); + } + else + { + fixup = static tree => tree.ToFullString(); + } + + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.BoolKeyword)), + Identifier("TryGetBytecode")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) + .WithBody(block); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance. + /// The resulting bytecode literals to insert into the final source code. + /// The instance trying to retrieve the precompiled shader. + [Pure] + private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) + { + if (bytecodeInfo.Bytecode.IsEmpty) + { + bytecodeLiterals = null; + + // This code produces a method declaration as follows: + // + // bytecode = default; + // + // return false; + return + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement( + LiteralExpression( + SyntaxKind.FalseLiteralExpression))); + } + + bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // This code produces a method declaration as follows: + // + // if (threadsX == && threadsY == && threadsZ == ) + // { + // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // + // return true; + // } + // + // bytecode = default; + // + // return false; + // + // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string + // is created by the generator. This greatly speeds up the code generation, as it avoids + // having to create/parse tens of thousands of literal expression nodes for every shader. + return + Block( + IfStatement( + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsX"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsY"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsZ"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))), + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), + ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); + } + + /// + /// A mapping of precomputed literals for all values. + /// + private static readonly string[] formattedBytes = + { + "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", + "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", + "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", + "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", + "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", + "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", + "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", + "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", + "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", + "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", + "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", + "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", + "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", + "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", + "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", + "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" + }; + + /// + /// Creates a formatted expression to initialize a with a given shader data. + /// + /// The input shader bytecode to serialize. + /// A formatted with the serialized data. + private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) + { + //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values + using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); + + builder.Append(formattedBytes[bytecode[0]]); + + foreach (byte b in bytecode.Slice(1)) + { + builder.Append(", "); + builder.Append(formattedBytes[b]); + } + + return builder.WrittenSpan.ToString(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs index 7cc33038..8d2c1170 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs @@ -7,20 +7,15 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.__Internals; using ComputeSharp.Exceptions; using ComputeSharp.Shaders.Translation; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -220,175 +215,4 @@ public sealed partial class IShaderGenerator2 areDxcLibrariesLoaded = true; } - - /// - /// Creates a instance for the TryGetBytecode method. - /// - /// The input instance. - /// An opaque instance to transform the final tree into text. - /// The resulting instance for the BuildHlslString method. - private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) - { - BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); - - if (bytecodeLiterals is not null) - { - fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); - } - else - { - fixup = static tree => tree.ToFullString(); - } - - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.BoolKeyword)), - Identifier("TryGetBytecode")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) - .WithBody(block); - } - - /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. - /// - /// The input instance. - /// The resulting bytecode literals to insert into the final source code. - /// The instance trying to retrieve the precompiled shader. - [Pure] - private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) - { - if (bytecodeInfo.Bytecode.IsEmpty) - { - bytecodeLiterals = null; - - // This code produces a method declaration as follows: - // - // bytecode = default; - // - // return false; - return - Block( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), - ReturnStatement( - LiteralExpression( - SyntaxKind.FalseLiteralExpression))); - } - - bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); - - // This code produces a method declaration as follows: - // - // if (threadsX == && threadsY == && threadsZ == ) - // { - // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; - // - // return true; - // } - // - // bytecode = default; - // - // return false; - // - // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string - // is created by the generator. This greatly speeds up the code generation, as it avoids - // having to create/parse tens of thousands of literal expression nodes for every shader. - return - Block( - IfStatement( - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsX"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsY"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsZ"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))), - Block( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), - ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), - ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); - } - - /// - /// A mapping of precomputed literals for all values. - /// - private static readonly string[] formattedBytes = - { - "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", - "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", - "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", - "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", - "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", - "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", - "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", - "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", - "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", - "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", - "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", - "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", - "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", - "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", - "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", - "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" - }; - - /// - /// Creates a formatted expression to initialize a with a given shader data. - /// - /// The input shader bytecode to serialize. - /// A formatted with the serialized data. - private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) - { - //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values - using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); - - builder.Append(formattedBytes[bytecode[0]]); - - foreach (byte b in bytecode.Slice(1)) - { - builder.Append(", "); - builder.Append(formattedBytes[b]); - } - - return builder.WrittenSpan.ToString(); - } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs deleted file mode 100644 index 5f153721..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs +++ /dev/null @@ -1,725 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using ComputeSharp.SourceGenerators.Models; -using ComputeSharp.SourceGenerators.SyntaxRewriters; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618, RS1024 - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator2 -{ - /// - /// Gathers all necessary information on a transpiled HLSL source for a given shader type. - /// - /// The input object currently in use. - /// The node to process. - /// The for . - /// The resulting diagnostics from the processing operation. - /// The resulting info on the processed shader. - private static HlslSourceInfo GetNonDynamicHlslSourceInfo( - Compilation compilation, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out ImmutableArray diagnostics) - { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - - // Properties are not supported - DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // A given type can only represent a single shader type - if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) - { - builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); - } - - // Explore the syntax tree and extract the processed info - var semanticModelProvider = new SemanticModelProvider(compilation); - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); - var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol); - var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); - var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); - var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); - var declaredTypes = GetDeclaredTypes(discoveredTypes); - var definedConstants = GetDefinedConstants(constantDefinitions); - var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - - diagnostics = builder.ToImmutable(); - - // Get the HLSL source data with the intermediate info - return GetNonDynamicHlslSourceInfo( - definedConstants, - declaredTypes, - resourceFields, - valueFields, - delegateInstanceFields, - staticFields, - sharedBuffers, - processedMethods, - isComputeShader, - implicitTextureType, - isSamplerUsed, - entryPoint); - } - - /// - /// Gets a sequence of captured fields and their mapped names. - /// - /// The collection of produced instances. - /// The input instance to process. - /// The collection of currently discovered types. - /// Indicates whether or not represents a compute shader. - /// A sequence of captured fields in . - [Pure] - private static ( - ImmutableArray<(string MetadataName, string Name, string HlslType)>, - ImmutableArray<(string Name, string HlslType)>) - GetInstanceFields( - ImmutableArray.Builder 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)>(); - bool hlslResourceFound = false; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (fieldSymbol.IsStatic) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - // Group shared fields must be static - if (attribute is not null) - { - diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); - } - - // Captured fields must be named type symbols - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) - { - diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - string metadataName = typeSymbol.GetFullMetadataName(); - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Allowed fields must be either resources, unmanaged values or delegates - if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - hlslResourceFound = true; - - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) - { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); - } - - // Add the current mapping for the name (if the name used a reserved keyword) - resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); - } - else if (!typeSymbol.IsUnmanagedType && - typeSymbol.TypeKind != TypeKind.Delegate) - { - // Shaders can only capture valid HLSL resource types or unmanaged types - diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - - continue; - } - else if (typeSymbol.IsUnmanagedType) - { - // Track the type if it's a custom struct - if (!HlslKnownTypes.IsKnownHlslType(metadataName)) - { - types.Add(typeSymbol); - } - - values.Add((mapping ?? fieldSymbol.Name, typeName)); - } - } - - // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource - if (!hlslResourceFound && isComputeShader) - { - diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); - } - - return (resources.ToImmutable(), values.ToImmutable()); - } - - /// - /// Gets a sequence of shader static fields and their mapped names. - /// - /// The collection of produced instances. - /// The instance for the type to process. - /// The instance for the current type. - /// The type symbol for the shader type. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of static constant fields in . - [Pure] - private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, - SemanticModelProvider semanticModel, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); - - foreach (var fieldDeclaration in structDeclaration.Members.OfType()) - { - foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) - { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; - - if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is not null) - { - continue; - } - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) - { - diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string typeDeclaration = fieldSymbol.IsReadOnly switch - { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; - - StaticFieldRewriter2 staticFieldRewriter = new( - semanticModel, - discoveredTypes, - constantDefinitions, - diagnostics); - - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); - - builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); - } - } - - return builder.ToImmutable(); - } - - /// - /// Gets a sequence of captured members and their mapped names. - /// - /// The collection of produced instances. - /// The input instance to process. - /// The collection of currently discovered types. - /// A sequence of captured members in . - [Pure] - private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( - ImmutableArray.Builder diagnostics, - INamedTypeSymbol structDeclarationSymbol, - ICollection types) - { - ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (!fieldSymbol.IsStatic) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is null) - { - continue; - } - - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - - string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize)); - - types.Add((INamedTypeSymbol)typeSymbol.ElementType); - } - - return builder.ToImmutable(); - } - - /// - /// Gets a sequence of processed methods declared within a given type. - /// - /// The collection of produced instances. - /// The type symbol for the shader type. - /// The instance for the current type. - /// The instance for the type to process. - /// The collection of currently discovered types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// Indicates whether or not represents a compute shader. - /// A sequence of processed methods in , and the entry point. - [Pure] - private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( - ImmutableArray.Builder diagnostics, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - bool isComputeShader) - { - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - string? entryPoint = null; - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); - bool isSamplerUsed = false; - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) - { - IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; - bool isShaderEntryPoint = - (isComputeShader && - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) || - (!isComputeShader && - methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && - methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0); - - // Create the source rewriter for the current method - ShaderSourceRewriter2 shaderSourceRewriter = new( - structDeclarationSymbol, - semanticModel, - discoveredTypes, - staticMethods, - constantDefinitions, - diagnostics, - isShaderEntryPoint); - - // Rewrite the method syntax tree - MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - - // Track the implicit sampler, if used - isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - - // Emit the extracted local functions first - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - // If the method is the shader entry point, do additional processing - if (isShaderEntryPoint) - { - processedMethod = isComputeShader switch - { - true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)! - }; - - entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); - } - else - { - methods.Add(( - processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - } - - // Process static methods as well - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - methods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - return (entryPoint!, methods.ToImmutable(), isSamplerUsed); - } - - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - [Pure] - internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) - { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); - - foreach (var constant in constantDefinitions) - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - builder.Add((constantName, constant.Value)); - } - - return builder.MoveToImmutable(); - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// The sequence of discovered custom types. - /// A sequence of custom type definitions to add to the shader source. - internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) - { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); - - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) - { - var structType = type.GetFullMetadataName().ToHlslIdentifierName(); - var structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (var field in type.GetMembers().OfType()) - { - if (field.IsStatic) continue; - - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) - { - mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); - } - - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mapped!)).AddVariables( - VariableDeclarator(Identifier(field.Name))))); - } - - // Insert the trailing ; right after the closing bracket (after normalization) - builder.Add(( - structType, - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString())); - } - - return builder.ToImmutable(); - } - - /// - /// Finds and reports all declared properties in a shader. - /// - /// The collection of produced instances. - /// The input instance to process. - private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) - { - foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) - { - diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); - } - } - - /// - /// Produces the series of statements to build the current HLSL source. - /// - /// The sequence of defined constants for the shader. - /// The sequence of declared types used by the shader. - /// The sequence of resource instance fields for the current shader. - /// The sequence of value instance fields for the current shader. - /// The sequence of delegate fields for the current shader. - /// The sequence of static fields referenced by the shader. - /// The sequence of shared buffers declared by the shader. - /// The sequence of processed methods used by the shader. - /// Whether or not the current shader type is a compute shader. - /// The type of the implicit target texture, if present. - /// Whether the static sampler is used by the shader. - /// The body of the entry point of the shader. - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static HlslSourceInfo GetNonDynamicHlslSourceInfo( - ImmutableArray<(string Name, string Value)> definedConstants, - ImmutableArray<(string Name, string Definition)> declaredTypes, - ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, - ImmutableArray<(string Name, string HlslType)> valueFields, - ImmutableArray delegateInstanceFields, - ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, - ImmutableArray<(string Signature, string Definition)> processedMethods, - bool isComputeShader, - string? implicitTextureType, - bool isSamplerUsed, - - string executeMethod) - { - StringBuilder hlslBuilder = new(); - - void AppendLF() - { - hlslBuilder.Append('\n'); - } - - void AppendLine(string text) - { - hlslBuilder.Append(text); - } - - void AppendLineAndLF(string text) - { - hlslBuilder.Append(text); - hlslBuilder.Append('\n'); - } - - void AppendCharacterAndLF(char c) - { - hlslBuilder.Append(c); - hlslBuilder.Append('\n'); - } - - string FlushText() - { - string text = hlslBuilder.ToString(); - - hlslBuilder.Clear(); - - return text; - } - - // Header - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// AUTO GENERATED"); - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// This shader was created by ComputeSharp."); - AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); - - // Group size constants - AppendLF(); - AppendLine("#define __GroupSize__get_X "); - - string headerAndThreadsX = FlushText(); - - AppendLF(); - AppendLine("#define __GroupSize__get_Y "); - - string threadsY = FlushText(); - - AppendLF(); - AppendLine("#define __GroupSize__get_Z "); - - string threadsZ = FlushText(); - - AppendLF(); - - // Define declarations - foreach (var (name, value) in definedConstants) - { - AppendLineAndLF($"#define {name} {value}"); - } - - string defines = FlushText(); - - // Static fields - if (staticFields.Any()) - { - AppendLF(); - - foreach (var field in staticFields) - { - if (field.Assignment is string assignment) - { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); - } - else - { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); - } - } - } - - // Declared types - foreach (var (_, typeDefinition) in declaredTypes) - { - AppendLF(); - AppendLineAndLF(typeDefinition); - } - - string staticFieldsAndDeclaredTypes = FlushText(); - - // Captured variables - AppendLF(); - AppendLineAndLF("cbuffer _ : register(b0)"); - AppendCharacterAndLF('{'); - AppendLineAndLF(" uint __x;"); - AppendLineAndLF(" uint __y;"); - - if (isComputeShader) - { - AppendLineAndLF(" uint __z;"); - } - - // User-defined values - foreach (var (fieldName, fieldType) in valueFields) - { - AppendLineAndLF($" {fieldType} {fieldName};"); - } - - AppendCharacterAndLF('}'); - - int constantBuffersCount = 1; - int readOnlyBuffersCount = 0; - int readWriteBuffersCount = 0; - - // Optional implicit texture field - if (!isComputeShader) - { - AppendLF(); - AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); - } - - // Optional sampler field - if (isSamplerUsed) - { - AppendLF(); - AppendLineAndLF("SamplerState __sampler : register(s);"); - } - - // Resources - foreach (var (metadataName, fieldName, fieldType) in resourceFields) - { - if (HlslKnownTypes.IsConstantBufferType(metadataName)) - { - AppendLF(); - AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); - AppendCharacterAndLF('{'); - AppendLineAndLF($" {fieldType} {fieldName}[2];"); - AppendCharacterAndLF('}'); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) - { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); - } - else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName)) - { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); - } - } - - // Shared buffers - foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) - { - object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; - - AppendLF(); - AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); - } - - // Forward declarations - foreach (var (forwardDeclaration, _) in processedMethods) - { - AppendLF(); - AppendLineAndLF(forwardDeclaration); - } - - string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); - - // Captured methods - foreach (var (_, method) in processedMethods) - { - AppendLF(); - AppendLineAndLF(method); - } - - string capturedMethods = FlushText(); - - // Entry point - AppendLF(); - AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); - AppendLineAndLF(executeMethod); - - string entryPoint = FlushText(); - - return new( - headerAndThreadsX, - threadsY, - threadsZ, - defines, - staticFieldsAndDeclaredTypes, - capturedFieldsAndResourcesAndForwardDeclarations, - capturedMethods, - entryPoint, - implicitTextureType, - isSamplerUsed, - declaredTypes.Select(static t => t.Name).ToImmutableArray(), - definedConstants.Select(static c => c.Name).ToImmutableArray(), - processedMethods.Select(static m => m.Signature).ToImmutableArray(), - delegateInstanceFields); - } -} From a48f036518dd8148a58663528772cf9640ffbbd2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 00:14:26 +0100 Subject: [PATCH 19/36] Delete non-incremental IShaderGenerator files --- ...erGenerator.CreateBuildHlslStringMethod.cs | 834 ------------------ ...aderGenerator.CreateGetDispatchIdMethod.cs | 101 --- ...rGenerator.CreateLoadDispatchDataMethod.cs | 335 ------- ...erator.CreateLoadDispatchMetadataMethod.cs | 156 ---- ...derGenerator.CreateTryGetBytecodeMethod.cs | 322 ------- ...ntal.CreateBuildHlslStringMethod.Syntax.cs | 2 +- ...Incremental.CreateBuildHlslStringMethod.cs | 2 +- ...mental.CreateGetDispatchIdMethod.Syntax.cs | 2 +- ...r.Incremental.CreateGetDispatchIdMethod.cs | 2 +- ...tal.CreateLoadDispatchDataMethod.Syntax.cs | 2 +- ...ncremental.CreateLoadDispatchDataMethod.cs | 2 +- ...CreateLoadDispatchMetadataMethod.Syntax.cs | 2 +- ...mental.CreateLoadDispatchMetadataMethod.cs | 2 +- ...ental.CreateTryGetBytecodeMethod.Syntax.cs | 2 +- ....Incremental.CreateTryGetBytecodeMethod.cs | 2 +- .../IShaderGenerator.Incremental.cs | 2 +- .../IShaderGenerator.SyntaxReceiver.cs | 47 - .../IShaderGenerator.cs | 224 ----- .../ShaderMethodSourceGenerator.cs | 5 +- 19 files changed, 13 insertions(+), 2033 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs deleted file mode 100644 index 94d6bf45..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ /dev/null @@ -1,834 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using ComputeSharp.SourceGenerators.SyntaxRewriters; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -#pragma warning disable CS0618, RS1024 - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator -{ - /// - private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out string? implicitTextureType, - out bool isSamplerUsed, - out string hlslSource) - { - // Properties are not supported - DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // A given type can only represent a single shader type - if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) - { - context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); - } - - // Explore the syntax tree and extract the processed info - var semanticModel = new SemanticModelProvider(context.Compilation); - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); - var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); - var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?); - var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = GetProcessedConstants(constantDefinitions); - var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - string structName = structDeclaration.Identifier.Text; - SyntaxTokenList structModifiers = structDeclaration.Modifiers; - IEnumerable bodyStatements = GenerateRenderMethodBody( - processedConstants, - staticFields, - processedTypes, - isComputeShader, - processedMembers, - pixelShaderTextureType, - accessesStaticSampler, - sharedBuffers, - processedMethods, - entryPoint, - out hlslSource); - - implicitTextureType = pixelShaderTextureType; - isSamplerUsed = accessesStaticSampler; - - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("BuildHlslString")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(bodyStatements)); - } - - /// - /// Gets a sequence of captured fields and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// Indicates whether or not represents a compute shader. - /// A sequence of captured fields in . - [Pure] - private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types, - bool isComputeShader) - { - bool hlslResourceFound = false; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - // Group shared fields must be static - if (attribute is not null) - { - context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); - } - - // Captured fields must be named type symbols - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - string metadataName = typeSymbol.GetFullMetadataName(); - - // Allowed fields must be either resources, unmanaged values or delegates - if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - hlslResourceFound = true; - - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) - { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); - } - } - else if (!typeSymbol.IsUnmanagedType && - typeSymbol.TypeKind != TypeKind.Delegate) - { - // Shaders can only capture valid HLSL resource types or unmanaged types - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - - continue; - } - else if (typeSymbol.IsUnmanagedType && - !HlslKnownTypes.IsKnownHlslType(metadataName)) - { - // Track the type if it's a custom struct - types.Add(typeSymbol); - } - - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); - } - - // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource - if (!hlslResourceFound && isComputeShader) - { - context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); - } - } - - /// - /// Gets a sequence of shader static fields and their mapped names. - /// - /// The current generator context in use. - /// The instance for the type to process. - /// The instance for the current type. - /// The type symbol for the shader type. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of static constant fields in . - [Pure] - private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - GeneratorExecutionContext context, - SemanticModelProvider semanticModel, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - foreach (var fieldDeclaration in structDeclaration.Members.OfType()) - { - foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) - { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; - - if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is not null) continue; - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) - { - context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string typeDeclaration = fieldSymbol.IsReadOnly switch - { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; - - StaticFieldRewriter staticFieldRewriter = new( - semanticModel, - discoveredTypes, - constantDefinitions, - context); - - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); - - yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); - } - } - } - - /// - /// Gets a sequence of captured members and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// A sequence of captured members in . - [Pure] - private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types) - { - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (!fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is null) continue; - - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - - string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); - - types.Add((INamedTypeSymbol)typeSymbol.ElementType); - } - } - - /// - /// Gets a sequence of processed methods declared within a given type. - /// - /// The current generator context in use. - /// The type symbol for the shader type. - /// The instance for the current type. - /// The instance for the type to process. - /// The collection of currently discovered types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// Indicates whether or not represents a compute shader. - /// A sequence of processed methods in , and the entry point. - [Pure] - private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - bool isComputeShader) - { - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - string? entryPoint = null; - List<(string, string)> processedMethods = new(); - bool isSamplerUsed = false; - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) - { - IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; - bool isShaderEntryPoint = - (isComputeShader && - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) || - (!isComputeShader && - methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && - methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0); - - // Create the source rewriter for the current method - ShaderSourceRewriter shaderSourceRewriter = new( - structDeclarationSymbol, - semanticModel, - discoveredTypes, - staticMethods, - constantDefinitions, - context, - isShaderEntryPoint); - - // Rewrite the method syntax tree - MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - - // Track the implicit sampler, if used - isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - - // Emit the extracted local functions first - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - processedMethods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - // If the method is the shader entry point, do additional processing - if (isShaderEntryPoint) - { - processedMethod = isComputeShader switch - { - true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! - }; - - entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); - } - else - { - processedMethods.Add(( - processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - } - - // Process static methods as well - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - processedMethods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - return (entryPoint!, processedMethods, isSamplerUsed); - } - - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - [Pure] - internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) - { - foreach (var constant in constantDefinitions) - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - yield return (constantName, constant.Value); - } - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// The sequence of discovered custom types. - /// A sequence of custom type definitions to add to the shader source. - internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable types) - { - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) - { - var structType = type.GetFullMetadataName().ToHlslIdentifierName(); - var structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (var field in type.GetMembers().OfType()) - { - if (field.IsStatic) continue; - - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) - { - mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); - } - - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mapped!)).AddVariables( - VariableDeclarator(Identifier(field.Name))))); - } - - // Insert the trailing ; right after the closing bracket (after normalization) - yield return - (structType, - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString()); - } - } - - /// - /// Finds and reports all declared properties in a shader. - /// - /// The current generator context in use. - /// The input instance to process. - private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol) - { - foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) - { - context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); - } - } - - /// - /// Produces the series of statements to build the current HLSL source. - /// - /// The sequence of defined constants for the shader. - /// The sequence of static fields referenced by the shader. - /// The sequence of declared types used by the shader. - /// Whether or not the current shader is a compute shader (or a pixel shader). - /// The sequence of instance fields for the current shader. - /// The type of the implicit target texture, if present. - /// Whether the static sampler is used by the shader. - /// The sequence of shared buffers declared by the shader. - /// The sequence of processed methods used by the shader. - /// The body of the entry point of the shader. - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static IEnumerable GenerateRenderMethodBody( - IEnumerable<(string Name, string Value)> definedConstants, - IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - IEnumerable<(string Name, string Definition)> declaredTypes, - bool isComputeShader, - IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, - string? implicitTextureType, - bool isSamplerUsed, - IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable<(string Signature, string Definition)> processedMethods, - string executeMethod, - out string hlslSource) - { - List statements = new(); - StringBuilder chunkedTextBuilder = new(); - StringBuilder aggregateTextBuilder = new(); - int capturedDelegates = 0; - int prologueStatements = 0; - int sizeHint = 64; - - void AppendLF() - { - chunkedTextBuilder.Append('\n'); - } - - void AppendLine(string text) - { - chunkedTextBuilder.Append(text); - } - - void AppendLineAndLF(string text) - { - chunkedTextBuilder.Append(text); - chunkedTextBuilder.Append('\n'); - } - - void AppendCharacterAndLF(char c) - { - chunkedTextBuilder.Append(c); - chunkedTextBuilder.Append('\n'); - } - - void AppendThreadNumIdentifier(string name) - { - aggregateTextBuilder.Append(name); - } - - void AppendParsedStatement(string text) - { - FlushText(); - - statements.Add(ParseStatement(text)); - } - - void FlushText() - { - if (chunkedTextBuilder.Length > 0) - { - string chunkedText = chunkedTextBuilder.ToString(); - - aggregateTextBuilder.Append(chunkedText); - - sizeHint += chunkedTextBuilder.Length; - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(chunkedText)))))); - - chunkedTextBuilder.Clear(); - } - } - - // Declare the hashsets to track imported members and types from delegates, if needed - if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - void DeclareMapping(int index, string name, IEnumerable items) - { - // global::System.Collections.Generic.HashSet = new(); - statements.Insert(index, - LocalDeclarationStatement(VariableDeclaration( - GenericName(Identifier("global::System.Collections.Generic.HashSet")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) - .AddVariables( - VariableDeclarator(Identifier(name)) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); - - prologueStatements++; - - // .Add(""); - foreach (var item in items) - { - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(name), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); - - prologueStatements++; - } - } - - DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name)); - DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name)); - DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature)); - - // Go through all existing delegate fields, if any - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - prologueStatements++; - } - } - - // Header - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// AUTO GENERATED"); - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// This shader was created by ComputeSharp."); - AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); - - // Group size constants - AppendLF(); - AppendLine("#define __GroupSize__get_X "); - AppendParsedStatement("builder.Append(threadsX);"); - AppendThreadNumIdentifier(""); - AppendLF(); - AppendLine("#define __GroupSize__get_Y "); - AppendParsedStatement("builder.Append(threadsY);"); - AppendThreadNumIdentifier(""); - AppendLF(); - AppendLine("#define __GroupSize__get_Z "); - AppendParsedStatement("builder.Append(threadsZ);"); - AppendThreadNumIdentifier(""); - AppendLF(); - - // Define declarations - foreach (var (name, value) in definedConstants) - { - AppendLineAndLF($"#define {name} {value}"); - } - - // Defines from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); - } - - // Static fields - if (staticFields.Any()) - { - AppendLF(); - - foreach (var field in staticFields) - { - if (field.Assignment is string assignment) - { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); - } - else - { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); - } - } - } - - // Declared types - foreach (var (_, typeDefinition) in declaredTypes) - { - AppendLF(); - AppendLineAndLF(typeDefinition); - } - - // Declared types from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - } - - // Captured variables - AppendLF(); - AppendLineAndLF("cbuffer _ : register(b0)"); - AppendCharacterAndLF('{'); - AppendLineAndLF(" uint __x;"); - AppendLineAndLF(" uint __y;"); - - if (isComputeShader) - { - AppendLineAndLF(" uint __z;"); - } - - // User-defined values - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType)) - { - AppendLineAndLF($" {fieldType} {fieldName};"); - } - - AppendCharacterAndLF('}'); - - int constantBuffersCount = 1; - int readOnlyBuffersCount = 0; - int readWriteBuffersCount = 0; - - // Optional implicit texture field - if (!isComputeShader) - { - AppendLF(); - AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); - } - - // Optional sampler field - if (isSamplerUsed) - { - AppendLF(); - AppendLineAndLF("SamplerState __sampler : register(s);"); - } - - // Resources - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) - { - string metadataName = fieldSymbol.Type.GetFullMetadataName(); - - if (HlslKnownTypes.IsConstantBufferType(metadataName)) - { - AppendLF(); - AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); - AppendCharacterAndLF('{'); - AppendLineAndLF($" {fieldType} {fieldName}[2];"); - AppendCharacterAndLF('}'); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) - { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); - } - else if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); - } - } - - // Shared buffers - foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) - { - object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; - - AppendLF(); - AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); - } - - // Forward declarations - foreach (var (forwardDeclaration, _) in processedMethods) - { - AppendLF(); - AppendLineAndLF(forwardDeclaration); - } - - // Forward declarations from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); - } - - // Remove all forward declarations from methods that are embedded into the shader. - // This is necessary to avoid duplicate definitions from methods from delegates. - if (capturedDelegates > 0) - { - // .Add(""); - foreach (var (forwardDeclaration, _) in processedMethods) - { - FlushText(); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("__methodNames"), - IdentifierName("Remove"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); - } - } - - // Captured methods - foreach (var (_, method) in processedMethods) - { - AppendLF(); - AppendLineAndLF(method); - } - - // Captured methods from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); - } - - // Captured delegate methods - foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendLF(); - AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); - AppendLF(); - } - - // Entry point - AppendLF(); - AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); - AppendLineAndLF(executeMethod); - - FlushText(); - - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - statements.Insert( - prologueStatements, - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("builder"), - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), - IdentifierName("Create"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(sizeHint))))))); - - hlslSource = aggregateTextBuilder.ToString(); - - return statements; - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs deleted file mode 100644 index 1e8a3eae..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using ComputeSharp.__Internals; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator -{ - /// - private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader) - { - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("GetDispatchId")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(structDeclarationSymbol, out isDynamicShader)); - } - - /// - /// Gets a instance with the logic to compute the hashcode of a given shader type. - /// - /// The input instance to process. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The instance to hash the input shader. - [Pure] - private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader) - { - var delegateFields = structDeclarationSymbol - .GetMembers() - .OfType() - .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) - .ToImmutableArray(); - - isDynamicShader = delegateFields.Length > 0; - - if (delegateFields.Length == 0) - { - // return 0; - return - Block(ReturnStatement( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))); - } - - List blockStatements = new(4); - - // global::System.HashCode hashCode = default; - blockStatements.Add(LocalDeclarationStatement( - VariableDeclaration(IdentifierName("global::System.HashCode")) - .AddVariables( - VariableDeclarator(Identifier("hashCode")) - .WithInitializer(EqualsValueClause( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))))); - - foreach (IFieldSymbol fieldSymbol in delegateFields) - { - // hashCode.Add(delegateField.Method); - blockStatements.Add(ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(fieldSymbol.Name), - IdentifierName("Method")))))); - } - - // return hashCode.ToHashCode(); - blockStatements.Add(ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("ToHashCode"))))); - - return Block(blockStatements); - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs deleted file mode 100644 index a6288e93..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ /dev/null @@ -1,335 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using ComputeSharp.__Internals; -using ComputeSharp.Core.Helpers; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator -{ - /// - private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - out IReadOnlyCollection discoveredResources, - out int root32BitConstantsCount) - { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchData")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TDataLoader")), - Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), - Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount))); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of discovered resources in the current shader type. - /// The total number of 32 bit root constants being loaded for the current shader type. - /// The sequence of instances to load shader dispatch data. - private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) - { - List statements = new(); - List resources = new(); - - discoveredResources = resources; - - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - int resourceOffset = 0; - int rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); - - // Append the statements for the dispatch ranges: - // - // span0[0] = (uint)x; - // span0[1] = (uint)y; - // span0[2] = (uint)z; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); - - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); - - if (isComputeShader) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); - } - - // Append the statements to load all fields (both resources and other captured values) - AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, resources, statements); - - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to a multiple of a 32 bit value. This is necessary to - // enable loading all the dispatch data after reinterpreting it to a sequence of values - // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); - root32BitConstantsCount = rawDataOffset / sizeof(int); - - // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. - // Loaded values in the root signature have the following costs: - // - Root constants cost 1 DWORD each, since they are 32-bit values. - // - Descriptor tables cost 1 DWORD each. - // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. - // So here we check whether the current signature respects that constraint, - // and emit a build error otherwise. For more info on this, see the docs here: - // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. - int rootSignatureDwordSize = root32BitConstantsCount + resourceOffset; - - if (rootSignatureDwordSize > 64) - { - context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - } - - // 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( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedValues"))) - .AddArgumentListArguments(Argument(IdentifierName("span0"))))); - - if (resourceOffset > 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(resourceOffset))))))))))); - - // 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( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedResources"))) - .AddArgumentListArguments(Argument(IdentifierName("span1"))))); - } - - return statements; - } - - /// - /// Explores a given type hierarchy and generates statements to load fields. - /// - /// The current type being explored. - /// The current path of the field with respect to the shader instance. - /// The current offset in the root table of loaded resources. - /// The current offset within the loaded data buffer. - /// The target list of resources in the current shader type. - /// The target list of statements being generated. - private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection resources, ICollection statements) - { - bool isFirstField = true; - - foreach ( - IFieldSymbol fieldSymbol in - from fieldSymbol in currentTypeSymbol.GetMembers().OfType() - where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && - !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer - select fieldSymbol) - { - string fieldName = fieldSymbol.Name; - string typeName = fieldSymbol.Type.GetFullMetadataName(); - - // Disambiguates the name of target fields against the current input parameters - if (fieldName is "loader" or "device" or "x" or "y" or "z") - { - fieldName = $"this.{fieldName}"; - } - - // The first item in each nested struct needs to be aligned to 16 bytes - if (isFirstField && fieldPath.Count > 0) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - isFirstField = false; - } - - if (HlslKnownTypes.IsTypedResourceType(typeName)) - { - resources.Add(typeName); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++})"), - ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); - } - else if (HlslKnownTypes.IsKnownHlslType(typeName)) - { - AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements); - } - else if (fieldSymbol.Type.IsUnmanagedType) - { - // Custom struct type defined by the user - AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements); - } - } - } - - /// - /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix). - /// - /// The current path of the field with respect to the shader instance. - /// The type name currently being read. - /// The current offset within the loaded data buffer. - /// The target list of statements being generated. - private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements) - { - // For scalar, vector and linear matrix types, serialize the value normally. - // Only the initial alignment needs to be considered, while data is packed. - var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); - - // Check if the current type is a matrix type with more than one row. In this - // case, each row is aligned as if it was a separate array, so the start of - // 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)) - { - string rowTypeName = $"global::ComputeSharp.{elementName}{columns}"; - string rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; - - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); - - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < rows; j++) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); - - rawDataOffset += fieldPack * columns; - } - } - else - { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer). - // Since we're in a constant buffer, we need to both pad the starting offset - // to be aligned to the packing size of the type, and also to align the initial - // offset to ensure that values do not cross 16 bytes boundaries either. - rawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, fieldPack), - fieldSize, - 16); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), - ParseExpression($"{string.Join(".", fieldPath)}")))); - - rawDataOffset += fieldSize; - } - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs deleted file mode 100644 index 391416d0..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ /dev/null @@ -1,156 +0,0 @@ -using System; -using System.Collections.Generic; -using ComputeSharp.__Internals; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator -{ - /// - private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( - string? implicitTextureType, - IReadOnlyCollection discoveredResources, - int root32BitConstantsCount, - bool isSamplerUsed) - { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchMetadata")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TMetadataLoader")), - Parameter(Identifier("result")) - .AddModifiers(Token(SyntaxKind.OutKeyword)) - .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) - .WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed))); - } - - /// - /// Gets a sequence of statements to load the dispatch metadata for a given shader type. - /// - /// The implicit texture type, if available (if the shader is a pixel shader). - /// The collection of resources used by the shader. - /// The total number of 32 bit root constants being loaded for the shader. - /// Whether or not the shader requires a static sampler to be available. - /// The sequence of instances to load shader dispatch data. - private static IEnumerable GetDispatchMetadataLoadingStatements( - string? implicitTextureType, - IReadOnlyCollection discoveredResources, - int root32BitConstantsCount, - bool isSamplerUsed) - { - // global::System.Span span0 = stackalloc byte[5]; - yield return - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))); - - // Compute the total number of resources (discovered ones and the implicit target texture, if present) - int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0); - - // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; - yield return - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))); - - // ref byte r0 = ref span0[0]; - yield return - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0))))))))); - - // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; - yield return - LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0))))))))); - - // Serialized shader metadata - yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {root32BitConstantsCount});"); - yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});"); - - int constantBufferOffset = 1; - int readOnlyResourceOffset = 0; - int readWriteResourceOffset = 0; - int resourceOffset = 0; - - // Add the implicit texture descriptor, if needed - if (implicitTextureType is not null) - { - yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); - } - - // Populate the sequence of resource descriptors - foreach (var resource in discoveredResources) - { - if (HlslKnownTypes.IsConstantBufferType(resource)) - { - yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(2, {constantBufferOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource)) - { - yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); - } - else - { - yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); - } - } - - // Invoke the value delegate to create the opaque root signature handle - yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"); - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs deleted file mode 100644 index 78e78d53..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ /dev/null @@ -1,322 +0,0 @@ -using System; -using System.ComponentModel; -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using ComputeSharp.__Internals; -using ComputeSharp.Exceptions; -using ComputeSharp.Shaders.Translation; -using ComputeSharp.SourceGenerators.Diagnostics; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator -{ - /// - /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. - /// - private static bool areDxcLibrariesLoaded; - - /// - private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - bool isDynamicShader, - string hlslSource, - out string? bytecodeLiterals) - { - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.BoolKeyword)), - Identifier("TryGetBytecode")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) - .WithBody(GetShaderBytecodeBody(context, structDeclarationSymbol, isDynamicShader, hlslSource, out bytecodeLiterals)); - } - - /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. - /// - /// The current generator context in use. - /// The input instance to process. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting bytecode literals to insert into the final source code. - /// The instance to hash the input shader. - [Pure] - private static unsafe BlockSyntax GetShaderBytecodeBody( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - bool isDynamicShader, - string hlslSource, - out string? bytecodeLiterals) - { - AttributeData? attribute = structDeclarationSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(EmbeddedBytecodeAttribute) }); - - // No embedded shader was requested - if (attribute is null) - { - goto Failure; - } - - // If the current shader is dynamic, emit a diagnostic error - if (isDynamicShader) - { - context.ReportDiagnostic(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); - - goto Failure; - } - - // Validate the thread number arguments - if (attribute.ConstructorArguments[0].Value is not int threadsX || - attribute.ConstructorArguments[1].Value is not int threadsY || - attribute.ConstructorArguments[2].Value is not int threadsZ || - threadsX is < 1 or > 1024 || - threadsY is < 1 or > 1024 || - threadsZ is < 1 or > 64) - { - context.ReportDiagnostic(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); - - goto Failure; - } - - try - { - // Try to load dxcompiler.dll and dxil.dll - LoadNativeDxcLibraries(); - - // Replace the actual thread num values - hlslSource = hlslSource.Replace("", threadsX.ToString()).Replace("", threadsY.ToString()).Replace("", threadsZ.ToString()); - - // Compile the shader bytecode - using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); - - byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); - int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); - - // Build and set the text with the literal expressions - bytecodeLiterals = BuildShaderBytecodeExpressionString(new ReadOnlySpan(buffer, length)); - - // This code produces a method declaration as follows: - // - // if (threadsX == && threadsY == && threadsZ == ) - // { - // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; - // - // return true; - // } - // - // bytecode = default; - // - // return false; - // - // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string - // is created by the generator. This greatly speeds up the code generation, as it avoids - // having to create/parse tens of thousands of literal expression nodes for every shader. - return - Block( - IfStatement( - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsX"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsX))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsY"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsY)))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsZ"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsZ)))), - Block( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), - ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), - ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); - } - catch (Win32Exception e) - { - context.ReportDiagnostic( - EmbeddedBytecodeFailedWithWin32Exception, - structDeclarationSymbol, - structDeclarationSymbol, - e.HResult, - e.Message); - } - catch (HlslCompilationException e) - { - context.ReportDiagnostic( - EmbeddedBytecodeFailedWithHlslCompilationException, - structDeclarationSymbol, - structDeclarationSymbol, - e.Message); - } - - Failure: - bytecodeLiterals = null; - - // This code produces a method declaration as follows: - // - // bytecode = default; - // - // return false; - return - Block( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), - ReturnStatement( - LiteralExpression( - SyntaxKind.FalseLiteralExpression))); - } - - /// - /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. - /// - /// Thrown if the CPU architecture is not supported. - /// Thrown if a library fails to load. - private static void LoadNativeDxcLibraries() - { - // Extracts a specified native library for a given runtime identifier - static string ExtractLibrary(string rid, string name) - { - string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; - string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll"); - - Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); - - using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); - - try - { - using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write); - - sourceStream.CopyTo(destinationStream); - } - catch (IOException) - { - } - - return targetFilename; - } - - // Loads a target native library - static unsafe void LoadLibrary(string filename) - { - [DllImport("kernel32", ExactSpelling = true, SetLastError = true)] - static extern void* LoadLibraryW(ushort* lpLibFileName); - - fixed (char* p = filename) - { - if (LoadLibraryW((ushort*)p) is null) - { - int hresult = Marshal.GetLastWin32Error(); - - throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}."); - } - } - } - - if (!areDxcLibrariesLoaded) - { - string rid = RuntimeInformation.ProcessArchitecture switch - { - Architecture.X64 => "x64", - Architecture.Arm64 => "arm64", - _ => throw new NotSupportedException("Invalid process architecture") - }; - - LoadLibrary(ExtractLibrary(rid, "dxil")); - LoadLibrary(ExtractLibrary(rid, "dxcompiler")); - } - - areDxcLibrariesLoaded = true; - } - - /// - /// A mapping of precomputed literals for all values. - /// - private static readonly string[] formattedBytes = - { - "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", - "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", - "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", - "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", - "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", - "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", - "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", - "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", - "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", - "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", - "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", - "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", - "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", - "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", - "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", - "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" - }; - - /// - /// Creates a formatted expression to initialize a with a given shader data. - /// - /// The input shader bytecode to serialize. - /// A formatted with the serialized data. - private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) - { - //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values - using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); - - builder.Append(formattedBytes[bytecode[0]]); - - foreach (byte b in bytecode.Slice(1)) - { - builder.Append(", "); - builder.Append(formattedBytes[b]); - } - - return builder.WrittenSpan.ToString(); - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs index 73116592..30ae2e4c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs @@ -12,7 +12,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Creates a instance for the BuildHlslString method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs index e5ecf8c2..92db4fb3 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs @@ -21,7 +21,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Gathers all necessary information on a transpiled HLSL source for a given shader type. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs index fe0e9a61..2a7e5d16 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs @@ -11,7 +11,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Creates a instance for the GetDispatchId method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs index 9ea1324f..0148802c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs @@ -6,7 +6,7 @@ using Microsoft.CodeAnalysis; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Extracts the names of all instance fields of a type. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs index 65e63abb..e6ef3d2b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs @@ -11,7 +11,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Creates a instance for the LoadDispatchDataMethod method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs index 579581de..ec2d39e8 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs @@ -14,7 +14,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Explores a given type hierarchy and generates statements to load fields. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs index d5ad9351..ea70202a 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -11,7 +11,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Creates a instance for the LoadDispatchMetadata method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs index 6e671a19..a4dc5339 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs @@ -5,7 +5,7 @@ using ComputeSharp.SourceGenerators.Models; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Gets the data related to the shader metadata for a given shader type. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs index a4917459..035239a5 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs @@ -12,7 +12,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Creates a instance for the TryGetBytecode method. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs index 8d2c1170..7be250dd 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs @@ -20,7 +20,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; /// -public sealed partial class IShaderGenerator2 +public sealed partial class IShaderGenerator { /// /// Gets the thread ids values for a given shader type, if available. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 1ee1527f..25868a19 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -19,7 +19,7 @@ namespace ComputeSharp.SourceGenerators; /// A source generator creating data loaders for and types. /// [Generator] -public sealed partial class IShaderGenerator2 : IIncrementalGenerator +public sealed partial class IShaderGenerator : IIncrementalGenerator { /// public void Initialize(IncrementalGeneratorInitializationContext context) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs deleted file mode 100644 index 1fe3c634..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class IShaderGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => - interfaceSymbol.Name == nameof(IComputeShader) || - interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs deleted file mode 100644 index 52f01b52..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ /dev/null @@ -1,224 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Text; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -namespace ComputeSharp.SourceGenerators; - -/// -/// A source generator creating data loaders for and types. -/// -[Generator] -public sealed partial class IShaderGenerator : ISourceGenerator -{ - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - try - { - OnExecute(context, item.StructDeclaration, item.StructSymbol); - } - catch - { - context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The for . - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) - { - // Create the required interface methods for the current shader type - MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol, out bool isDynamicShader); - MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants); - MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out string hlslSource); - MethodDeclarationSyntax loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); - MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(context, structDeclarationSymbol, isDynamicShader, hlslSource, out string? bytecodeLiterals); - - // Reorder the method declarations to respect the order in the interface definition - MethodDeclarationSyntax[] methods = - { - // getDispatchIdMethod, - // loadDispatchDataMethod, - //loadDispatchMetadataMethod, - //buildHlslStringMethod, - //tryGetBytecodeMethod - }; - - // Method attributes - List attributes = new() - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - // Add [SkipLocalsInit] if the target project allows it and can access it - if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && - context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null) - { - attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); - } - - string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - string structName = structDeclaration.Identifier.Text; - SyntaxTokenList structModifiers = structDeclaration.Modifiers; - - // Create the partial shader type declaration with the hashcode interface method implementation. - // This code produces a struct declaration as follows: - // - // public struct ShaderType - // { - // - // } - var structDeclarationSyntax = - StructDeclaration(structName) - .WithModifiers(structModifiers) - .AddMembers(methods.Select(m => m.AddAttributeLists(attributes.ToArray())).ToArray()); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (var parentType in structDeclaration.Ancestors().OfType()) - { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); - } - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // #pragma warning disable - // - // namespace ; - // - // - var source = - CompilationUnit().AddMembers( - FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - // Insert the bytecode literals, if needed - if (bytecodeLiterals is not null) - { - source = source.Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); - } - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Creates a instance for the GetDispatchId method. - /// - /// The for the input struct declaration. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The resulting instance for the GetDispatchId method. - private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader); - - /// - /// Creates a instance for the LoadDispatchDataMethod method. - /// - /// The input instance to use. - /// The for the input struct declaration. - /// The collection of discovered resources in the current shader type. - /// The total number of 32 bit root constants being loaded for the current shader type. - /// The resulting instance for the LoadDispatchDataMethod method. - private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - out IReadOnlyCollection discoveredResources, - out int root32BitConstantsCount); - - /// - /// Creates a instance for the BuildHlslString method. - /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The implicit texture type, if available (if the shader is a pixel shader). - /// Whether or not the current shader type requires a static sampler to be available. - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting instance for the BuildHlslString method. - private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out string? implicitTextureType, - out bool isSamplerUsed, - out string hlslSource); - - /// - /// Creates a instance for the LoadDispatchMetadata method. - /// - /// The implicit texture type, if available (if the shader is a pixel shader). - /// The collection of resources used by the shader. - /// The total number of 32 bit root constants being loaded for the shader. - /// Whether or not the shader requires a static sampler to be available. - /// The resulting instance for the LoadDispatchMetadata method. - private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( - string? implicitTextureType, - IReadOnlyCollection discoveredResources, - int root32BitConstantsCount, - bool isSamplerUsed); - - /// - /// Creates a instance for the TryGetBytecode method. - /// - /// The input instance to use. - /// The for the shader type. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting bytecode literals to insert into the final source code. - /// The resulting instance for the BuildHlslString method. - private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - bool isDynamicShader, - string hlslSource, - out string? bytecodeLiterals); -} diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index cfabb6a4..374f9478 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; -using System.Linq; using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; @@ -70,8 +69,8 @@ public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator // Explore the syntax tree and extract the processed info var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions); + var processedTypes = IShaderGenerator.GetDeclaredTypes(discoveredTypes); + var processedConstants = IShaderGenerator.GetDefinedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = From 1262bf6e0ee0b55f4907ff2de89745a5c6632bb3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 00:17:40 +0100 Subject: [PATCH 20/36] Rename incremental generator files over non-incremental ones --- ....cs => IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs} | 0 ...gMethod.cs => IShaderGenerator.CreateBuildHlslStringMethod.cs} | 0 ...ax.cs => IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs} | 0 ...hIdMethod.cs => IShaderGenerator.CreateGetDispatchIdMethod.cs} | 0 ...cs => IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs} | 0 ...Method.cs => IShaderGenerator.CreateLoadDispatchDataMethod.cs} | 0 ...> IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs} | 0 ...od.cs => IShaderGenerator.CreateLoadDispatchMetadataMethod.cs} | 0 ...x.cs => IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs} | 0 ...deMethod.cs => IShaderGenerator.CreateTryGetBytecodeMethod.cs} | 0 .../{IShaderGenerator.Incremental.cs => IShaderGenerator.cs} | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs => IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs => IShaderGenerator.CreateBuildHlslStringMethod.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs => IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs => IShaderGenerator.CreateGetDispatchIdMethod.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs => IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs => IShaderGenerator.CreateLoadDispatchDataMethod.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs => IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs => IShaderGenerator.CreateLoadDispatchMetadataMethod.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs => IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs => IShaderGenerator.CreateTryGetBytecodeMethod.cs} (100%) rename src/ComputeSharp.SourceGenerators/{IShaderGenerator.Incremental.cs => IShaderGenerator.cs} (100%) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.Syntax.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.Syntax.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateGetDispatchIdMethod.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.Syntax.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.Syntax.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.Syntax.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateTryGetBytecodeMethod.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs similarity index 100% rename from src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs rename to src/ComputeSharp.SourceGenerators/IShaderGenerator.cs From 000435305237078727cf0c1b54fc46c5937ea0d6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 00:34:21 +0100 Subject: [PATCH 21/36] Code refactoring in IShaderGenerator --- ...ator.CreateBuildHlslStringMethod.Syntax.cs | 410 +++--- ...erGenerator.CreateBuildHlslStringMethod.cs | 1292 +++++++++-------- ...erator.CreateGetDispatchIdMethod.Syntax.cs | 136 +- ...aderGenerator.CreateGetDispatchIdMethod.cs | 30 +- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 374 ++--- ...rGenerator.CreateLoadDispatchDataMethod.cs | 286 ++-- ...CreateLoadDispatchMetadataMethod.Syntax.cs | 224 +-- ...erator.CreateLoadDispatchMetadataMethod.cs | 82 +- ...rator.CreateTryGetBytecodeMethod.Syntax.cs | 304 ++-- ...derGenerator.CreateTryGetBytecodeMethod.cs | 324 +++-- .../IShaderGenerator.Helpers.cs | 126 ++ .../IShaderGenerator.cs | 140 +- .../ShaderMethodSourceGenerator.cs | 4 +- 13 files changed, 1897 insertions(+), 1835 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs index 30ae2e4c..8ecc9d28 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs @@ -14,241 +14,245 @@ namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { - /// - /// Creates a instance for the BuildHlslString method. - /// - /// The input instance to use. - /// The resulting instance for the BuildHlslString method. - private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo) + /// + internal static partial class BuildHlslString { - ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); - - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("BuildHlslString")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(bodyStatements)); - } - - /// - /// Produces the series of statements to build the current HLSL source. - /// - /// The input instance to use. - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) - { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - StringBuilder textBuilder = new(); - int capturedDelegates = 0; - int prologueStatements = 0; - int sizeHint = 64; - - void AppendLF() + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The resulting instance for the BuildHlslString method. + public static MethodDeclarationSyntax GetSyntax(HlslSourceInfo hlslSourceInfo) { - textBuilder.Append('\n'); + ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); + + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements)); } - void AppendLine(string text) + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The input instance to use. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) { - textBuilder.Append(text); - } + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + StringBuilder textBuilder = new(); + int capturedDelegates = 0; + int prologueStatements = 0; + int sizeHint = 64; - void AppendParsedStatement(string text) - { - FlushText(); - - statements.Add(ParseStatement(text)); - } - - void FlushText() - { - if (textBuilder.Length > 0) + void AppendLF() { - string text = textBuilder.ToString(); - - textBuilder.Append(text); - - sizeHint += textBuilder.Length; - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); - - textBuilder.Clear(); + textBuilder.Append('\n'); } - } - // Declare the hashsets to track imported members and types from delegates, if needed - if (!hlslSourceInfo.Delegates.IsEmpty) - { - void DeclareMapping(int index, string name, IEnumerable items) + void AppendLine(string text) { - // global::System.Collections.Generic.HashSet = new(); - statements.Insert(index, - LocalDeclarationStatement(VariableDeclaration( - GenericName(Identifier("global::System.Collections.Generic.HashSet")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) - .AddVariables( - VariableDeclarator(Identifier(name)) - .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + textBuilder.Append(text); + } - prologueStatements++; + void AppendParsedStatement(string text) + { + FlushText(); - // .Add(""); - foreach (var item in items) + statements.Add(ParseStatement(text)); + } + + void FlushText() + { + if (textBuilder.Length > 0) { + string text = textBuilder.ToString(); + + textBuilder.Append(text); + + sizeHint += textBuilder.Length; + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); + + textBuilder.Clear(); + } + } + + // Declare the hashsets to track imported members and types from delegates, if needed + if (!hlslSourceInfo.Delegates.IsEmpty) + { + void DeclareMapping(int index, string name, IEnumerable items) + { + // global::System.Collections.Generic.HashSet = new(); + statements.Insert(index, + LocalDeclarationStatement(VariableDeclaration( + GenericName(Identifier("global::System.Collections.Generic.HashSet")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .AddVariables( + VariableDeclarator(Identifier(name)) + .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + + prologueStatements++; + + // .Add(""); + foreach (var item in items) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(name), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + + prologueStatements++; + } + } + + DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); + DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); + DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); + + // Go through all existing delegate fields, if any + foreach (string fieldName in hlslSourceInfo.Delegates) + { + // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } + } + + // Header and thread ids + AppendLine(hlslSourceInfo.HeaderAndThreadsX); + AppendParsedStatement("builder.Append(threadsX);"); + AppendLine(hlslSourceInfo.ThreadsY); + AppendParsedStatement("builder.Append(threadsY);"); + AppendLine(hlslSourceInfo.ThreadsZ); + AppendParsedStatement("builder.Append(threadsZ);"); + + // Define declarations + AppendLine(hlslSourceInfo.Defines); + + // Defines from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + } + + // Static fields and declared types + AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); + + // Declared types from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); + } + + // Captured variables + AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); + + // Forward declarations from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) + { + FlushText(); + statements.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(name), - IdentifierName("Add"))) + IdentifierName("__methodNames"), + IdentifierName("Remove"))) .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); - - prologueStatements++; + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); } } - DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); - DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); - DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); + // Captured methods + AppendLine(hlslSourceInfo.CapturedMethods); - // Go through all existing delegate fields, if any + // Captured methods from captured delegates foreach (string fieldName in hlslSourceInfo.Delegates) { - // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - prologueStatements++; + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); } - } - // Header and thread ids - AppendLine(hlslSourceInfo.HeaderAndThreadsX); - AppendParsedStatement("builder.Append(threadsX);"); - AppendLine(hlslSourceInfo.ThreadsY); - AppendParsedStatement("builder.Append(threadsY);"); - AppendLine(hlslSourceInfo.ThreadsZ); - AppendParsedStatement("builder.Append(threadsZ);"); - - // Define declarations - AppendLine(hlslSourceInfo.Defines); - - // Defines from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); - } - - // Static fields and declared types - AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); - - // Declared types from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - } - - // Captured variables - AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); - - // Forward declarations from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); - } - - // Remove all forward declarations from methods that are embedded into the shader. - // This is necessary to avoid duplicate definitions from methods from delegates. - if (capturedDelegates > 0) - { - // .Add(""); - foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) + // Captured delegate methods + foreach (string fieldName in hlslSourceInfo.Delegates) { - FlushText(); + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); + AppendLF(); + } - statements.Add( - ExpressionStatement( + // Entry point + AppendLine(hlslSourceInfo.EntryPoint); + + FlushText(); + + // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); + statements.Insert( + prologueStatements, + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("builder"), InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("__methodNames"), - IdentifierName("Remove"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); - } + IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), + IdentifierName("Create"))) + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(sizeHint))))))); + + return statements.ToImmutable(); } - - // Captured methods - AppendLine(hlslSourceInfo.CapturedMethods); - - // Captured methods from captured delegates - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); - } - - // Captured delegate methods - foreach (string fieldName in hlslSourceInfo.Delegates) - { - AppendLF(); - AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); - AppendLF(); - } - - // Entry point - AppendLine(hlslSourceInfo.EntryPoint); - - FlushText(); - - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - statements.Insert( - prologueStatements, - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("builder"), - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), - IdentifierName("Create"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(sizeHint))))))); - - return statements.ToImmutable(); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 92db4fb3..3f791bdd 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -24,720 +24,726 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator { /// - /// Gathers all necessary information on a transpiled HLSL source for a given shader type. + /// A helper with all logic to generate the BuildHlslString method. /// - /// The input object currently in use. - /// The node to process. - /// The for . - /// The resulting diagnostics from the processing operation. - /// The resulting info on the processed shader. - private static HlslSourceInfo GetNonDynamicHlslSourceInfo( - Compilation compilation, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out ImmutableArray diagnostics) + internal static partial class BuildHlslString { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - - // Properties are not supported - DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // A given type can only represent a single shader type - if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) - { - builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); - } - - // Explore the syntax tree and extract the processed info - var semanticModelProvider = new SemanticModelProvider(compilation); - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); - var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol); - var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); - var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); - var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); - var declaredTypes = GetDeclaredTypes(discoveredTypes); - var definedConstants = GetDefinedConstants(constantDefinitions); - var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - - diagnostics = builder.ToImmutable(); - - // Get the HLSL source data with the intermediate info - return GetNonDynamicHlslSourceInfo( - definedConstants, - declaredTypes, - resourceFields, - valueFields, - delegateInstanceFields, - staticFields, - sharedBuffers, - processedMethods, - isComputeShader, - implicitTextureType, - isSamplerUsed, - entryPoint); - } - - /// - /// Gets a sequence of captured fields and their mapped names. - /// - /// The collection of produced instances. - /// The input instance to process. - /// The collection of currently discovered types. - /// Indicates whether or not represents a compute shader. - /// A sequence of captured fields in . - [Pure] - private static ( - ImmutableArray<(string MetadataName, string Name, string HlslType)>, - ImmutableArray<(string Name, string HlslType)>) - GetInstanceFields( - ImmutableArray.Builder diagnostics, + /// + /// Gathers all necessary information on a transpiled HLSL source for a given shader type. + /// + /// The input object currently in use. + /// The node to process. + /// The for . + /// The resulting diagnostics from the processing operation. + /// The resulting info on the processed shader. + public static HlslSourceInfo GetInfo( + Compilation compilation, + StructDeclarationSyntax structDeclaration, 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)>(); - bool hlslResourceFound = false; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + out ImmutableArray diagnostics) { - if (fieldSymbol.IsStatic) + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // Properties are not supported + DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) { - continue; + builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + // Explore the syntax tree and extract the processed info + var semanticModelProvider = new SemanticModelProvider(compilation); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol); + var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); + var declaredTypes = GetDeclaredTypes(discoveredTypes); + var definedConstants = GetDefinedConstants(constantDefinitions); + var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - // Group shared fields must be static - if (attribute is not null) - { - diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); - } + diagnostics = builder.ToImmutable(); - // Captured fields must be named type symbols - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) - { - diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - string metadataName = typeSymbol.GetFullMetadataName(); - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Allowed fields must be either resources, unmanaged values or delegates - if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - hlslResourceFound = true; - - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) - { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); - } - - // Add the current mapping for the name (if the name used a reserved keyword) - resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); - } - else if (!typeSymbol.IsUnmanagedType && - typeSymbol.TypeKind != TypeKind.Delegate) - { - // Shaders can only capture valid HLSL resource types or unmanaged types - diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - - continue; - } - else if (typeSymbol.IsUnmanagedType) - { - // Track the type if it's a custom struct - if (!HlslKnownTypes.IsKnownHlslType(metadataName)) - { - types.Add(typeSymbol); - } - - values.Add((mapping ?? fieldSymbol.Name, typeName)); - } + // Get the HLSL source data with the intermediate info + return GetHlslSourceInfo( + definedConstants, + declaredTypes, + resourceFields, + valueFields, + delegateInstanceFields, + staticFields, + sharedBuffers, + processedMethods, + isComputeShader, + implicitTextureType, + isSamplerUsed, + entryPoint); } - // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource - if (!hlslResourceFound && isComputeShader) + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. + /// A sequence of captured fields in . + [Pure] + private static ( + ImmutableArray<(string MetadataName, string Name, string HlslType)>, + ImmutableArray<(string Name, string HlslType)>) + GetInstanceFields( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types, + bool isComputeShader) { - diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); - } + ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>(); + ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + bool hlslResourceFound = false; - return (resources.ToImmutable(), values.ToImmutable()); - } - - /// - /// Gets a sequence of shader static fields and their mapped names. - /// - /// The collection of produced instances. - /// The instance for the type to process. - /// The instance for the current type. - /// The type symbol for the shader type. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of static constant fields in . - [Pure] - private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, - SemanticModelProvider semanticModel, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); - - foreach (var fieldDeclaration in structDeclaration.Members.OfType()) - { - foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; - - if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + if (fieldSymbol.IsStatic) { continue; } AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + // Group shared fields must be static if (attribute is not null) { - continue; + diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); } - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) { - diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); continue; } + string metadataName = typeSymbol.GetFullMetadataName(); + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - string typeDeclaration = fieldSymbol.IsReadOnly switch + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; + hlslResourceFound = true; - StaticFieldRewriter2 staticFieldRewriter = new( - semanticModel, - discoveredTypes, - constantDefinitions, - diagnostics); + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); - - builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); - } - } - - return builder.ToImmutable(); - } - - /// - /// Gets a sequence of captured members and their mapped names. - /// - /// The collection of produced instances. - /// The input instance to process. - /// The collection of currently discovered types. - /// A sequence of captured members in . - [Pure] - private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( - ImmutableArray.Builder diagnostics, - INamedTypeSymbol structDeclarationSymbol, - ICollection types) - { - ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (!fieldSymbol.IsStatic) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is null) - { - continue; - } - - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - - string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize)); - - types.Add((INamedTypeSymbol)typeSymbol.ElementType); - } - - return builder.ToImmutable(); - } - - /// - /// Gets a sequence of processed methods declared within a given type. - /// - /// The collection of produced instances. - /// The type symbol for the shader type. - /// The instance for the current type. - /// The instance for the type to process. - /// The collection of currently discovered types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// Indicates whether or not represents a compute shader. - /// A sequence of processed methods in , and the entry point. - [Pure] - private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( - ImmutableArray.Builder diagnostics, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - bool isComputeShader) - { - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - string? entryPoint = null; - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); - bool isSamplerUsed = false; - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) - { - IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; - bool isShaderEntryPoint = - (isComputeShader && - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) || - (!isComputeShader && - methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && - methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0); - - // Create the source rewriter for the current method - ShaderSourceRewriter2 shaderSourceRewriter = new( - structDeclarationSymbol, - semanticModel, - discoveredTypes, - staticMethods, - constantDefinitions, - diagnostics, - isShaderEntryPoint); - - // Rewrite the method syntax tree - MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - - // Track the implicit sampler, if used - isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - - // Emit the extracted local functions first - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - // If the method is the shader entry point, do additional processing - if (isShaderEntryPoint) - { - processedMethod = isComputeShader switch + // Add the current mapping for the name (if the name used a reserved keyword) + resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); + } + else if (!typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) { - true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)! - }; + // Shaders can only capture valid HLSL resource types or unmanaged types + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); - } - else - { - methods.Add(( - processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - } - - // Process static methods as well - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - methods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - return (entryPoint!, methods.ToImmutable(), isSamplerUsed); - } - - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - [Pure] - internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) - { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); - - foreach (var constant in constantDefinitions) - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - builder.Add((constantName, constant.Value)); - } - - return builder.MoveToImmutable(); - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// The sequence of discovered custom types. - /// A sequence of custom type definitions to add to the shader source. - internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) - { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); - - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) - { - var structType = type.GetFullMetadataName().ToHlslIdentifierName(); - var structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (var field in type.GetMembers().OfType()) - { - if (field.IsStatic) continue; - - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + continue; + } + else if (typeSymbol.IsUnmanagedType) { - mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + // Track the type if it's a custom struct + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + types.Add(typeSymbol); + } + + values.Add((mapping ?? fieldSymbol.Name, typeName)); + } + } + + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) + { + diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); + } + + return (resources.ToImmutable(), values.ToImmutable()); + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The collection of produced instances. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + [Pure] + private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + ImmutableArray.Builder diagnostics, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is not null) + { + continue; + } + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter2 staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + diagnostics); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + + builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + } + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) + { + continue; } - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mapped!)).AddVariables( - VariableDeclarator(Identifier(field.Name))))); + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is null) + { + continue; + } + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + if (!typeSymbol.ElementType.IsUnmanagedType) + { + diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize)); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); } - // Insert the trailing ; right after the closing bracket (after normalization) - builder.Add(( - structType, - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString())); + return builder.ToImmutable(); } - return builder.ToImmutable(); - } - - /// - /// Finds and reports all declared properties in a shader. - /// - /// The collection of produced instances. - /// The input instance to process. - private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) - { - foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The collection of produced instances. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. + /// A sequence of processed methods in , and the entry point. + [Pure] + private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( + ImmutableArray.Builder diagnostics, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + bool isComputeShader) { - diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); - } - } + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - /// - /// Produces the series of statements to build the current HLSL source. - /// - /// The sequence of defined constants for the shader. - /// The sequence of declared types used by the shader. - /// The sequence of resource instance fields for the current shader. - /// The sequence of value instance fields for the current shader. - /// The sequence of delegate fields for the current shader. - /// The sequence of static fields referenced by the shader. - /// The sequence of shared buffers declared by the shader. - /// The sequence of processed methods used by the shader. - /// Whether or not the current shader type is a compute shader. - /// The type of the implicit target texture, if present. - /// Whether the static sampler is used by the shader. - /// The body of the entry point of the shader. - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static HlslSourceInfo GetNonDynamicHlslSourceInfo( - ImmutableArray<(string Name, string Value)> definedConstants, - ImmutableArray<(string Name, string Definition)> declaredTypes, - ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, - ImmutableArray<(string Name, string HlslType)> valueFields, - ImmutableArray delegateInstanceFields, - ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, - ImmutableArray<(string Signature, string Definition)> processedMethods, - bool isComputeShader, - string? implicitTextureType, - bool isSamplerUsed, - - string executeMethod) - { - StringBuilder hlslBuilder = new(); + string? entryPoint = null; + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + bool isSamplerUsed = false; - void AppendLF() - { - hlslBuilder.Append('\n'); - } - - void AppendLine(string text) - { - hlslBuilder.Append(text); - } - - void AppendLineAndLF(string text) - { - hlslBuilder.Append(text); - hlslBuilder.Append('\n'); - } - - void AppendCharacterAndLF(char c) - { - hlslBuilder.Append(c); - hlslBuilder.Append('\n'); - } - - string FlushText() - { - string text = hlslBuilder.ToString(); - - hlslBuilder.Clear(); - - return text; - } - - // Header - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// AUTO GENERATED"); - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// This shader was created by ComputeSharp."); - AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); - - // Group size constants - AppendLF(); - AppendLine("#define __GroupSize__get_X "); - - string headerAndThreadsX = FlushText(); - - AppendLF(); - AppendLine("#define __GroupSize__get_Y "); - - string threadsY = FlushText(); - - AppendLF(); - AppendLine("#define __GroupSize__get_Z "); - - string threadsZ = FlushText(); - - AppendLF(); - - // Define declarations - foreach (var (name, value) in definedConstants) - { - AppendLineAndLF($"#define {name} {value}"); - } - - string defines = FlushText(); - - // Static fields - if (staticFields.Any()) - { - AppendLF(); - - foreach (var field in staticFields) + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { - if (field.Assignment is string assignment) + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); + + // Create the source rewriter for the current method + ShaderSourceRewriter2 shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + diagnostics, + isShaderEntryPoint); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; + + entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); } else { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + methods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } } - } - // Declared types - foreach (var (_, typeDefinition) in declaredTypes) - { - AppendLF(); - AppendLineAndLF(typeDefinition); - } - - string staticFieldsAndDeclaredTypes = FlushText(); - - // Captured variables - AppendLF(); - AppendLineAndLF("cbuffer _ : register(b0)"); - AppendCharacterAndLF('{'); - AppendLineAndLF(" uint __x;"); - AppendLineAndLF(" uint __y;"); - - if (isComputeShader) - { - AppendLineAndLF(" uint __z;"); - } - - // User-defined values - foreach (var (fieldName, fieldType) in valueFields) - { - AppendLineAndLF($" {fieldType} {fieldName};"); - } - - AppendCharacterAndLF('}'); - - int constantBuffersCount = 1; - int readOnlyBuffersCount = 0; - int readWriteBuffersCount = 0; - - // Optional implicit texture field - if (!isComputeShader) - { - AppendLF(); - AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); - } - - // Optional sampler field - if (isSamplerUsed) - { - AppendLF(); - AppendLineAndLF("SamplerState __sampler : register(s);"); - } - - // Resources - foreach (var (metadataName, fieldName, fieldType) in resourceFields) - { - if (HlslKnownTypes.IsConstantBufferType(metadataName)) + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) { - AppendLF(); - AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); - AppendCharacterAndLF('{'); - AppendLineAndLF($" {fieldType} {fieldName}[2];"); - AppendCharacterAndLF('}'); + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + + return (entryPoint!, methods.ToImmutable(), isSamplerUsed); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + + foreach (var constant in constantDefinitions) { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); } - else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName)) + + return builder.MoveToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + builder.Add(( + structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); } } - // Shared buffers - foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of declared types used by the shader. + /// The sequence of resource instance fields for the current shader. + /// The sequence of value instance fields for the current shader. + /// The sequence of delegate fields for the current shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of shared buffers declared by the shader. + /// The sequence of processed methods used by the shader. + /// Whether or not the current shader type is a compute shader. + /// The type of the implicit target texture, if present. + /// Whether the static sampler is used by the shader. + /// The body of the entry point of the shader. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static HlslSourceInfo GetHlslSourceInfo( + ImmutableArray<(string Name, string Value)> definedConstants, + ImmutableArray<(string Name, string Definition)> declaredTypes, + ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, + ImmutableArray<(string Name, string HlslType)> valueFields, + ImmutableArray delegateInstanceFields, + ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, + ImmutableArray<(string Signature, string Definition)> processedMethods, + bool isComputeShader, + string? implicitTextureType, + bool isSamplerUsed, + + string executeMethod) { - object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + StringBuilder hlslBuilder = new(); + + void AppendLF() + { + hlslBuilder.Append('\n'); + } + + void AppendLine(string text) + { + hlslBuilder.Append(text); + } + + void AppendLineAndLF(string text) + { + hlslBuilder.Append(text); + hlslBuilder.Append('\n'); + } + + void AppendCharacterAndLF(char c) + { + hlslBuilder.Append(c); + hlslBuilder.Append('\n'); + } + + string FlushText() + { + string text = hlslBuilder.ToString(); + + hlslBuilder.Clear(); + + return text; + } + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + + // Group size constants + AppendLF(); + AppendLine("#define __GroupSize__get_X "); + + string headerAndThreadsX = FlushText(); AppendLF(); - AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); - } + AppendLine("#define __GroupSize__get_Y "); + + string threadsY = FlushText(); - // Forward declarations - foreach (var (forwardDeclaration, _) in processedMethods) - { AppendLF(); - AppendLineAndLF(forwardDeclaration); - } + AppendLine("#define __GroupSize__get_Z "); - string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); + string threadsZ = FlushText(); - // Captured methods - foreach (var (_, method) in processedMethods) - { AppendLF(); - AppendLineAndLF(method); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + string defines = FlushText(); + + // Static fields + if (staticFields.Any()) + { + AppendLF(); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } + } + } + + // Declared types + foreach (var (_, typeDefinition) in declaredTypes) + { + AppendLF(); + AppendLineAndLF(typeDefinition); + } + + string staticFieldsAndDeclaredTypes = FlushText(); + + // Captured variables + AppendLF(); + AppendLineAndLF("cbuffer _ : register(b0)"); + AppendCharacterAndLF('{'); + AppendLineAndLF(" uint __x;"); + AppendLineAndLF(" uint __y;"); + + if (isComputeShader) + { + AppendLineAndLF(" uint __z;"); + } + + // User-defined values + foreach (var (fieldName, fieldType) in valueFields) + { + AppendLineAndLF($" {fieldType} {fieldName};"); + } + + AppendCharacterAndLF('}'); + + int constantBuffersCount = 1; + int readOnlyBuffersCount = 0; + int readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + AppendLF(); + AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); + } + + // Optional sampler field + if (isSamplerUsed) + { + AppendLF(); + AppendLineAndLF("SamplerState __sampler : register(s);"); + } + + // Resources + foreach (var (metadataName, fieldName, fieldType) in resourceFields) + { + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); + AppendCharacterAndLF('{'); + AppendLineAndLF($" {fieldType} {fieldName}[2];"); + AppendCharacterAndLF('}'); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + } + else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + + AppendLF(); + AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); + } + + // Forward declarations + foreach (var (forwardDeclaration, _) in processedMethods) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); + + // Captured methods + foreach (var (_, method) in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + + string capturedMethods = FlushText(); + + // Entry point + AppendLF(); + AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); + AppendLineAndLF(executeMethod); + + string entryPoint = FlushText(); + + return new( + headerAndThreadsX, + threadsY, + threadsZ, + defines, + staticFieldsAndDeclaredTypes, + capturedFieldsAndResourcesAndForwardDeclarations, + capturedMethods, + entryPoint, + implicitTextureType, + isSamplerUsed, + declaredTypes.Select(static t => t.Name).ToImmutableArray(), + definedConstants.Select(static c => c.Name).ToImmutableArray(), + processedMethods.Select(static m => m.Signature).ToImmutableArray(), + delegateInstanceFields); } - string capturedMethods = FlushText(); - - // Entry point - AppendLF(); - AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); - AppendLineAndLF(executeMethod); - - string entryPoint = FlushText(); - - return new( - headerAndThreadsX, - threadsY, - threadsZ, - defines, - staticFieldsAndDeclaredTypes, - capturedFieldsAndResourcesAndForwardDeclarations, - capturedMethods, - entryPoint, - implicitTextureType, - isSamplerUsed, - declaredTypes.Select(static t => t.Name).ToImmutableArray(), - definedConstants.Select(static c => c.Name).ToImmutableArray(), - processedMethods.Select(static m => m.Signature).ToImmutableArray(), - delegateInstanceFields); - } - - /// - /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). - /// - /// The input instance to use. - /// The non dynamic HLSL source code. - private static string GetNonDynamicHlslSource(HlslSourceInfo hlslSourceInfo) - { - return - hlslSourceInfo.HeaderAndThreadsX + "" + - hlslSourceInfo.ThreadsY + "" + - hlslSourceInfo.ThreadsZ + "" + - hlslSourceInfo.Defines + - hlslSourceInfo.StaticFieldsAndDeclaredTypes + - hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations + - hlslSourceInfo.CapturedMethods + - hlslSourceInfo.EntryPoint; + /// + /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). + /// + /// The input instance to use. + /// The non dynamic HLSL source code. + public static string GetNonDynamicHlslSource(HlslSourceInfo hlslSourceInfo) + { + return + hlslSourceInfo.HeaderAndThreadsX + "" + + hlslSourceInfo.ThreadsY + "" + + hlslSourceInfo.ThreadsZ + "" + + hlslSourceInfo.Defines + + hlslSourceInfo.StaticFieldsAndDeclaredTypes + + hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations + + hlslSourceInfo.CapturedMethods + + hlslSourceInfo.EntryPoint; + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs index 2a7e5d16..273bf081 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs @@ -13,82 +13,86 @@ namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { - /// - /// Creates a instance for the GetDispatchId method. - /// - ///The names of all instance fields within the current shader type. - /// The resulting instance for the GetDispatchId method. - private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray delegateFieldNames) + /// + private static partial class GetDispatchId { - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("GetDispatchId")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(delegateFieldNames)); - } - - /// - /// Gets a instance with the logic to compute the hashcode of a given shader type. - /// - /// The names of all instance fields within the current shader type. - /// The instance to hash the input shader. - [Pure] - private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) - { - if (delegateFieldNames.Length == 0) + /// + /// Creates a instance for the GetDispatchId method. + /// + ///The names of all instance fields within the current shader type. + /// The resulting instance for the GetDispatchId method. + public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames) { - // return 0; + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() + // { + // + // } return - Block(ReturnStatement( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))); + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(delegateFieldNames)); } - List blockStatements = new(4); - - // global::System.HashCode hashCode = default; - blockStatements.Add(LocalDeclarationStatement( - VariableDeclaration(IdentifierName("global::System.HashCode")) - .AddVariables( - VariableDeclarator(Identifier("hashCode")) - .WithInitializer(EqualsValueClause( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))))); - - foreach (string fieldName in delegateFieldNames) + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The names of all instance fields within the current shader type. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) { - // hashCode.Add(delegateField.Method); - blockStatements.Add(ExpressionStatement( + if (delegateFieldNames.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List blockStatements = new(4); + + // global::System.HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("global::System.HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + foreach (string fieldName in delegateFieldNames) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(fieldName), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("hashCode"), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(fieldName), - IdentifierName("Method")))))); + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); } - - // return hashCode.ToHashCode(); - blockStatements.Add(ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("ToHashCode"))))); - - return Block(blockStatements); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs index 0148802c..65b64877 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -9,19 +9,25 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator { /// - /// Extracts the names of all instance fields of a type. + /// A helper with all logic to generate the GetDispatchId method. /// - /// The input instance to process. - /// The names of all instance fields within . - [Pure] - private static ImmutableArray GetDelegateFieldNames(INamedTypeSymbol structDeclarationSymbol) + private static partial class GetDispatchId { - return - structDeclarationSymbol - .GetMembers() - .OfType() - .Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) - .Select(static member => member.Name) - .ToImmutableArray(); + /// + /// Extracts the names of all instance fields of a type. + /// + /// The input instance to process. + /// The names of all instance fields within . + [Pure] + public static ImmutableArray GetInfo(INamedTypeSymbol structDeclarationSymbol) + { + return + structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .Select(static member => member.Name) + .ToImmutableArray(); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index e6ef3d2b..e834356d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -13,233 +13,237 @@ namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { - /// - /// Creates a instance for the LoadDispatchDataMethod method. - /// - /// The type of shader interface urrently being processed. - /// The array of values for all captured fields. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The resulting instance for the LoadDispatchDataMethod method. - private static MethodDeclarationSyntax CreateLoadDispatchDataMethod( - Type shaderInterfaceType, - ImmutableArray fieldInfos, - int resourceCount, - int root32BitConstantsCount) + /// + private static partial class LoadDispatchData { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchData")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TDataLoader")), - Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), - Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. - /// - /// The type of shader interface urrently being processed. - /// The array of values for all captured fields. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The sequence of instances to load shader dispatch data. - private static ImmutableArray GetDispatchDataLoadingStatements( - Type shaderInterfaceType, - ImmutableArray fieldInfos, - int resourceCount, - int root32BitConstantsCount) - { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); - - // Append the statements for the dispatch ranges: - // - // span0[0] = (uint)x; - // span0[1] = (uint)y; - // span0[2] = (uint)z; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); - - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .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) + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting instance for the LoadDispatchDataMethod method. + public static MethodDeclarationSyntax GetSyntax( + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TDataLoader")), + Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), + Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader. + /// + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchDataLoadingStatements( + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + + // Append the statements for the dispatch ranges: + // + // span0[0] = (uint)x; + // span0[1] = (uint)y; + // span0[2] = (uint)z; statements.Add( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); - } + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .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) { - case FieldInfo.Resource resource: - - // Validate the resource and get a handle for it. This will generate: - // - // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) = - // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device); - statements.Add(ExpressionStatement( + statements.Add( + ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"), - ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)")))); - break; - case FieldInfo.Primitive primitive: + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); + } - // Read a primitive value and serialize it into the target buffer. This will generate: - // - // global::System.Runtime.CompilerServices.Unsafe.As>( - // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), - ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); - break; + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in fieldInfos) + { + switch (fieldInfo) + { + case FieldInfo.Resource resource: - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; - string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; - - // Declare a local to index into individual rows. This will generate: - // - // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( - // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); - - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < matrix.Rows; j++) - { + // Validate the resource and get a handle for it. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) = + // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device); statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); - } - break; + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"), + ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)")))); + break; + case FieldInfo.Primitive primitive: + + // Read a primitive value and serialize it into the target buffer. This will generate: + // + // global::System.Runtime.CompilerServices.Unsafe.As>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), + ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + + // Declare a local to index into individual rows. This will generate: + // + // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); + for (int j = 0; j < matrix.Rows; j++) + { + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); + } + break; + } } - } - // 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( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedValues"))) - .AddArgumentListArguments(Argument(IdentifierName("span0"))))); - - if (resourceCount > 0) - { - // global::System.Span span1 = stackalloc ulong[]; - statements.Insert(1, + // global::System.Span span0 = stackalloc uint[]; + statements.Insert(0, LocalDeclarationStatement( VariableDeclaration( GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) .AddVariables( - VariableDeclarator(Identifier("span1")) + VariableDeclarator(Identifier("span0")) .WithInitializer(EqualsValueClause( StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) .AddRankSpecifiers( ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount))))))))))); + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); - // ref ulong r1 = ref span1[0]; - statements.Insert(3, + // ref uint r0 = ref span0[0]; + statements.Insert(1, LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) .AddVariables( - VariableDeclarator(Identifier("r1")) + VariableDeclarator(Identifier("r0")) .WithInitializer(EqualsValueClause( RefExpression( - ElementAccessExpression(IdentifierName("span1")) + ElementAccessExpression(IdentifierName("span0")) .AddArgumentListArguments(Argument( LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(0)))))))))); - // loader.LoadCapturedResources(span1); + // loader.LoadCapturedValues(span0); statements.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("loader"), - IdentifierName("LoadCapturedResources"))) - .AddArgumentListArguments(Argument(IdentifierName("span1"))))); - } + IdentifierName("LoadCapturedValues"))) + .AddArgumentListArguments(Argument(IdentifierName("span0"))))); - return statements.ToImmutable(); + 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( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedResources"))) + .AddArgumentListArguments(Argument(IdentifierName("span1"))))); + } + + return statements.ToImmutable(); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index ec2d39e8..813722bf 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -17,171 +17,177 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator { /// - /// Explores a given type hierarchy and generates statements to load fields. + /// A helper with all logic to generate the LoadDispatchData method. /// - /// The current shader type being explored. - /// The type of shader interface urrently being processed. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The resulting diagnostics from the processing operation. - /// The sequence of instances for all captured resources and values. - private static ImmutableArray GetCapturedFieldInfos( - ITypeSymbol structDeclarationSymbol, - Type shaderInterfaceType, - out int resourceCount, - out int root32BitConstantCount, - out ImmutableArray diagnostics) + private static partial class LoadDispatchData { - // Helper method that uses boxes instead of ref-s (illegal in enumerators) - static IEnumerable GetCapturedFieldInfos( - ITypeSymbol currentTypeSymbol, - ImmutableArray fieldPath, - StrongBox resourceOffset, - StrongBox rawDataOffset) + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The current shader type being explored. + /// The type of shader interface urrently being processed. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting diagnostics from the processing operation. + /// The sequence of instances for all captured resources and values. + public static ImmutableArray GetInfo( + ITypeSymbol structDeclarationSymbol, + Type shaderInterfaceType, + out int resourceCount, + out int root32BitConstantCount, + out ImmutableArray diagnostics) { - bool isFirstField = true; - - foreach ( - IFieldSymbol fieldSymbol in - from fieldSymbol in currentTypeSymbol.GetMembers().OfType() - where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && - !fieldSymbol.IsConst && !fieldSymbol.IsStatic && - !fieldSymbol.IsFixedSizeBuffer - select fieldSymbol) + // Helper method that uses boxes instead of ref-s (illegal in enumerators) + static IEnumerable GetCapturedFieldInfos( + ITypeSymbol currentTypeSymbol, + ImmutableArray fieldPath, + StrongBox resourceOffset, + StrongBox rawDataOffset) { - string fieldName = fieldSymbol.Name; - string typeName = fieldSymbol.Type.GetFullMetadataName(); + bool isFirstField = true; - // Disambiguates the name of target fields against the current input parameters - if (fieldName is "loader" or "device" or "x" or "y" or "z") + foreach ( + IFieldSymbol fieldSymbol in + from fieldSymbol in currentTypeSymbol.GetMembers().OfType() + where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && + !fieldSymbol.IsConst && !fieldSymbol.IsStatic && + !fieldSymbol.IsFixedSizeBuffer + select fieldSymbol) { - fieldName = $"this.{fieldName}"; - } + string fieldName = fieldSymbol.Name; + string typeName = fieldSymbol.Type.GetFullMetadataName(); - // The first item in each nested struct needs to be aligned to 16 bytes - if (isFirstField && fieldPath.Length > 0) - { - rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16); - - isFirstField = false; - } - - if (HlslKnownTypes.IsTypedResourceType(typeName)) - { - yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++); - } - else if (HlslKnownTypes.IsKnownHlslType(typeName)) - { - yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value); - } - else if (fieldSymbol.Type.IsUnmanagedType) - { - // Custom struct type defined by the user - foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), resourceOffset, rawDataOffset)) + // Disambiguates the name of target fields against the current input parameters + if (fieldName is "loader" or "device" or "x" or "y" or "z") { - yield return fieldInfo; + fieldName = $"this.{fieldName}"; + } + + // The first item in each nested struct needs to be aligned to 16 bytes + if (isFirstField && fieldPath.Length > 0) + { + rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16); + + isFirstField = false; + } + + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++); + } + else if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value); + } + else if (fieldSymbol.Type.IsUnmanagedType) + { + // Custom struct type defined by the user + foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), resourceOffset, rawDataOffset)) + { + yield return fieldInfo; + } } } } - } - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - // Setup the resource and byte offsets for tracking. Pixel shaders have only two - // implicitly captured int values, as they're always dispatched over a 2D texture. - bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); - int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); - StrongBox resourceOffsetAsBox = new(); - StrongBox rawDataOffsetAsBox = new(initialRawDataOffset); + // Setup the resource and byte offsets for tracking. Pixel shaders have only two + // implicitly captured int values, as they're always dispatched over a 2D texture. + bool isComputeShader = shaderInterfaceType == typeof(IComputeShader); + int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); + StrongBox resourceOffsetAsBox = new(); + StrongBox rawDataOffsetAsBox = new(initialRawDataOffset); - // Traverse all shader fields and gather info, and update the tracking offsets - ImmutableArray fieldInfos = GetCapturedFieldInfos( - structDeclarationSymbol, - ImmutableArray.Empty, - resourceOffsetAsBox, - rawDataOffsetAsBox).ToImmutableArray(); + // Traverse all shader fields and gather info, and update the tracking offsets + ImmutableArray fieldInfos = GetCapturedFieldInfos( + structDeclarationSymbol, + ImmutableArray.Empty, + resourceOffsetAsBox, + rawDataOffsetAsBox).ToImmutableArray(); - resourceCount = resourceOffsetAsBox.Value; + resourceCount = resourceOffsetAsBox.Value; - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to a multiple of a 32 bit value. This is necessary to - // enable loading all the dispatch data after reinterpreting it to a sequence of values - // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. - root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to a multiple of a 32 bit value. This is necessary to + // enable loading all the dispatch data after reinterpreting it to a sequence of values + // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. + root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); - // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. - // Loaded values in the root signature have the following costs: - // - Root constants cost 1 DWORD each, since they are 32-bit values. - // - Descriptor tables cost 1 DWORD each. - // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. - // So here we check whether the current signature respects that constraint, - // and emit a build error otherwise. For more info on this, see the docs here: - // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. - int rootSignatureDwordSize = root32BitConstantCount + resourceCount; + // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. + // Loaded values in the root signature have the following costs: + // - Root constants cost 1 DWORD each, since they are 32-bit values. + // - Descriptor tables cost 1 DWORD each. + // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. + // So here we check whether the current signature respects that constraint, + // and emit a build error otherwise. For more info on this, see the docs here: + // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. + int rootSignatureDwordSize = root32BitConstantCount + resourceCount; - if (rootSignatureDwordSize > 64) - { - builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - } - - diagnostics = builder.ToImmutable(); - - return fieldInfos; - } - - /// - /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix). - /// - /// The current path of the field with respect to the shader instance. - /// The type name currently being read. - /// The current offset within the loaded data buffer. - private static FieldInfo GetHlslKnownTypeFieldInfo( - ImmutableArray fieldPath, - string typeName, - ref int rawDataOffset) - { - // For scalar, vector and linear matrix types, serialize the value normally. - // Only the initial alignment needs to be considered, while data is packed. - var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); - - // Check if the current type is a matrix type with more than one row. In this - // case, each row is aligned as if it was a separate array, so the start of - // 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); - - for (int j = 0; j < rows; j++) + if (rootSignatureDwordSize > 64) { - int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - builder.Add(startingRawDataOffset); - - rawDataOffset = startingRawDataOffset + fieldPack * columns; + builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } - return new FieldInfo.NonLinearMatrix( - fieldPath, - typeName, - elementName!, - rows, - columns, - builder.MoveToImmutable()); + diagnostics = builder.ToImmutable(); + + return fieldInfos; } - else + + /// + /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix). + /// + /// The current path of the field with respect to the shader instance. + /// The type name currently being read. + /// The current offset within the loaded data buffer. + private static FieldInfo GetHlslKnownTypeFieldInfo( + ImmutableArray fieldPath, + string typeName, + ref int rawDataOffset) { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer). - // Since we're in a constant buffer, we need to both pad the starting offset - // to be aligned to the packing size of the type, and also to align the initial - // offset to ensure that values do not cross 16 bytes boundaries either. - int startingRawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, fieldPack), - fieldSize, - 16); + // For scalar, vector and linear matrix types, serialize the value normally. + // Only the initial alignment needs to be considered, while data is packed. + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); - rawDataOffset = startingRawDataOffset + fieldSize; + // Check if the current type is a matrix type with more than one row. In this + // case, each row is aligned as if it was a separate array, so the start of + // 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); - return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); + for (int j = 0; j < rows; j++) + { + int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + builder.Add(startingRawDataOffset); + + rawDataOffset = startingRawDataOffset + fieldPack * columns; + } + + return new FieldInfo.NonLinearMatrix( + fieldPath, + typeName, + elementName!, + rows, + columns, + builder.MoveToImmutable()); + } + else + { + // Calculate the right offset with 16-bytes padding (HLSL constant buffer). + // Since we're in a constant buffer, we need to both pad the starting offset + // to be aligned to the packing size of the type, and also to align the initial + // offset to ensure that values do not cross 16 bytes boundaries either. + int startingRawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + rawDataOffset = startingRawDataOffset + fieldSize; + + return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); + } } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index ea70202a..a886d33e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -13,120 +13,124 @@ namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { - /// - /// Creates a instance for the LoadDispatchMetadata method. - /// - /// The dispatch metadata for the current shader.. - /// The resulting instance for the LoadDispatchMetadata method. - private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo) + /// + private static partial class LoadDispatchMetadata { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchMetadata")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TMetadataLoader")), - Parameter(Identifier("result")) - .AddModifiers(Token(SyntaxKind.OutKeyword)) - .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) - .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); - } - - /// - /// Gets a sequence of statements to load the dispatch metadata for a given shader type. - /// - /// The dispatch metadata for the current shader.. - /// The sequence of instances to load shader dispatch data. - private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) - { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - - // global::System.Span span0 = stackalloc byte[5]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); - - // Compute the total number of resources - int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; - - // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); - - // ref byte r0 = ref span0[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // Serialized shader metadata - statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); - statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});")); - - - // Populate the sequence of resource descriptors - foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The dispatch metadata for the current shader.. + /// The resulting instance for the LoadDispatchMetadata method. + public static MethodDeclarationSyntax GetSyntax(DispatchMetadataInfo metadataInfo) { - statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchMetadata")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TMetadataLoader")), + Parameter(Identifier("result")) + .AddModifiers(Token(SyntaxKind.OutKeyword)) + .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) + .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); } - // Invoke the value delegate to create the opaque root signature handle - statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The dispatch metadata for the current shader.. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - return statements.ToImmutable(); + // global::System.Span span0 = stackalloc byte[5]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); + + // Compute the total number of resources + int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; + + // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); + + // ref byte r0 = ref span0[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // Serialized shader metadata + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});")); + + + // Populate the sequence of resource descriptors + foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) + { + statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); + } + + // Invoke the value delegate to create the opaque root signature handle + statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); + + return statements.ToImmutable(); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index a4dc5339..5132b5d0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -8,51 +8,57 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator { /// - /// Gets the data related to the shader metadata for a given shader type. + /// A helper with all logic to generate the LoadDispatchMetadata method. /// - /// The total number of needed 32 bit constants in the shader root signature. - /// Indicates whether the current shader uses an implicit texture. - /// Whether the static sampler is used by the shader. - /// The sequence of captured fields for the shader. - /// The metadata info for the shader. - private static DispatchMetadataInfo GetDispatchMetadataInfo( - int root32BitConstantCount, - bool isImplicitTextureUsed, - bool isSamplerUsed, - ImmutableArray capturedFields) + private static partial class LoadDispatchMetadata { - ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); - int constantBufferOffset = 1; - int readOnlyResourceOffset = 0; - int readWriteResourceOffset = 0; - int resourceOffset = 0; - - // Add the implicit texture descriptor, if needed - if (isImplicitTextureUsed) + /// + /// Gets the data related to the shader metadata for a given shader type. + /// + /// The total number of needed 32 bit constants in the shader root signature. + /// Indicates whether the current shader uses an implicit texture. + /// Whether the static sampler is used by the shader. + /// The sequence of captured fields for the shader. + /// The metadata info for the shader. + public static DispatchMetadataInfo GetInfo( + int root32BitConstantCount, + bool isImplicitTextureUsed, + bool isSamplerUsed, + ImmutableArray capturedFields) { - descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); - } + ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); + int constantBufferOffset = 1; + int readOnlyResourceOffset = 0; + int readWriteResourceOffset = 0; + int resourceOffset = 0; - // Populate the sequence of resource descriptors - foreach (FieldInfo.Resource resource in capturedFields.OfType()) - { - if (HlslKnownTypes.IsConstantBufferType(resource.TypeName)) - { - descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++)); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName)) - { - descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++)); - } - else + // Add the implicit texture descriptor, if needed + if (isImplicitTextureUsed) { descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); } - } - return new( - root32BitConstantCount, - isSamplerUsed, - descriptors.ToImmutable()); + // Populate the sequence of resource descriptors + foreach (FieldInfo.Resource resource in capturedFields.OfType()) + { + if (HlslKnownTypes.IsConstantBufferType(resource.TypeName)) + { + descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++)); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName)) + { + descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++)); + } + else + { + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + } + } + + return new( + root32BitConstantCount, + isSamplerUsed, + descriptors.ToImmutable()); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs index 035239a5..ce084c18 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs @@ -14,174 +14,178 @@ namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { - /// - /// Creates a instance for the TryGetBytecode method. - /// - /// The input instance. - /// An opaque instance to transform the final tree into text. - /// The resulting instance for the BuildHlslString method. - private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) + /// + private static partial class TryGetBytecode { - BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); - - if (bytecodeLiterals is not null) + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input instance. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the BuildHlslString method. + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) { - fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); - } - else - { - fixup = static tree => tree.ToFullString(); - } + BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); - // This code produces a method declaration as follows: - // - // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.BoolKeyword)), - Identifier("TryGetBytecode")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) - .WithBody(block); - } - - /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. - /// - /// The input instance. - /// The resulting bytecode literals to insert into the final source code. - /// The instance trying to retrieve the precompiled shader. - [Pure] - private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) - { - if (bytecodeInfo.Bytecode.IsEmpty) - { - bytecodeLiterals = null; + if (bytecodeLiterals is not null) + { + fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals); + } + else + { + fixup = static tree => tree.ToFullString(); + } // This code produces a method declaration as follows: // - // bytecode = default; - // - // return false; + // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) + // { + // + // } return - Block( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), - ReturnStatement( - LiteralExpression( - SyntaxKind.FalseLiteralExpression))); + MethodDeclaration( + PredefinedType(Token(SyntaxKind.BoolKeyword)), + Identifier("TryGetBytecode")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) + .WithBody(block); } - bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance. + /// The resulting bytecode literals to insert into the final source code. + /// The instance trying to retrieve the precompiled shader. + [Pure] + private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) + { + if (bytecodeInfo.Bytecode.IsEmpty) + { + bytecodeLiterals = null; - // This code produces a method declaration as follows: - // - // if (threadsX == && threadsY == && threadsZ == ) - // { - // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; - // - // return true; - // } - // - // bytecode = default; - // - // return false; - // - // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string - // is created by the generator. This greatly speeds up the code generation, as it avoids - // having to create/parse tens of thousands of literal expression nodes for every shader. - return - Block( - IfStatement( - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsX"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsY"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsZ"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))), + // This code produces a method declaration as follows: + // + // bytecode = default; + // + // return false; + return Block( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName("bytecode"), - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), - ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("bytecode"), - LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), - ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); - } + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement( + LiteralExpression( + SyntaxKind.FalseLiteralExpression))); + } - /// - /// A mapping of precomputed literals for all values. - /// - private static readonly string[] formattedBytes = - { - "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", - "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", - "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", - "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", - "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", - "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", - "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", - "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", - "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", - "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", - "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", - "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", - "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", - "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", - "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", - "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" - }; + bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); - /// - /// Creates a formatted expression to initialize a with a given shader data. - /// - /// The input shader bytecode to serialize. - /// A formatted with the serialized data. - private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) - { - //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values - using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); - - builder.Append(formattedBytes[bytecode[0]]); - - foreach (byte b in bytecode.Slice(1)) - { - builder.Append(", "); - builder.Append(formattedBytes[b]); + // This code produces a method declaration as follows: + // + // if (threadsX == && threadsY == && threadsZ == ) + // { + // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // + // return true; + // } + // + // bytecode = default; + // + // return false; + // + // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string + // is created by the generator. This greatly speeds up the code generation, as it avoids + // having to create/parse tens of thousands of literal expression nodes for every shader. + return + Block( + IfStatement( + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsX"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsY"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsZ"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))), + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), + ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); } - return builder.WrittenSpan.ToString(); + /// + /// A mapping of precomputed literals for all values. + /// + private static readonly string[] formattedBytes = + { + "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F", + "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F", + "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F", + "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F", + "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", + "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F", + "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F", + "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F", + "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F", + "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F", + "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF", + "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF", + "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF", + "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF", + "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF", + "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" + }; + + /// + /// Creates a formatted expression to initialize a with a given shader data. + /// + /// The input shader bytecode to serialize. + /// A formatted with the serialized data. + private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) + { + //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values + using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); + + builder.Append(formattedBytes[bytecode[0]]); + + foreach (byte b in bytecode.Slice(1)) + { + builder.Append(", "); + builder.Append(formattedBytes[b]); + } + + return builder.WrittenSpan.ToString(); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 7be250dd..75231ba7 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -23,196 +23,202 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator { /// - /// Gets the thread ids values for a given shader type, if available. + /// A helper with all logic to generate the TryGetBytecode method. /// - /// The instance for the attribute. - /// The input instance to process. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The resulting diagnostics from the processing operation. - /// The thread ids for the precompiled shader, if available. - private static ThreadIdsInfo GetThreadIdsForEmbeddedShader( - INamedTypeSymbol embeddedBytecodeAttribute, - INamedTypeSymbol structDeclarationSymbol, - bool isDynamicShader, - out ImmutableArray diagnostics) + private static partial class TryGetBytecode { - AttributeData? attribute = structDeclarationSymbol - .GetAttributes() - .FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, embeddedBytecodeAttribute)); - - if (attribute is null) + /// + /// Gets the thread ids values for a given shader type, if available. + /// + /// The instance for the attribute. + /// The input instance to process. + /// Indicates whether or not the shader is dynamic (ie. captures delegates). + /// The resulting diagnostics from the processing operation. + /// The thread ids for the precompiled shader, if available. + public static ThreadIdsInfo GetInfo( + INamedTypeSymbol embeddedBytecodeAttribute, + INamedTypeSymbol structDeclarationSymbol, + bool isDynamicShader, + out ImmutableArray diagnostics) { - diagnostics = ImmutableArray.Empty; + AttributeData? attribute = structDeclarationSymbol + .GetAttributes() + .FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, embeddedBytecodeAttribute)); - return new(true, 0, 0, 0); - } + if (attribute is null) + { + diagnostics = ImmutableArray.Empty; - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + return new(true, 0, 0, 0); + } - // Validate the thread number arguments - if (attribute.ConstructorArguments[0].Value is not int threadsX || - attribute.ConstructorArguments[1].Value is not int threadsY || - attribute.ConstructorArguments[2].Value is not int threadsZ || - threadsX is < 1 or > 1024 || - threadsY is < 1 or > 1024 || - threadsZ is < 1 or > 64) - { - builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // Validate the thread number arguments + if (attribute.ConstructorArguments[0].Value is not int threadsX || + attribute.ConstructorArguments[1].Value is not int threadsY || + attribute.ConstructorArguments[2].Value is not int threadsZ || + threadsX is < 1 or > 1024 || + threadsY is < 1 or > 1024 || + threadsZ is < 1 or > 64) + { + builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); + + diagnostics = builder.ToImmutable(); + + return new(true, 0, 0, 0); + } + + // If the current shader is dynamic, emit a diagnostic error + if (isDynamicShader) + { + builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); + + diagnostics = builder.ToImmutable(); + + return new(true, 0, 0, 0); + } diagnostics = builder.ToImmutable(); - return new(true, 0, 0, 0); + return new(false, threadsX, threadsY, threadsZ); } - // If the current shader is dynamic, emit a diagnostic error - if (isDynamicShader) + /// + /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// + private static bool areDxcLibrariesLoaded; + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance to process. + /// The generated HLSL source code (ignoring captured delegates, if present). + /// The resulting diagnostics from the processing operation. + /// The instance with the compiled shader bytecode. + [Pure] + public static unsafe ImmutableArray GetBytecode( + ThreadIdsInfo threadIds, + string hlslSource, + out ImmutableArray diagnostics) { - builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); + ImmutableArray bytecode = ImmutableArray.Empty; + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - diagnostics = builder.ToImmutable(); - - return new(true, 0, 0, 0); - } - - diagnostics = builder.ToImmutable(); - - return new(false, threadsX, threadsY, threadsZ); - } - - /// - /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. - /// - private static bool areDxcLibrariesLoaded; - - /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. - /// - /// The input instance to process. - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting diagnostics from the processing operation. - /// The instance with the compiled shader bytecode. - [Pure] - private static unsafe ImmutableArray GetShaderBytecode( - ThreadIdsInfo threadIds, - string hlslSource, - out ImmutableArray diagnostics) - { - ImmutableArray bytecode = ImmutableArray.Empty; - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - - // No embedded shader was requested - if (threadIds.IsDefault) - { - goto End; - } - - try - { - // Try to load dxcompiler.dll and dxil.dll - LoadNativeDxcLibraries(); - - // Replace the actual thread num values - hlslSource = hlslSource - .Replace("", threadIds.X.ToString()) - .Replace("", threadIds.Y.ToString()) - .Replace("", threadIds.Z.ToString()); - - // Compile the shader bytecode - using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); - - byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); - int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); - - byte[] array = new ReadOnlySpan(buffer, length).ToArray(); - - bytecode = Unsafe.As>(ref array); - } - catch (Win32Exception) - { - // TODO - //builder.Add( - // EmbeddedBytecodeFailedWithWin32Exception, - // structDeclarationSymbol, - // structDeclarationSymbol, - // e.HResult, - // e.Message); - } - catch (HlslCompilationException) - { - // TODO - //builder.Add( - // EmbeddedBytecodeFailedWithHlslCompilationException, - // structDeclarationSymbol, - // structDeclarationSymbol, - // e.Message); - } - - End: - diagnostics = builder.ToImmutable(); - - return bytecode; - } - - /// - /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. - /// - /// Thrown if the CPU architecture is not supported. - /// Thrown if a library fails to load. - private static void LoadNativeDxcLibraries() - { - // Extracts a specified native library for a given runtime identifier - static string ExtractLibrary(string rid, string name) - { - string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; - string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll"); - - Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); - - using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); + // No embedded shader was requested + if (threadIds.IsDefault) + { + goto End; + } try { - using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write); + // Try to load dxcompiler.dll and dxil.dll + LoadNativeDxcLibraries(); - sourceStream.CopyTo(destinationStream); + // Replace the actual thread num values + hlslSource = hlslSource + .Replace("", threadIds.X.ToString()) + .Replace("", threadIds.Y.ToString()) + .Replace("", threadIds.Z.ToString()); + + // Compile the shader bytecode + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + bytecode = Unsafe.As>(ref array); } - catch (IOException) + catch (Win32Exception) { + // TODO + //builder.Add( + // EmbeddedBytecodeFailedWithWin32Exception, + // structDeclarationSymbol, + // structDeclarationSymbol, + // e.HResult, + // e.Message); + } + catch (HlslCompilationException) + { + // TODO + //builder.Add( + // EmbeddedBytecodeFailedWithHlslCompilationException, + // structDeclarationSymbol, + // structDeclarationSymbol, + // e.Message); } - return targetFilename; + End: + diagnostics = builder.ToImmutable(); + + return bytecode; } - // Loads a target native library - static unsafe void LoadLibrary(string filename) + /// + /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. + /// + /// Thrown if the CPU architecture is not supported. + /// Thrown if a library fails to load. + private static void LoadNativeDxcLibraries() { - [DllImport("kernel32", ExactSpelling = true, SetLastError = true)] - static extern void* LoadLibraryW(ushort* lpLibFileName); - - fixed (char* p = filename) + // Extracts a specified native library for a given runtime identifier + static string ExtractLibrary(string rid, string name) { - if (LoadLibraryW((ushort*)p) is null) - { - int hresult = Marshal.GetLastWin32Error(); + string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; + string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll"); - throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}."); + Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); + + using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); + + try + { + using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write); + + sourceStream.CopyTo(destinationStream); + } + catch (IOException) + { + } + + return targetFilename; + } + + // Loads a target native library + static unsafe void LoadLibrary(string filename) + { + [DllImport("kernel32", ExactSpelling = true, SetLastError = true)] + static extern void* LoadLibraryW(ushort* lpLibFileName); + + fixed (char* p = filename) + { + if (LoadLibraryW((ushort*)p) is null) + { + int hresult = Marshal.GetLastWin32Error(); + + throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}."); + } } } - } - if (!areDxcLibrariesLoaded) - { - string rid = RuntimeInformation.ProcessArchitecture switch + if (!areDxcLibrariesLoaded) { - Architecture.X64 => "x64", - Architecture.Arm64 => "arm64", - _ => throw new NotSupportedException("Invalid process architecture") - }; + string rid = RuntimeInformation.ProcessArchitecture switch + { + Architecture.X64 => "x64", + Architecture.Arm64 => "arm64", + _ => throw new NotSupportedException("Invalid process architecture") + }; - LoadLibrary(ExtractLibrary(rid, "dxil")); - LoadLibrary(ExtractLibrary(rid, "dxcompiler")); + LoadLibrary(ExtractLibrary(rid, "dxil")); + LoadLibrary(ExtractLibrary(rid, "dxcompiler")); + } + + areDxcLibrariesLoaded = true; } - - areDxcLibrariesLoaded = true; } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs new file mode 100644 index 00000000..8435dada --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator +{ + /// + /// Gets the shader type for a given shader, if any. + /// + /// The input instance to check. + /// The instance for . + /// The instance for . + /// Either or , or . + [Pure] + private static Type? GetShaderType( + INamedTypeSymbol typeSymbol, + INamedTypeSymbol iComputeShaderSymbol, + INamedTypeSymbol iPixelShaderSymbol) + { + foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces) + { + if (interfaceSymbol.Name == nameof(IComputeShader) && + SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol)) + { + return typeof(IComputeShader); + } + + if (interfaceSymbol.IsGenericType && + interfaceSymbol.Name == nameof(IPixelShader) && + SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol)) + { + return typeof(IPixelShader<>); + } + } + + return null; + } + + /// + /// Creates a instance wrapping the given method. + /// + /// The instance for the current type. + /// The item to insert. + /// Whether [SkipLocalsInit] can be used. + /// A object wrapping . + [Pure] + private static CompilationUnitSyntax GetCompilationUnitFromMethod( + HierarchyInfo hierarchyInfo, + MethodDeclarationSyntax methodDeclaration, + bool canUseSkipLocalsInit) + { + // Method attributes + List attributes = new() + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code")))))) + }; + + // Add [SkipLocalsInit] if the target project allows it + if (canUseSkipLocalsInit) + { + attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); + } + + // Create the partial shader type declaration with the given method implementation. + // This code produces a struct declaration as follows: + // + // partial struct + // { + // + // } + StructDeclarationSyntax structDeclarationSyntax = + StructDeclaration(hierarchyInfo.Names[0]) + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray())); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) + { + typeDeclarationSyntax = + ClassDeclaration(parentType) + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(typeDeclarationSyntax); + } + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // #pragma warning disable + // + // namespace ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 25868a19..ebcf35b2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Diagnostics; @@ -11,7 +10,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; @@ -61,13 +59,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Get the hierarchy info and delegate field names for each shader type IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo Info)> hierarchyAndDispatchIdInfo = shaderDeclarations - .Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDelegateFieldNames(item.Symbol)))) + .Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDispatchId.GetInfo(item.Symbol)))) .WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default); // Generate the GetDispatchId() methods context.RegisterSourceOutput(hierarchyAndDispatchIdInfo, static (context, item) => { - MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Info.Delegates); + MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.Info.Delegates); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, false); context.AddSource($"{item.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); @@ -86,8 +84,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator .Combine(embeddedBytecodeSymbol) .Select(static (item, token) => { - // GetDispatchId() data - ImmutableArray fieldInfos = GetCapturedFieldInfos( + // LoadDispatchData() info + ImmutableArray fieldInfos = LoadDispatchData.GetInfo( item.Left.Left.Symbol, item.Left.Left.Type, out int resourceCount, @@ -103,14 +101,14 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator dispatchDataDiagnostics); // BuildHlslString() info - HlslSourceInfo hlslSourceInfo = GetNonDynamicHlslSourceInfo( + HlslSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( item.Left.Right, item.Left.Left.Syntax, item.Left.Left.Symbol, out ImmutableArray hlslSourceDiagnostics); // TryGetBytecode() info - ThreadIdsInfo threadIds = GetThreadIdsForEmbeddedShader( + ThreadIdsInfo threadIds = TryGetBytecode.GetInfo( item.Right, item.Left.Left.Symbol, !hlslSourceInfo.Delegates.IsEmpty, @@ -142,7 +140,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Generate the LoadDispatchData() methods context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod( + MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax( item.Left.Type, item.Left.FieldInfos, item.Left.ResourceCount, @@ -161,7 +159,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Generate the BuildHlslString() methods context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(item.Left.SourceInfo); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslString.GetSyntax(item.Left.SourceInfo); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); @@ -172,7 +170,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator shaderInfo .Select(static (item, token) => ( item.Dispatch.Hierarchy, - GetDispatchMetadataInfo( + LoadDispatchMetadata.GetInfo( item.Dispatch.Root32BitConstantCount, item.Hlsl.ImplicitTextureType is not null, item.Hlsl.IsSamplerUsed, @@ -182,7 +180,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Generate the LoadDispatchMetadata() methods context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = CreateLoadDispatchMetadataMethod(item.Left.MetadataInfo); + MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Left.MetadataInfo); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); @@ -191,7 +189,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Transform the raw HLSL source to compile IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = shaderInfo - .Select(static (item, token) => (item.Dispatch.Hierarchy, GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)) + .Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslString.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds)) .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, ThreadIdsInfo.Comparer.Default); // Compile the requested shader bytecodes @@ -199,7 +197,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator shaderBytecodeInfo .Select(static (item, token) => { - ImmutableArray bytecode = GetShaderBytecode(item.ThreadIds, item.Hlsl, out ImmutableArray diagnostics); + ImmutableArray bytecode = TryGetBytecode.GetBytecode(item.ThreadIds, item.Hlsl, out ImmutableArray diagnostics); EmbeddedBytecodeInfo bytecodeInfo = new( item.ThreadIds.X, @@ -222,123 +220,11 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Generate the TryGetBytecode() methods context.RegisterSourceOutput(embeddedBytecode, static (context, item) => { - MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(item.BytecodeInfo, out Func fixup); + MethodDeclarationSyntax tryGetBytecodeMethod = TryGetBytecode.GetSyntax(item.BytecodeInfo, out Func fixup); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, false); string text = fixup(compilationUnit); context.AddSource($"{item.Hierarchy.FilenameHint}.TryGetBytecode", SourceText.From(text, Encoding.UTF8)); }); } - - /// - /// Gets the shader type for a given shader, if any. - /// - /// The input instance to check. - /// The instance for . - /// The instance for . - /// Either or , or . - [Pure] - private static Type? GetShaderType( - INamedTypeSymbol typeSymbol, - INamedTypeSymbol iComputeShaderSymbol, - INamedTypeSymbol iPixelShaderSymbol) - { - foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces) - { - if (interfaceSymbol.Name == nameof(IComputeShader) && - SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol)) - { - return typeof(IComputeShader); - } - - if (interfaceSymbol.IsGenericType && - interfaceSymbol.Name == nameof(IPixelShader) && - SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol)) - { - return typeof(IPixelShader<>); - } - } - - return null; - } - - /// - /// Creates a instance wrapping the given method. - /// - /// The instance for the current type. - /// The item to insert. - /// Whether [SkipLocalsInit] can be used. - /// A object wrapping . - [Pure] - private static CompilationUnitSyntax GetCompilationUnitFromMethod( - HierarchyInfo hierarchyInfo, - MethodDeclarationSyntax methodDeclaration, - bool canUseSkipLocalsInit) - { - // Method attributes - List attributes = new() - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - // Add [SkipLocalsInit] if the target project allows it - if (canUseSkipLocalsInit) - { - attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); - } - - // Create the partial shader type declaration with the given method implementation. - // This code produces a struct declaration as follows: - // - // partial struct - // { - // - // } - StructDeclarationSyntax structDeclarationSyntax = - StructDeclaration(hierarchyInfo.Names[0]) - .AddModifiers(Token(SyntaxKind.PartialKeyword)) - .AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray())); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) - { - typeDeclarationSyntax = - ClassDeclaration(parentType) - .AddModifiers(Token(SyntaxKind.PartialKeyword)) - .AddMembers(typeDeclarationSyntax); - } - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // #pragma warning disable - // - // namespace ; - // - // - return - CompilationUnit().AddMembers( - FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) - .AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList( - Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), - SyntaxKind.NamespaceKeyword, - TriviaList()))) - .NormalizeWhitespace(eol: "\n"); - } } diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 374f9478..53af0970 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -69,8 +69,8 @@ public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator // Explore the syntax tree and extract the processed info var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - var processedTypes = IShaderGenerator.GetDeclaredTypes(discoveredTypes); - var processedConstants = IShaderGenerator.GetDefinedConstants(constantDefinitions); + var processedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes); + var processedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = From fcbe997d783896a77cf88e6505651925274be5c0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 00:40:42 +0100 Subject: [PATCH 22/36] Fix source generator unit tests --- .../DiagnosticsTests.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 0092a1ae..1943477d 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -1410,12 +1410,15 @@ public class DiagnosticsTests { public interface IComputeShader { } public class ReadWriteBuffer { } - public class EmbeddedBytecodeAttribute : Attribute { } + public class EmbeddedBytecodeAttribute : Attribute + { + public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ) { } + } } namespace MyFancyApp.Sample { - [EmbeddedBytecode] + [EmbeddedBytecode(8, 8, 1)] public struct MyShader : IComputeShader { public ReadWriteBuffer buffer; @@ -1476,7 +1479,7 @@ public class DiagnosticsTests /// The input source to process. /// The expected diagnostics ids to be generated. private static void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds) - where TGenerator : class, ISourceGenerator, new() + where TGenerator : class, IIncrementalGenerator, new() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); @@ -1488,7 +1491,7 @@ public class DiagnosticsTests CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); - ISourceGenerator generator = new TGenerator(); + IIncrementalGenerator generator = new TGenerator(); CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator); From 5c5c3439cb360bccbe77beceecf878d5ebd719b5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 00:46:18 +0100 Subject: [PATCH 23/36] Remove non-incremental source rewriters --- ...erGenerator.CreateBuildHlslStringMethod.cs | 8 +- .../ShaderMethodSourceGenerator.cs | 9 +- .../ExecuteMethodRewriter.Incremental.cs | 191 -------- .../HlslSourceRewriter.Diagnostics.cs | 48 +- ...lSourceRewriter.Incremental.Diagnostics.cs | 205 -------- .../HlslSourceRewriter.Incremental.cs | 342 -------------- .../SyntaxRewriters/HlslSourceRewriter.cs | 21 +- .../ShaderSourceRewriter.Incremental.cs | 443 ------------------ .../SyntaxRewriters/ShaderSourceRewriter.cs | 27 +- .../StaticFieldRewriter.Incremental.cs | 134 ------ .../SyntaxRewriters/StaticFieldRewriter.cs | 9 +- 11 files changed, 66 insertions(+), 1371 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs delete mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs delete mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs delete mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs delete mode 100644 src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 3f791bdd..a7189020 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -239,7 +239,7 @@ public sealed partial class IShaderGenerator false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" }; - StaticFieldRewriter2 staticFieldRewriter = new( + StaticFieldRewriter staticFieldRewriter = new( semanticModel, discoveredTypes, constantDefinitions, @@ -360,7 +360,7 @@ public sealed partial class IShaderGenerator methodDeclarationSymbol.Parameters.Length == 0); // Create the source rewriter for the current method - ShaderSourceRewriter2 shaderSourceRewriter = new( + ShaderSourceRewriter shaderSourceRewriter = new( structDeclarationSymbol, semanticModel, discoveredTypes, @@ -388,8 +388,8 @@ public sealed partial class IShaderGenerator { processedMethod = isComputeShader switch { - true => new ExecuteMethodRewriter2.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter2.Pixel(shaderSourceRewriter).Visit(processedMethod)! + true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! }; entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 53af0970..4d569fa0 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Text; using ComputeSharp.__Internals; @@ -109,8 +110,14 @@ public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator IDictionary constantDefinitions) { Dictionary staticMethods = new(SymbolEqualityComparer.Default); + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics); + + foreach (Diagnostic diagnostic in diagnostics.ToImmutable()) + { + context.ReportDiagnostic(diagnostic); + } // Rewrite the method syntax tree var targetMethod = shaderSourceRewriter diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs deleted file mode 100644 index 7e1f3d36..00000000 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.Incremental.cs +++ /dev/null @@ -1,191 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; - -/// -/// A custom type that does postprocessing fixups on the shader main method. -/// -internal abstract class ExecuteMethodRewriter2 : CSharpSyntaxRewriter -{ - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance used to process the input tree. - public ExecuteMethodRewriter2(ShaderSourceRewriter2 shaderSourceRewriter) - { - ShaderSourceRewriter2 = shaderSourceRewriter; - } - - /// - /// Gets the instance used to process the input tree. - /// - protected ShaderSourceRewriter2 ShaderSourceRewriter2 { get; } - - /// - public TNode? Visit(TNode? node) - where TNode : SyntaxNode - { - return (TNode?)base.Visit(node); - } - - /// - public override SyntaxNode? VisitParameterList(ParameterListSyntax node) - { - var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!; - - updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID"))); - - if (ShaderSourceRewriter2.IsGroupIdsUsed) - { - updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID"))); - } - - if (ShaderSourceRewriter2.IsGroupIdsIndexUsed) - { - updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex"))); - } - - if (ShaderSourceRewriter2.IsGridIdsUsed) - { - updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GridIds)} : SV_GroupID"))); - } - - return updatedNode; - } - - /// - /// A custom type specialized for compute shaders. - /// - public sealed class Compute : ExecuteMethodRewriter2 - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance used to process the input tree. - public Compute(ShaderSourceRewriter2 shaderSourceRewriter) - : base(shaderSourceRewriter) - { - } - - /// - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) - { - var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); - - // When we're rewriting the main compute shader method, we need to insert a range - // check to ensure that invocation outside of the requested range are discarded. - // The following snippet creates this prologue before the user provided body: - // - // if (ThreadIds.x < __x && - // ThreadIds.y < __y && - // ThreadIds.z < __z) - // { - // - // } - BinaryExpressionSyntax rangeCheckExpression = - BinaryExpression(SyntaxKind.LogicalAndExpression, - BinaryExpression(SyntaxKind.LogicalAndExpression, - BinaryExpression(SyntaxKind.LessThanExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ThreadIds)), - IdentifierName("x")), - IdentifierName("__x")), - BinaryExpression(SyntaxKind.LessThanExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ThreadIds)), - IdentifierName("y")), - IdentifierName("__y"))), - BinaryExpression(SyntaxKind.LessThanExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ThreadIds)), - IdentifierName("z")), - IdentifierName("__z"))); - - return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); - } - } - - /// - /// A custom type specialized for compute shaders. - /// - public sealed class Pixel : ExecuteMethodRewriter2 - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance used to process the input tree. - public Pixel(ShaderSourceRewriter2 shaderSourceRewriter) - : base(shaderSourceRewriter) - { - } - - /// - public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node) - { - var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!; - - // __outputTexture[ThreadIds.xy] = ; - return - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("__outputTexture")) - .AddArgumentListArguments( - Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ThreadIds"), - IdentifierName("xy")))), - updatedNode.Expression!)); - } - - /// - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) - { - var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); - - // Change the return type to void - updatedNode = updatedNode.WithReturnType(PredefinedType(Token(SyntaxKind.VoidKeyword))); - - // Same as above, but skipping the third check for the Z axis. - // This is because pixel shaders only ever run on 2D textures. - BinaryExpressionSyntax rangeCheckExpression = - BinaryExpression(SyntaxKind.LogicalAndExpression, - BinaryExpression(SyntaxKind.LessThanExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ThreadIds)), - IdentifierName("x")), - IdentifierName("__x")), - BinaryExpression(SyntaxKind.LessThanExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ThreadIds)), - IdentifierName("y")), - IdentifierName("__y"))); - - return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); - } - - /// - public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) - { - IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - - // Since pixel shaders are only ever executed on 2D textures, the special __z field can - // be removed and replaced with just numeric literal expressions, where the value is 1. - if (updatedNode.Identifier.Text == "__z") - { - return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)); - } - - return updatedNode; - } - } -} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index ea074239..ca805ce7 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -14,7 +14,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; - Context.ReportDiagnostic(AnonymousObjectCreationExpression, node); + Diagnostics.Add(AnonymousObjectCreationExpression, node); return updatedNode; } @@ -22,7 +22,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) { - Context.ReportDiagnostic(AwaitExpression, node); + Diagnostics.Add(AwaitExpression, node); return base.VisitAwaitExpression(node); } @@ -30,7 +30,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) { - Context.ReportDiagnostic(CheckedExpression, node); + Diagnostics.Add(CheckedExpression, node); return base.VisitCheckedExpression(node); } @@ -38,7 +38,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) { - Context.ReportDiagnostic(CheckedStatement, node); + Diagnostics.Add(CheckedStatement, node); return base.VisitCheckedStatement(node); } @@ -46,7 +46,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) { - Context.ReportDiagnostic(FixedStatement, node); + Diagnostics.Add(FixedStatement, node); return base.VisitFixedStatement(node); } @@ -54,7 +54,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) { - Context.ReportDiagnostic(ForEachStatement, node); + Diagnostics.Add(ForEachStatement, node); return base.VisitForEachStatement(node); } @@ -62,7 +62,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) { - Context.ReportDiagnostic(ForEachStatement, node); + Diagnostics.Add(ForEachStatement, node); return base.VisitForEachVariableStatement(node); } @@ -70,7 +70,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) { - Context.ReportDiagnostic(LockStatement, node); + Diagnostics.Add(LockStatement, node); return base.VisitLockStatement(node); } @@ -78,7 +78,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) { - Context.ReportDiagnostic(QueryExpression, node); + Diagnostics.Add(QueryExpression, node); return base.VisitQueryExpression(node); } @@ -86,7 +86,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) { - Context.ReportDiagnostic(RangeExpression, node); + Diagnostics.Add(RangeExpression, node); return base.VisitRangeExpression(node); } @@ -94,7 +94,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) { - Context.ReportDiagnostic(RecursivePattern, node); + Diagnostics.Add(RecursivePattern, node); return base.VisitRecursivePattern(node); } @@ -102,7 +102,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitRefType(RefTypeSyntax node) { - Context.ReportDiagnostic(RefType, node); + Diagnostics.Add(RefType, node); return base.VisitRefType(node); } @@ -110,7 +110,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) { - Context.ReportDiagnostic(RelationalPattern, node); + Diagnostics.Add(RelationalPattern, node); return base.VisitRelationalPattern(node); } @@ -118,7 +118,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) { - Context.ReportDiagnostic(SizeOfExpression, node); + Diagnostics.Add(SizeOfExpression, node); return base.VisitSizeOfExpression(node); } @@ -126,7 +126,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) { - Context.ReportDiagnostic(StackAllocArrayCreationExpression, node); + Diagnostics.Add(StackAllocArrayCreationExpression, node); return base.VisitStackAllocArrayCreationExpression(node); } @@ -134,7 +134,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) { - Context.ReportDiagnostic(ThrowExpressionOrStatement, node); + Diagnostics.Add(ThrowExpressionOrStatement, node); return base.VisitThrowExpression(node); } @@ -142,7 +142,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) { - Context.ReportDiagnostic(ThrowExpressionOrStatement, node); + Diagnostics.Add(ThrowExpressionOrStatement, node); return base.VisitThrowStatement(node); } @@ -150,7 +150,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) { - Context.ReportDiagnostic(TryStatement, node); + Diagnostics.Add(TryStatement, node); return base.VisitTryStatement(node); } @@ -158,7 +158,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) { - Context.ReportDiagnostic(TupleType, node); + Diagnostics.Add(TupleType, node); return base.VisitTupleType(node); } @@ -166,7 +166,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) { - Context.ReportDiagnostic(UsingStatementOrDeclaration, node); + Diagnostics.Add(UsingStatementOrDeclaration, node); return base.VisitUsingStatement(node); } @@ -174,7 +174,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) { - Context.ReportDiagnostic(YieldStatement, node); + Diagnostics.Add(YieldStatement, node); return base.VisitYieldStatement(node); } @@ -182,7 +182,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) { - Context.ReportDiagnostic(FunctionPointer, node); + Diagnostics.Add(FunctionPointer, node); return base.VisitFunctionPointerType(node); } @@ -190,7 +190,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) { - Context.ReportDiagnostic(PointerType, node); + Diagnostics.Add(PointerType, node); return base.VisitPointerType(node); } @@ -198,7 +198,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) { - Context.ReportDiagnostic(UnsafeStatement, node); + Diagnostics.Add(UnsafeStatement, node); return base.VisitUnsafeStatement(node); } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs deleted file mode 100644 index c2aecf1d..00000000 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.Diagnostics.cs +++ /dev/null @@ -1,205 +0,0 @@ -using ComputeSharp.SourceGenerators.Diagnostics; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; - -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; - -/// -internal abstract partial class HlslSourceRewriter2 : CSharpSyntaxRewriter -{ - /// - public override SyntaxNode? VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) - { - var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!; - - Diagnostics.Add(AnonymousObjectCreationExpression, node); - - return updatedNode; - } - - /// - public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node) - { - Diagnostics.Add(AwaitExpression, node); - - return base.VisitAwaitExpression(node); - } - - /// - public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node) - { - Diagnostics.Add(CheckedExpression, node); - - return base.VisitCheckedExpression(node); - } - - /// - public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node) - { - Diagnostics.Add(CheckedStatement, node); - - return base.VisitCheckedStatement(node); - } - - /// - public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node) - { - Diagnostics.Add(FixedStatement, node); - - return base.VisitFixedStatement(node); - } - - /// - public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node) - { - Diagnostics.Add(ForEachStatement, node); - - return base.VisitForEachStatement(node); - } - - /// - public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node) - { - Diagnostics.Add(ForEachStatement, node); - - return base.VisitForEachVariableStatement(node); - } - - /// - public override SyntaxNode? VisitLockStatement(LockStatementSyntax node) - { - Diagnostics.Add(LockStatement, node); - - return base.VisitLockStatement(node); - } - - /// - public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node) - { - Diagnostics.Add(QueryExpression, node); - - return base.VisitQueryExpression(node); - } - - /// - public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node) - { - Diagnostics.Add(RangeExpression, node); - - return base.VisitRangeExpression(node); - } - - /// - public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node) - { - Diagnostics.Add(RecursivePattern, node); - - return base.VisitRecursivePattern(node); - } - - /// - public override SyntaxNode? VisitRefType(RefTypeSyntax node) - { - Diagnostics.Add(RefType, node); - - return base.VisitRefType(node); - } - - /// - public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node) - { - Diagnostics.Add(RelationalPattern, node); - - return base.VisitRelationalPattern(node); - } - - /// - public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node) - { - Diagnostics.Add(SizeOfExpression, node); - - return base.VisitSizeOfExpression(node); - } - - /// - public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node) - { - Diagnostics.Add(StackAllocArrayCreationExpression, node); - - return base.VisitStackAllocArrayCreationExpression(node); - } - - /// - public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node) - { - Diagnostics.Add(ThrowExpressionOrStatement, node); - - return base.VisitThrowExpression(node); - } - - /// - public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node) - { - Diagnostics.Add(ThrowExpressionOrStatement, node); - - return base.VisitThrowStatement(node); - } - - /// - public override SyntaxNode? VisitTryStatement(TryStatementSyntax node) - { - Diagnostics.Add(TryStatement, node); - - return base.VisitTryStatement(node); - } - - /// - public override SyntaxNode? VisitTupleType(TupleTypeSyntax node) - { - Diagnostics.Add(TupleType, node); - - return base.VisitTupleType(node); - } - - /// - public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node) - { - Diagnostics.Add(UsingStatementOrDeclaration, node); - - return base.VisitUsingStatement(node); - } - - /// - public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) - { - Diagnostics.Add(YieldStatement, node); - - return base.VisitYieldStatement(node); - } - - /// - public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node) - { - Diagnostics.Add(FunctionPointer, node); - - return base.VisitFunctionPointerType(node); - } - - /// - public override SyntaxNode? VisitPointerType(PointerTypeSyntax node) - { - Diagnostics.Add(PointerType, node); - - return base.VisitPointerType(node); - } - - /// - public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) - { - Diagnostics.Add(UnsafeStatement, node); - - return base.VisitUnsafeStatement(node); - } -} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs deleted file mode 100644 index 16abb6d8..00000000 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Incremental.cs +++ /dev/null @@ -1,342 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using System.Linq; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Operations; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; - -/// -/// A base type that processes C# source to convert to HLSL compliant code. -/// This class contains only the shared logic for all derived HLSL source rewriters. -/// -internal abstract partial class HlslSourceRewriter2 : CSharpSyntaxRewriter -{ - /// - /// The instance with semantic info on the target syntax tree. - /// - protected readonly SemanticModelProvider SemanticModel; - - /// - /// The collection of discovered custom types. - /// - protected readonly ICollection DiscoveredTypes; - - /// - /// The collection of discovered constant definitions. - /// - protected readonly IDictionary ConstantDefinitions; - - /// - /// The collection of produced instances. - /// - protected readonly ImmutableArray.Builder Diagnostics; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - protected HlslSourceRewriter2( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - { - SemanticModel = semanticModel; - DiscoveredTypes = discoveredTypes; - ConstantDefinitions = constantDefinitions; - Diagnostics = diagnostics; - } - - /// - /// Gets whether or not the shader uses a texture sampler at least once. - /// - public bool IsSamplerUsed { get; private set; } - - /// - public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) - { - var updatedNode = (CastExpressionSyntax)base.VisitCastExpression(node)!; - - return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - } - - /// - public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) - { - var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; - - if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) - { - Diagnostics.Add(InvalidObjectDeclaration, node, type); - } - - // If var is used, replace it with the explicit type - if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) - { - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - } - - return updatedNode; - } - - /// - public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) - { - var updatedNode = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node)!; - - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) - { - Diagnostics.Add(InvalidObjectCreationExpression, node, type); - } - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); - - // New objects use the default HLSL cast syntax, eg. (float4)0 - if (updatedNode.ArgumentList!.Arguments.Count == 0) - { - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - // Add explicit casts for matrix constructors to help the overload resolution - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) - { - for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) - { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; - INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; - - updatedNode = updatedNode.ReplaceNode( - updatedNode.ArgumentList!.Arguments[i].Expression, - CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); - } - } - - return InvocationExpression(updatedNode.Type, updatedNode.ArgumentList!); - } - - /// - public override SyntaxNode VisitImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node) - { - var updatedNode = (ImplicitObjectCreationExpressionSyntax)base.VisitImplicitObjectCreationExpression(node)!; - - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) - { - Diagnostics.Add(InvalidObjectCreationExpression, node, type); - } - - TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); - - // Mutate the syntax like with explicit object creation expressions - if (updatedNode.ArgumentList!.Arguments.Count == 0) - { - return CastExpression(explicitType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - // Add explicit casts like with the explicit object creation expressions above - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullMetadataName())) - { - for (int i = 0; i < node.ArgumentList.Arguments.Count; i++) - { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; - INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; - - updatedNode = updatedNode.ReplaceNode( - updatedNode.ArgumentList.Arguments[i].Expression, - CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); - } - } - - return InvocationExpression(explicitType, updatedNode.ArgumentList); - } - - /// - public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) - { - var updatedNode = (DefaultExpressionSyntax)base.VisitDefaultExpression(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - - // A default expression becomes (T)0 in HLSL - return CastExpression(updatedNode.Type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - - /// - public override SyntaxNode? VisitLiteralExpression(LiteralExpressionSyntax node) - { - var updatedNode = (LiteralExpressionSyntax)base.VisitLiteralExpression(node)!; - - if (updatedNode.IsKind(SyntaxKind.DefaultLiteralExpression)) - { - TypeSyntax type = node.TrackType(SemanticModel.For(node), DiscoveredTypes); - - // Same HLSL-style expression in the form (T)0 - return CastExpression(type, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); - } - else if (updatedNode.IsKind(SyntaxKind.NumericLiteralExpression) && - SemanticModel.For(node).GetOperation(node) is ILiteralOperation operation && - operation.Type is INamedTypeSymbol type) - { - // If the expression is a literal floating point value, we need to ensure the proper suffixes are - // used in the HLSL representation. Floating point values accept either f or F, but they don't work - // when the literal doesn't contain a decimal point. Since 32 bit floating point values are the default - // in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix. - if (type.GetFullMetadataName().Equals(typeof(float).FullName)) - { - string literal = updatedNode.Token.ValueText; - - // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix - if (literal.IndexOfAny(new[] { '.', 'E' }) == -1) - { - literal += ".0"; - } - - return updatedNode.WithToken(Literal(literal, 0f)); - } - else if (type.GetFullMetadataName().Equals(typeof(double).FullName)) - { - return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d)); - } - } - else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) - { - Diagnostics.Add(StringLiteralExpression, node); - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitElementAccessExpression(ElementAccessExpressionSyntax node) - { - var updatedNode = (ElementAccessExpressionSyntax)base.VisitElementAccessExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IPropertyReferenceOperation operation) - { - string propertyName = operation.Property.GetFullMetadataName(); - - // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. - // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. - if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) - { - var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); - - return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); - } - - // Rewrite texture resource sampled accesses, if needed - if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) - { - IsSamplerUsed = true; - - // Get the syntax for the argument syntax transformation as described above - ArgumentSyntax coordinateSyntax = mapping switch - { - not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), - null => updatedNode.ArgumentList.Arguments[0] - }; - - // Transform an indexer syntax into a sampling call with the implicit static linear sampler. - // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). - return - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - updatedNode.Expression, - IdentifierName("SampleLevel"))) - .AddArgumentListArguments( - Argument(IdentifierName("__sampler")), - coordinateSyntax, - Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); - } - - // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite - // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. - if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName)) - { - bool isValid = true; - - // Validate the arguments - foreach (ArgumentSyntax argument in node.ArgumentList.Arguments) - { - if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || - !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) - { - Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); - - isValid = false; - } - } - - if (isValid) - { - // Rewrite the indexer as a property access - string hlslPropertyName = string.Join("", - from argument in node.ArgumentList.Arguments - let fieldReference = (IFieldReferenceOperation)SemanticModel.For(node).GetOperation(argument.Expression)! - let fieldName = fieldReference.Field.Name - let row = (char)(fieldName[1] - 1) - let column = (char)(fieldName[2] - 1) - select $"_m{row}{column}"); - - return MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - updatedNode.Expression, - IdentifierName(hlslPropertyName)); - } - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) - { - var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && - operation.Field.IsConst && - operation.Type!.TypeKind != TypeKind.Enum) - { - ConstantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; - - return IdentifierName(constantName); - } - - return updatedNode; - } - - /// - public override SyntaxToken VisitToken(SyntaxToken token) - { - SyntaxToken updatedToken = base.VisitToken(token); - - // Replace all identifier tokens when needed, to avoid colliding with HLSL keywords - if (updatedToken.IsKind(SyntaxKind.IdentifierToken) && - HlslKnownKeywords.TryGetMappedName(updatedToken.Text, out string? mapped)) - { - return ParseToken(mapped!); - } - - return updatedToken.WithoutTrivia(); - } -} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 607f53b9..59ab4edf 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGenerators.Diagnostics; @@ -37,9 +38,9 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter protected readonly IDictionary ConstantDefinitions; /// - /// The current generator context in use. + /// The collection of produced instances. /// - protected readonly GeneratorExecutionContext Context; + protected readonly ImmutableArray.Builder Diagnostics; /// /// Creates a new instance with the specified parameters. @@ -47,17 +48,17 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. protected HlslSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - GeneratorExecutionContext context) + ImmutableArray.Builder diagnostics) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; ConstantDefinitions = constantDefinitions; - Context = context; + Diagnostics = diagnostics; } /// @@ -80,7 +81,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) { - Context.ReportDiagnostic(InvalidObjectDeclaration, node, type); + Diagnostics.Add(InvalidObjectDeclaration, node, type); } // If var is used, replace it with the explicit type @@ -99,7 +100,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) { - Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type); + Diagnostics.Add(InvalidObjectCreationExpression, node, type); } updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes); @@ -135,7 +136,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) { - Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type); + Diagnostics.Add(InvalidObjectCreationExpression, node, type); } TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes); @@ -214,7 +215,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter } else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression)) { - Context.ReportDiagnostic(StringLiteralExpression, node); + Diagnostics.Add(StringLiteralExpression, node); } return updatedNode; @@ -276,7 +277,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference || !HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName())) { - Context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument); + Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument); isValid = false; } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs deleted file mode 100644 index 1f1ef0d7..00000000 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.Incremental.cs +++ /dev/null @@ -1,443 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using System.Linq; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Operations; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; - -/// -/// A custom type that processes C# methods to convert to HLSL compliant code. -/// -internal sealed class ShaderSourceRewriter2 : HlslSourceRewriter2 -{ - /// - /// The type symbol for the shader type. - /// - private readonly INamedTypeSymbol? shaderType; - - /// - /// The collection of discovered static methods. - /// - private readonly IDictionary staticMethods; - - /// - /// The collection of processed local functions in the current tree. - /// - private readonly Dictionary localFunctions; - - /// - /// The list of implicit variables to declare at the start of the body. - /// - private readonly List implicitVariables; - - /// - /// Whether or not the current instance is processing a shader entry point. - /// - private readonly bool isEntryPoint; - - /// - /// The current tree being visited. - /// - private MethodDeclarationSyntax? currentMethod; - - /// - /// The current depth inside local declarations. - /// - private int localFunctionDepth; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The type symbol for the shader type. - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - /// Whether or not the current instance is processing a shader entry point. - public ShaderSourceRewriter2( - INamedTypeSymbol shaderType, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics, - bool isEntryPoint) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - this.shaderType = shaderType; - this.staticMethods = staticMethods; - this.localFunctions = new(); - this.implicitVariables = new(); - this.isEntryPoint = isEntryPoint; - } - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - public ShaderSourceRewriter2( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - this.staticMethods = staticMethods; - this.implicitVariables = new(); - this.localFunctions = new(); - } - - /// - /// Gets the collection of processed local functions in the current tree. - /// - public IReadOnlyDictionary LocalFunctions => this.localFunctions; - - /// - /// Gets whether or not the shader uses at least once (except ). - /// - public bool IsGroupIdsUsed { get; private set; } - - /// - /// Gets whether or not the shader uses at least once. - /// - public bool IsGroupIdsIndexUsed { get; private set; } - - /// - /// Gets whether or not the shader uses at least once. - /// - public bool IsGridIdsUsed { get; set; } - - /// - public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) - { - this.currentMethod = node; - - var updatedNode = (MethodDeclarationSyntax?)base.Visit(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); - - if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) - { - Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); - } - - if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) - { - Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); - } - - if (updatedNode is not null) - { - var implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); - - // Add the tracked implicit declarations (at the start of the body) - updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements(updatedNode.Body!.Statements.ToArray()); - } - - return updatedNode; - } - - /// - public override SyntaxNode VisitParameter(ParameterSyntax node) - { - var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; - - // Convert the C# parameter modifiers to the HLSL equivalent - SyntaxToken modifier = - node.Modifiers - .Where(static m => m.Kind() is SyntaxKind.OutKeyword or SyntaxKind.RefKeyword or SyntaxKind.InKeyword) - .Select(static m => m.Kind() switch - { - SyntaxKind.OutKeyword => m, - SyntaxKind.InKeyword => m, - SyntaxKind.RefKeyword => ParseToken("inout"), - _ => Token(SyntaxKind.None) - }).FirstOrDefault(); - - return updatedNode - .WithAttributeLists(default) - .ReplaceAndTrackType(updatedNode.Type!, node.Type!, SemanticModel.For(node), DiscoveredTypes) - .WithModifiers(TokenList(modifier)); - } - - /// - public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) - { - var updatedNode = ((LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node)!); - - if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) - { - Diagnostics.Add(UsingStatementOrDeclaration, node); - } - - return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); - } - - /// - public override SyntaxNode? VisitDeclarationExpression(DeclarationExpressionSyntax node) - { - var updatedNode = (DeclarationExpressionSyntax)base.VisitDeclarationExpression(node)!; - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); - - // Add the variable to the list of implicit declarations - this.implicitVariables.Add(VariableDeclaration(updatedNode.Type).AddVariables(VariableDeclarator(updatedNode.Designation.ToString()))); - - return IdentifierName(updatedNode.Designation.ToString()); - } - - /// - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) - { - return - ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) - .WithBlockBody() - .WithoutAccessibilityModifiers() - .WithAttributeLists(List()); - } - - /// - public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - this.localFunctionDepth++; - - var updatedNode = - ((LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!) - .WithBlockBody() - .WithAttributeLists(List()) - .WithIdentifier(Identifier($"__{this.currentMethod!.Identifier.Text}__{node.Identifier.Text}")); - - updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.ReturnType, node!.ReturnType, SemanticModel.For(node), DiscoveredTypes); - - if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) - { - Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); - } - - if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) - { - Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); - } - - this.localFunctionDepth--; - - // HLSL doesn't support local functions, so we first process them as usual and then remove - // them from the current syntax tree completely. These will be added to the shader source - // as external static method with a special name to avoid conflicts with other methods. - // The name will simply be in the format: "____". - this.localFunctions.Add(updatedNode.Identifier.Text, updatedNode); - - return null; - } - - /// - public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) - { - var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; - - if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) - { - // If the member access is a constant, track it and replace the tree with the processed constant name - if (operation is IFieldReferenceOperation fieldOperation && - fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) - { - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; - - return IdentifierName(constantName); - } - - // If the current member access is a field or property access, check the lookup table - // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. - if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) - { - // Mark which dispatch properties have been used, to optimize the declaration afterwards - if (operation.Member.IsStatic) - { - string typeName = operation.Member.ContainingType.GetFullMetadataName(); - - if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true; - else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true; - else if (typeName == typeof(GridIds).FullName) IsGridIdsUsed = true; - - // Check that the dispatch info types are only used from the main shader body - if (!this.isEntryPoint || this.localFunctionDepth > 0) - { - DiagnosticDescriptor? descriptor = typeName switch - { - _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, - _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, - _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, - _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, - _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, - _ => null - }; - - if (descriptor is not null) - { - Diagnostics.Add(descriptor, node); - } - } - } - - // Static and instance members are handled differently, with static members being - // converted into a literal expression, and instance getting an updated identifier. - // For instance, consider these three cases: - // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) - // - ThreadIds.X (custom) => ThreadIds.x - // - uint3.X (instance) => [arg].x - return operation.Member.IsStatic switch - { - true => ParseExpression(mapping!), - false => updatedNode.WithName(IdentifierName(mapping!)) - }; - } - - // If the current member access is an access to any of the size properties in the available - // resource types (either buffer or texture types), then rewrite the subtree to transform the - // property access into an invocation of an autogenerated static helper method to get the target - // dimension for the buffer in use. The helper method is added to the list of static helpers. - if (operation is IPropertyReferenceOperation propertyOperation && - HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) - { - IMethodSymbol key = propertyOperation.Property.GetMethod!; - - if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) - { - INamedTypeSymbol resourceType = (INamedTypeSymbol)SemanticModel.For(node).GetTypeInfo(node.Expression).Type!; - string resourceName = HlslKnownTypes.GetMappedName(resourceType); - - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint _0, _1; - // texture.GetDimensions(_0, _1); - // - // return _0; - // } - methodSyntax = - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(IdentifierName(resourceName))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), - ReturnStatement(IdentifierName("_" + axis)))); - - this.staticMethods.Add(key, methodSyntax); - } - - return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) - { - var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) - { - // If the invocation consists of invoking a static method that has a direct - // mapping to HLSL, rewrite the expression in the current invocation node. - // For instance: Math.Abs(expr) => abs(expr). - if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) - { - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - - // Update the name if the target is a local function. The exact schema for the - // updated name is detailed in the override handling the local function statement. - if (method.MethodKind == MethodKind.LocalFunction) - { - var functionIdentifier = $"__{this.currentMethod!.Identifier.Text}__{method.Name}"; - - return updatedNode.WithExpression(ParseExpression(functionIdentifier)); - } - - // If the method is an external static method, import and rewrite it as well. - // This assumes that the target method is actually part of the same compilation. - // We need to check the declaring type to avoid rewriting static methods in the shader - // type as well, as they will be processed by the generator in a different path. - if (!SymbolEqualityComparer.Default.Equals(this.shaderType, method.ContainingType)) - { - var methodIdentifier = method.GetFullMetadataName().ToHlslIdentifierName(); - - if (!this.staticMethods.ContainsKey(method)) - { - ShaderSourceRewriter2 ShaderSourceRewriter2 = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); - MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(); - MethodDeclarationSyntax processedMethod = ShaderSourceRewriter2.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); - - this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); - } - - return updatedNode.WithExpression(ParseExpression(methodIdentifier)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitArgument(ArgumentSyntax node) - { - var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; - - // Strip the ref keywords from arguments - updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); - - // Track and rewrite the discarded declaration - if (SemanticModel.For(node).GetOperation(node.Expression) is IDiscardOperation operation) - { - TypeSyntax typeSyntax = operation.Type!.TrackType(DiscoveredTypes); - string identifier = $"__implicit{this.implicitVariables.Count}"; - - // Add the variable to the list of implicit declarations - this.implicitVariables.Add(VariableDeclaration(typeSyntax).AddVariables(VariableDeclarator(identifier))); - - return updatedNode.WithExpression(IdentifierName(identifier)); - } - - return updatedNode; - } -} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0b45396c..0cf712f9 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGenerators.Diagnostics; @@ -63,7 +64,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. /// Whether or not the current instance is processing a shader entry point. public ShaderSourceRewriter( INamedTypeSymbol shaderType, @@ -71,9 +72,9 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - GeneratorExecutionContext context, + ImmutableArray.Builder diagnostics, bool isEntryPoint) - : base(semanticModel, discoveredTypes, constantDefinitions, context) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.shaderType = shaderType; this.staticMethods = staticMethods; @@ -89,14 +90,14 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. public ShaderSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - GeneratorExecutionContext context) - : base(semanticModel, discoveredTypes, constantDefinitions, context) + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; this.implicitVariables = new(); @@ -134,12 +135,12 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { - Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); } if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) { - Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node); + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); } if (updatedNode is not null) @@ -183,7 +184,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration }) { - Context.ReportDiagnostic(UsingStatementOrDeclaration, node); + Diagnostics.Add(UsingStatementOrDeclaration, node); } return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes); @@ -227,12 +228,12 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword))) { - Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node); + Diagnostics.Add(AsyncModifierOnMethodOrFunction, node); } if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) { - Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node); + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); } this.localFunctionDepth--; @@ -295,7 +296,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (descriptor is not null) { - Context.ReportDiagnostic(descriptor, node); + Diagnostics.Add(descriptor, node); } } } @@ -403,7 +404,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter if (!this.staticMethods.ContainsKey(method)) { - ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context); + ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics); MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(); MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs deleted file mode 100644 index ea6bb249..00000000 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.Incremental.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Operations; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGenerators.SyntaxRewriters; - -/// -/// A custom type that processes C# static field to convert to HLSL static fields (possibly constant). -/// -internal sealed class StaticFieldRewriter2 : HlslSourceRewriter2 -{ - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The collection of discovered constant definitions. - /// The collection of produced instances. - public StaticFieldRewriter2( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) - { - } - - /// - public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) - { - if (node?.Initializer is EqualsValueClauseSyntax fieldInitializer) - { - return ((EqualsValueClauseSyntax)Visit(fieldInitializer))!.Value; - } - - return null; - } - - /// - public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) - { - var updatedNode = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node)!; - - if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && - SemanticModel.For(node).GetOperation(node) is IMemberReferenceOperation operation) - { - // Track and replace constants - if (operation is IFieldReferenceOperation fieldOperation && - fieldOperation.Field.IsConst && - fieldOperation.Type!.TypeKind != TypeKind.Enum) - { - ConstantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); - - var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; - - return IdentifierName(constantName); - } - - if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) - { - if (operation.Member.IsStatic) - { - string typeName = operation.Member.ContainingType.GetFullMetadataName(); - - // Special dispatch types are not supported from static constants - DiagnosticDescriptor? descriptor = typeName switch - { - _ when typeName == typeof(ThreadIds).FullName || typeName == typeof(ThreadIds.Normalized).FullName => InvalidThreadIdsUsage, - _ when typeName == typeof(GroupIds).FullName => InvalidGroupIdsUsage, - _ when typeName == typeof(GroupSize).FullName => InvalidGroupSizeUsage, - _ when typeName == typeof(GridIds).FullName => InvalidGridIdsUsage, - _ when typeName == typeof(DispatchSize).FullName => InvalidDispatchSizeUsage, - _ => null - }; - - if (descriptor is not null) - { - Diagnostics.Add(descriptor, node); - } - } - - // Rewrite static and instance mapped members - return operation.Member.IsStatic switch - { - true => ParseExpression(mapping!), - false => updatedNode.WithName(IdentifierName(mapping!)) - }; - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) - { - var updatedNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - - if (SemanticModel.For(node).GetOperation(node) is IInvocationOperation operation && - operation.TargetMethod is IMethodSymbol method && - method.IsStatic) - { - // Rewrite HLSL intrinsic methods - if (HlslKnownMethods.TryGetMappedName(method.GetFullMetadataName(), out string? mapping)) - { - return updatedNode.WithExpression(ParseExpression(mapping!)); - } - } - - return updatedNode; - } - - /// - public override SyntaxNode? VisitArgument(ArgumentSyntax node) - { - var updatedNode = (ArgumentSyntax)base.VisitArgument(node)!; - - updatedNode = updatedNode.WithRefKindKeyword(Token(SyntaxKind.None)); - - return updatedNode; - } -} diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index f80d5e49..b724fc9d 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Globalization; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; @@ -25,13 +26,13 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. public StaticFieldRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - GeneratorExecutionContext context) - : base(semanticModel, discoveredTypes, constantDefinitions, context) + ImmutableArray.Builder diagnostics) + : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { } @@ -86,7 +87,7 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter if (descriptor is not null) { - Context.ReportDiagnostic(descriptor, node); + Diagnostics.Add(descriptor, node); } } From ce63946d13a907cae4f352ca64f856c225984553 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 00:54:16 +0100 Subject: [PATCH 24/36] Minor code style tweaks --- .../IShaderGenerator.CreateTryGetBytecodeMethod.cs | 2 +- src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs | 4 ++-- src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs | 4 ++-- src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs | 4 ++-- src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 75231ba7..f7df94ef 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -152,7 +152,7 @@ public sealed partial class IShaderGenerator // e.Message); } - End: + End: diagnostics = builder.ToImmutable(); return bytecode; diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs index fdf4a04a..b1462dad 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -1,7 +1,7 @@ -using ComputeSharp.SourceGenerators.Extensions; -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; namespace ComputeSharp.SourceGenerators.Models; diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs index 772a9516..373eb800 100644 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs @@ -1,7 +1,7 @@ -using ComputeSharp.SourceGenerators.Extensions; -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; namespace ComputeSharp.SourceGenerators.Models; diff --git a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs index f177ca4b..25f7a5d7 100644 --- a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs @@ -1,7 +1,7 @@ -using ComputeSharp.SourceGenerators.Extensions; -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; namespace ComputeSharp.SourceGenerators.Models; diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs index 702e1eb3..630884e2 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs @@ -1,7 +1,7 @@ -using ComputeSharp.SourceGenerators.Extensions; -using System; +using System; using System.Collections.Generic; using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; namespace ComputeSharp.SourceGenerators.Models; From 2209c9eb41388e3868755b2aa5c412f4496d18cf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 01:52:26 +0100 Subject: [PATCH 25/36] Set generator native libs to extract to same folder --- ...ShaderGenerator.CreateTryGetBytecodeMethod.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index f7df94ef..74771087 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -87,7 +87,7 @@ public sealed partial class IShaderGenerator /// /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. /// - private static bool areDxcLibrariesLoaded; + private static volatile bool areDxcLibrariesLoaded; /// /// Gets a instance with the logic to try to get a compiled shader bytecode. @@ -166,10 +166,10 @@ public sealed partial class IShaderGenerator private static void LoadNativeDxcLibraries() { // Extracts a specified native library for a given runtime identifier - static string ExtractLibrary(string rid, string name) + static string ExtractLibrary(string folder, string rid, string name) { string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; - string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll"); + string targetFilename = Path.Combine(folder, rid, $"{name}.dll"); Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); @@ -214,11 +214,13 @@ public sealed partial class IShaderGenerator _ => throw new NotSupportedException("Invalid process architecture") }; - LoadLibrary(ExtractLibrary(rid, "dxil")); - LoadLibrary(ExtractLibrary(rid, "dxcompiler")); - } + string folder = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName()); - areDxcLibrariesLoaded = true; + LoadLibrary(ExtractLibrary(folder, rid, "dxil")); + LoadLibrary(ExtractLibrary(folder, rid, "dxcompiler")); + + areDxcLibrariesLoaded = true; + } } } } From 2e160c5caac49f3241b45c5eec475f581a7fe03c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 02:23:48 +0100 Subject: [PATCH 26/36] Enable diagnostics from bytecode transformation --- ...derGenerator.CreateTryGetBytecodeMethod.cs | 29 +++------ .../IShaderGenerator.cs | 27 ++++++-- .../Models/DiagnosticInfo.cs | 64 +++++++++++++++++++ .../Models/HierarchyInfo.cs | 7 +- 4 files changed, 100 insertions(+), 27 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 74771087..645108ca 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -94,20 +94,21 @@ public sealed partial class IShaderGenerator /// /// The input instance to process. /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting diagnostics from the processing operation. + /// The resulting diagnostic from the processing operation, if any. /// The instance with the compiled shader bytecode. [Pure] public static unsafe ImmutableArray GetBytecode( ThreadIdsInfo threadIds, string hlslSource, - out ImmutableArray diagnostics) + out DiagnosticInfo? diagnostic) { ImmutableArray bytecode = ImmutableArray.Empty; - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); // No embedded shader was requested if (threadIds.IsDefault) { + diagnostic = null; + goto End; } @@ -131,30 +132,18 @@ public sealed partial class IShaderGenerator byte[] array = new ReadOnlySpan(buffer, length).ToArray(); bytecode = Unsafe.As>(ref array); + diagnostic = null; } - catch (Win32Exception) + catch (Win32Exception e) { - // TODO - //builder.Add( - // EmbeddedBytecodeFailedWithWin32Exception, - // structDeclarationSymbol, - // structDeclarationSymbol, - // e.HResult, - // e.Message); + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, e.Message); } - catch (HlslCompilationException) + catch (HlslCompilationException e) { - // TODO - //builder.Add( - // EmbeddedBytecodeFailedWithHlslCompilationException, - // structDeclarationSymbol, - // structDeclarationSymbol, - // e.Message); + diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithHlslCompilationException, e.Message); } End: - diagnostics = builder.ToImmutable(); - return bytecode; } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index ebcf35b2..04d0fdd7 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -193,11 +193,11 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default, ThreadIdsInfo.Comparer.Default); // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result BytecodeInfo)> embeddedBytecodeWithErrors = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = shaderBytecodeInfo .Select(static (item, token) => { - ImmutableArray bytecode = TryGetBytecode.GetBytecode(item.ThreadIds, item.Hlsl, out ImmutableArray diagnostics); + ImmutableArray bytecode = TryGetBytecode.GetBytecode(item.ThreadIds, item.Hlsl, out DiagnosticInfo? diagnostic); EmbeddedBytecodeInfo bytecodeInfo = new( item.ThreadIds.X, @@ -205,16 +205,33 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator item.ThreadIds.Z, bytecode); - return (item.Hierarchy, new Result(bytecodeInfo, diagnostics)); + return (item.Hierarchy, bytecodeInfo, diagnostic); + }); + + // Gather the diagnostics + IncrementalValuesProvider> embeddedBytecodeDiagnostics = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy.MetadataName, item.Diagnostic)) + .Where(static item => item.Diagnostic is not null) + .Combine(context.CompilationProvider) + .Select(static (item, token) => + { + INamedTypeSymbol? typeSymbol = item.Right.GetTypeByMetadataName(item.Left.MetadataName)!; + Diagnostic diagnostic = Diagnostic.Create( + item.Left.Diagnostic!.Descriptor, + typeSymbol.Locations.FirstOrDefault(), + new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + + return ImmutableArray.Create(diagnostic); }); // Output the diagnostics - context.ReportDiagnostics(embeddedBytecodeWithErrors.Select(static (item, token) => item.BytecodeInfo.Errors)); + context.ReportDiagnostics(embeddedBytecodeDiagnostics); // Get the filtered sequence to enable caching IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo.Value)) + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default); // Generate the TryGetBytecode() methods diff --git a/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs new file mode 100644 index 00000000..e3711b93 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for a serializeable diagnostic provider. +/// +/// The wrapped instance. +/// The diagnostic args. +internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(DiagnosticInfo? x, DiagnosticInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.Descriptor.Equals(y.Descriptor) && + x.Args.SequenceEqual(y.Args); + } + + /// + public int GetHashCode(DiagnosticInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.Descriptor); + + foreach (object arg in obj.Args) + { + hashCode.Add(arg); + } + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs index 0842eb94..10039dac 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -12,9 +12,10 @@ namespace ComputeSharp.SourceGenerators.Models; /// A model describing the hierarchy info for a specific type. /// /// The filename hint for the current type. +/// The metadata name for the current type. /// Gets the namespace for the current type. /// Gets the sequence of type definitions containing the current type. -internal sealed record HierarchyInfo(string FilenameHint, string Namespace, ImmutableArray Names) +internal sealed record HierarchyInfo(string FilenameHint, string MetadataName, string Namespace, ImmutableArray Names) { /// /// Creates a new instance from a given . @@ -35,6 +36,7 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu return new( typeSymbol.GetGeneratedFileName(), + typeSymbol.MetadataName, typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)), names.ToImmutable()); } @@ -69,6 +71,7 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu return x.FilenameHint == y.FilenameHint && + x.MetadataName == y.MetadataName && x.Namespace == y.Namespace && x.Names.SequenceEqual(y.Names); } @@ -76,7 +79,7 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu /// public int GetHashCode(HierarchyInfo obj) { - return HashCode.Combine(obj.Namespace, obj.Names, obj.Names[0]); + return HashCode.Combine(obj.Namespace, obj.MetadataName, obj.Names, obj.Names[0]); } } } From 2242f671eefe0847886a9dcd55dec768184542e2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 10:52:40 +0100 Subject: [PATCH 27/36] Match attributes by qualified name and not symbol --- ...erGenerator.CreateBuildHlslStringMethod.cs | 6 +-- ...derGenerator.CreateTryGetBytecodeMethod.cs | 4 +- .../IShaderGenerator.cs | 40 +++++++------------ 3 files changed, 19 insertions(+), 31 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index a7189020..884a657d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -119,7 +119,7 @@ public sealed partial class IShaderGenerator continue; } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName); // Group shared fields must be static if (attribute is not null) @@ -215,7 +215,7 @@ public sealed partial class IShaderGenerator continue; } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName); if (attribute is not null) { @@ -276,7 +276,7 @@ public sealed partial class IShaderGenerator continue; } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName); if (attribute is null) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 645108ca..44a5082b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -30,20 +30,18 @@ public sealed partial class IShaderGenerator /// /// Gets the thread ids values for a given shader type, if available. /// - /// The instance for the attribute. /// The input instance to process. /// Indicates whether or not the shader is dynamic (ie. captures delegates). /// The resulting diagnostics from the processing operation. /// The thread ids for the precompiled shader, if available. public static ThreadIdsInfo GetInfo( - INamedTypeSymbol embeddedBytecodeAttribute, INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, out ImmutableArray diagnostics) { AttributeData? attribute = structDeclarationSymbol .GetAttributes() - .FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, embeddedBytecodeAttribute)); + .FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(EmbeddedBytecodeAttribute).FullName); if (attribute is null) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 04d0fdd7..e16984d4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -38,21 +38,18 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) .Where(static pair => pair.Symbol is not null)!; - // Get the symbol for the IComputeShader interface - IncrementalValueProvider iComputeShaderSymbol = + // Get the symbol for the IComputeShader and IPixelShader interfaces + IncrementalValueProvider<(INamedTypeSymbol Compute, INamedTypeSymbol Pixel) > shaderInterfaces = context.CompilationProvider - .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName))!; - - // Get the symbol for the IPixelShader interface - IncrementalValueProvider iPixelShaderSymbol = - context.CompilationProvider - .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName))!; + .Select(static (compilation, token) => ( + Compute: compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName)!, + Pixel: compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName)!)); // Filter struct declarations that implement a shader interface, and also gather the hierarchy info and shader type IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy, Type Type)> shaderDeclarations = structDeclarations - .Combine(iComputeShaderSymbol.Combine(iPixelShaderSymbol)) - .Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Left, item.Right.Right))) + .Combine(shaderInterfaces) + .Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Compute, item.Right.Pixel))) .Where(static item => item.Type is not null) .Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol), item.Type!)); @@ -71,30 +68,24 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); - // Get the [EmbeddedBytecode] attribute - IncrementalValueProvider embeddedBytecodeSymbol = - context.CompilationProvider - .Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(EmbeddedBytecodeAttribute).FullName)!); - // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the // same step as parts are shared in following sub-branches in the incremental generator pipeline. IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) - .Combine(embeddedBytecodeSymbol) .Select(static (item, token) => { // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( - item.Left.Left.Symbol, - item.Left.Left.Type, + item.Left.Symbol, + item.Left.Type, out int resourceCount, out int root32BitConstantCount, out ImmutableArray dispatchDataDiagnostics); Result dispatchDataInfo = new(new DispatchDataInfo( - item.Left.Left.Hierarchy, - item.Left.Left.Type, + item.Left.Hierarchy, + item.Left.Type, fieldInfos, resourceCount, root32BitConstantCount), @@ -102,15 +93,14 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // BuildHlslString() info HlslSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( - item.Left.Right, - item.Left.Left.Syntax, - item.Left.Left.Symbol, + item.Right, + item.Left.Syntax, + item.Left.Symbol, out ImmutableArray hlslSourceDiagnostics); // TryGetBytecode() info ThreadIdsInfo threadIds = TryGetBytecode.GetInfo( - item.Right, - item.Left.Left.Symbol, + item.Left.Symbol, !hlslSourceInfo.Delegates.IsEmpty, out ImmutableArray threadIdsDiagnostics); From e564864b6c945cba6355d9496f2984fe4d23080f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 10:53:57 +0100 Subject: [PATCH 28/36] Add check for [EmbeddedBytecode] not having 3 arguments --- .../IShaderGenerator.CreateTryGetBytecodeMethod.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 44a5082b..47fc3948 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -53,7 +53,8 @@ public sealed partial class IShaderGenerator ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); // Validate the thread number arguments - if (attribute.ConstructorArguments[0].Value is not int threadsX || + if (attribute.ConstructorArguments.Length != 3 || + attribute.ConstructorArguments[0].Value is not int threadsX || attribute.ConstructorArguments[1].Value is not int threadsY || attribute.ConstructorArguments[2].Value is not int threadsZ || threadsX is < 1 or > 1024 || From 689e0e7202702ce610d17888f1b6d7a535a2ec0c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 11:19:05 +0100 Subject: [PATCH 29/36] Fix [GroupShared] HLSL generation, add unit tests --- ...erGenerator.CreateBuildHlslStringMethod.cs | 2 +- tests/ComputeSharp.Tests/DispatchTests.cs | 88 +++++++++++++++++++ 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 884a657d..58b2c3fc 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -680,7 +680,7 @@ public sealed partial class IShaderGenerator // Shared buffers foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) { - object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + object count = (object?)bufferCount ?? "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z"; AppendLF(); AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs index df57f287..b4078328 100644 --- a/tests/ComputeSharp.Tests/DispatchTests.cs +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -4,6 +4,8 @@ using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable CS0649, CS8618 + namespace ComputeSharp.Tests; [TestClass] @@ -298,4 +300,90 @@ public partial class DispatchTests 1); } } + + [CombinatorialTestMethod] + [AllDevices] + public void Verify_GroupShared_WithFixedSize(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(128); + + device.Get().For(256, new FixedGroupSharedPixelShader(buffer)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 128; i++) + { + Assert.AreEqual(result[i], i); + } + } + + [AutoConstructor] + internal readonly partial struct FixedGroupSharedPixelShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + [GroupShared(128)] + private static readonly int[] cache; + + public void Execute() + { + int index = ThreadIds.X / 2; + bool isWritingToGroupShared = ThreadIds.X % 2 == 0; + + if (isWritingToGroupShared) + { + cache[index] = index; + } + + Hlsl.GroupMemoryBarrier(); + + if (!isWritingToGroupShared) + { + buffer[index] = cache[index]; + } + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void Verify_GroupShared_WithDynamicSize(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(32); + + device.Get().For(64, 1, 1, 32, 1, 1, new DynamicGroupSharedPixelShader(buffer)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 32; i++) + { + Assert.AreEqual(result[i], i); + } + } + + [AutoConstructor] + internal readonly partial struct DynamicGroupSharedPixelShader : IComputeShader + { + private readonly ReadWriteBuffer buffer; + + [GroupShared] + private static readonly int[] cache; + + public void Execute() + { + int index = ThreadIds.X / 2; + bool isWritingToGroupShared = ThreadIds.X % 2 == 0; + + if (isWritingToGroupShared) + { + cache[index] = index; + } + + Hlsl.GroupMemoryBarrier(); + + if (!isWritingToGroupShared) + { + buffer[index] = cache[index]; + } + } + } } From 1216d511a76a88dd25d183c6e532760aaf20c423 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 12:31:36 +0100 Subject: [PATCH 30/36] Minor code tweaks to IShaderGenerator --- .../IShaderGenerator.Helpers.cs | 6 +++--- src/ComputeSharp.SourceGenerators/IShaderGenerator.cs | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs index 8435dada..fe59ff8e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -43,7 +43,7 @@ public sealed partial class IShaderGenerator return null; } - + /// /// Creates a instance wrapping the given method. /// @@ -105,8 +105,8 @@ public sealed partial class IShaderGenerator .AddMembers(typeDeclarationSyntax); } - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: + // Create the compilation unit with disabled warnings, target namespace and generated type. + // This will produce code as follows: // // #pragma warning disable // diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index e16984d4..3e887061 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -31,12 +31,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Get all declared struct types and their type symbols IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = - context.SyntaxProvider.CreateSyntaxProvider( + context.SyntaxProvider + .CreateSyntaxProvider( static (node, token) => node is StructDeclarationSyntax structDeclaration, static (context, token) => ( (StructDeclarationSyntax)context.Node, Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) - .Where(static pair => pair.Symbol is not null)!; + .Where(static pair => pair.Symbol is { Interfaces.IsEmpty: false })!; // Get the symbol for the IComputeShader and IPixelShader interfaces IncrementalValueProvider<(INamedTypeSymbol Compute, INamedTypeSymbol Pixel) > shaderInterfaces = From 0aba871d523cd6d961fb7ca8301504641946d3f4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 12:31:51 +0100 Subject: [PATCH 31/36] Switch [AutoConstructor] generator to incremental --- ...AutoConstructorGenerator.SyntaxReceiver.cs | 54 ----- .../AutoConstructorGenerator.cs | 200 +++++++++++------- .../Extensions/IEqualityComparerExtensions.cs | 59 ++++++ .../Models/ParameterInfo.cs | 8 + .../AutoConstructorGeneratorTests.cs | 33 +-- 5 files changed, 205 insertions(+), 149 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs create mode 100644 src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs create mode 100644 src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs deleted file mode 100644 index 478303bb..00000000 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class AutoConstructorGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax { AttributeLists: { Count: > 0 } } structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(AutoConstructorAttribute).FullName) is INamedTypeSymbol attributeSymbol && - structSymbol.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)) is AttributeData attributeData && - attributeData.ApplicationSyntaxReference is SyntaxReference syntaxReference && - syntaxReference.GetSyntax() is AttributeSyntax attributeSyntax) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol, attributeSyntax, attributeData)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - /// The instance for the target attribute over . - /// The instance for . - public sealed record Item( - StructDeclarationSyntax StructDeclaration, - INamedTypeSymbol StructSymbol, - AttributeSyntax AttributeSyntax, - AttributeData AttributeData); - } -} diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 1aac7f97..f04c3e04 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -1,111 +1,151 @@ -using System.Collections.Immutable; +using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Text; -using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; namespace ComputeSharp.SourceGenerators; /// /// A source generator creating constructors for types annotated with . /// -[Generator] -public sealed partial class AutoConstructorGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed partial class AutoConstructorGenerator : IIncrementalGenerator { /// - public void Initialize(GeneratorInitializationContext context) + public void Initialize(IncrementalGeneratorInitializationContext context) { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } + // Get all declared struct symbols with the [AutoConstructor] attribute + IncrementalValuesProvider structDeclarations = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, token) => node is StructDeclarationSyntax structDeclaration, + static (context, token) => (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)) + .Where(static symbol => symbol is not null && + symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(AutoConstructorAttribute).FullName))!; - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } + // Get the type hierarchy and fields info + IncrementalValuesProvider<(HierarchyInfo Left, ImmutableArray Right)> constructorInfo = + structDeclarations + .Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Parameters: Ctor.GetData(item))) + .Where(static item => !item.Parameters.IsEmpty) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default.ForImmutableArray()); - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) + // Generate the constructors + context.RegisterSourceOutput(constructorInfo, static (context, item) => { - try - { - OnExecute(context, item.StructDeclaration, item.StructSymbol); - } - catch - { - context.ReportDiagnostic(AutoConstructorGeneratorError, item.AttributeSyntax, item.StructSymbol); - } - } + CompilationUnitSyntax compilationUnit = Ctor.GetSyntax(item.Left, item.Right); + + context.AddSource($"{item.Left.FilenameHint}.Ctor", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// - /// Processes a given target type. + /// A helper with all logic to generate the constructor declarations. /// - /// The input instance to use. - /// The node to process. - /// The for . - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) + private static class Ctor { - // Extract the info on the type to process - var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - var structName = structDeclaration.Identifier.Text; - var structModifiers = structDeclaration.Modifiers; - var fields = ( - from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() - where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer - let typeName = fieldSymbol.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) - let fieldFullType = ParseTypeName(typeName) - select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray(); - - // Create the constructor declaration for the type. This will - // produce a constructor with simple initialization of all variables: - // - // public MyType(Foo a, Bar b, Baz c, ...) - // { - // this.a = a; - // this.b = b; - // this.c = c; - // ... - // } - var structDeclarationSyntax = - StructDeclaration(structName).WithModifiers(structModifiers).AddMembers( - ConstructorDeclaration(structName) - .AddModifiers(Token(SyntaxKind.PublicKeyword)) - .AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray()) - .AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray())); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (var parentType in structDeclaration.Ancestors().OfType()) + /// + /// Gets the sequence of items for all fields in the input type. + /// + /// The being inspected. + /// The sequence of items for all fields in . + public static ImmutableArray GetData(INamedTypeSymbol structDeclarationSymbol) { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); + return ( + from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() + where fieldSymbol is { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } + let typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + select new ParameterInfo(typeName, fieldSymbol.Name)).ToImmutableArray(); } - // Create the compilation unit with the namespace and target member. - // From this, we can finally generate the source code to output. - var source = - CompilationUnit().AddMembers( - FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace(eol: "\n") - .ToFullString(); + /// + /// Gets the instance for a given type and sequence of parameters. + /// + /// The type hierarchy info. + /// The sequence of parameters to initialize. + /// A instance for a specified type. + public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray parameters) + { + // Create the constructor declaration for the type. This will + // produce a constructor with simple initialization of all variables: + // + // public MyType(Foo a, Bar b, Baz c, ...) + // { + // this.a = a; + // this.b = b; + // this.c = c; + // ... + // } + ConstructorDeclarationSyntax constructorDeclaration = + ConstructorDeclaration(hierarchyInfo.Names[0]) + .AddModifiers(Token(SyntaxKind.PublicKeyword)) + .AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray()) + .AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray()); - // Add the partial type - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + // Add the unsafe modifier, if needed + if (parameters.Any(static param => param.Type.Contains("*"))) + { + constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword)); + } + + // Constructor attributes + AttributeListSyntax[] attributes = + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))) + }; + + // Create the partial shader type declaration with the given method implementation. + // This code produces a struct declaration as follows: + // + // partial struct + // { + // + // } + StructDeclarationSyntax structDeclarationSyntax = + StructDeclaration(hierarchyInfo.Names[0]) + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(constructorDeclaration.AddAttributeLists(attributes)); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1)) + { + typeDeclarationSyntax = + ClassDeclaration(parentType) + .AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddMembers(typeDeclarationSyntax); + } + + // Create the compilation unit with disabled warnings, target namespace and generated type. + // This will produce code as follows: + // + // #pragma warning disable + // + // namespace ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs new file mode 100644 index 00000000..306d8c11 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IEqualityComparerExtensions +{ + /// + /// Gets an for an sequence. + /// + /// The type of items to compare. + /// The compare for individual items. + public static IEqualityComparer> ForImmutableArray(this IEqualityComparer comparer) + { + return new Comparer(comparer); + } + + /// + /// An implementation for an value. + /// + public sealed class Comparer : IEqualityComparer> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + public Comparer(IEqualityComparer comparer) + { + this.comparer = comparer; + } + + /// + public bool Equals(ImmutableArray x, ImmutableArray y) + { + return + x == y || + x.SequenceEqual(y, this.comparer); + } + + /// + public int GetHashCode(ImmutableArray obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj, this.comparer); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs new file mode 100644 index 00000000..137df444 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs @@ -0,0 +1,8 @@ +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model describing info on a constructor parameter. +/// +/// The fully qualified type name. +/// The parameter name. +internal sealed record ParameterInfo(string Type, string Name); diff --git a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs index ca2cc0af..db4eb6c6 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs @@ -27,7 +27,7 @@ public class AutoConstructorGeneratorTests namespace MyFancyApp.Sample { - public partial interface IFoo : IFluff + public partial class IFoo : IFluff where T : notnull, new() { public partial class Foo @@ -44,25 +44,28 @@ public class AutoConstructorGeneratorTests } }"; - string expected = @" + string expected = $@" #pragma warning disable namespace MyFancyApp.Sample; - public partial interface IFoo - { - public partial class Foo - { - public readonly partial struct Test - { + partial class IFoo + {{ + partial class Foo + {{ + partial struct Test + {{ + [global::System.CodeDom.Compiler.GeneratedCode(""ComputeSharp.SourceGenerators.AutoConstructorGenerator"", ""{typeof(AutoConstructorGenerator).Assembly.GetName().Version}"")] + [global::System.Diagnostics.DebuggerNonUserCode] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public Test(float a, global::System.Numerics.Vector2 b, global::ComputeSharp.ReadWriteBuffer c, global::ComputeSharp.ReadWriteBuffer d) - { + {{ this.a = a; this.b = b; this.c = c; this.d = d; - } - } - } - }"; + }} + }} + }} + }}"; VerifyGeneratedMethodLines(source, 0, expected); } @@ -75,7 +78,7 @@ public class AutoConstructorGeneratorTests /// The target index to check in the resulting output. /// The expected body to compare with the generated code. private static void VerifyGeneratedMethodLines(string source, int index, string expectedBody) - where TGenerator : class, ISourceGenerator, new() + where TGenerator : class, IIncrementalGenerator, new() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); @@ -87,7 +90,7 @@ public class AutoConstructorGeneratorTests CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); - ISourceGenerator generator = new TGenerator(); + IIncrementalGenerator generator = new TGenerator(); CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator); From 6269267bf0eb070fa79b65c57789af7e83c81914 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 12:33:42 +0100 Subject: [PATCH 32/36] Switch global usings generator to incremental --- .../GlobalUsingDirectivesGenerator.cs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs b/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs index 020d0056..53d86891 100644 --- a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs @@ -9,13 +9,13 @@ namespace ComputeSharp.SourceGenerators; /// /// A source generator to create global using directives for the HLSL primitive types. /// -[Generator] -public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed class GlobalUsingDirectivesGenerator : IIncrementalGenerator { /// - public void Initialize(GeneratorInitializationContext context) + public void Initialize(IncrementalGeneratorInitializationContext context) { - context.RegisterForPostInitialization(static context => + context.RegisterPostInitializationOutput(static context => { const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs"; @@ -27,9 +27,4 @@ public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator context.AddSource("GlobalUsingDirectives.cs", SourceText.From(globalUsingDirectives, Encoding.UTF8)); }); } - - /// - public void Execute(GeneratorExecutionContext context) - { - } } From d1fabb6fedce058970a83b948f7f23b36749aa2a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 13:32:48 +0100 Subject: [PATCH 33/36] Switch [ShaderMethod] generator to incremental --- ...ator.CreateBuildHlslStringMethod.Syntax.cs | 8 +- ...erGenerator.CreateBuildHlslStringMethod.cs | 8 +- .../IShaderGenerator.cs | 14 +- .../Models/HlslMethodSourceInfo.cs | 73 +++++ ...lSourceInfo.cs => HlslShaderSourceInfo.cs} | 10 +- ...derMethodSourceGenerator.SyntaxReceiver.cs | 46 ---- .../ShaderMethodSourceGenerator.cs | 250 ++++++++++-------- 7 files changed, 236 insertions(+), 173 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs rename src/ComputeSharp.SourceGenerators/Models/{HlslSourceInfo.cs => HlslShaderSourceInfo.cs} (93%) delete mode 100644 src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs index 8ecc9d28..5b4e860a 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs @@ -20,9 +20,9 @@ public sealed partial class IShaderGenerator /// /// Creates a instance for the BuildHlslString method. /// - /// The input instance to use. + /// The input instance to use. /// The resulting instance for the BuildHlslString method. - public static MethodDeclarationSyntax GetSyntax(HlslSourceInfo hlslSourceInfo) + public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo) { ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); @@ -49,9 +49,9 @@ public sealed partial class IShaderGenerator /// /// Produces the series of statements to build the current HLSL source. /// - /// The input instance to use. + /// The input instance to use. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) + private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo) { ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); StringBuilder textBuilder = new(); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 58b2c3fc..d329491e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -36,7 +36,7 @@ public sealed partial class IShaderGenerator /// The for . /// The resulting diagnostics from the processing operation. /// The resulting info on the processed shader. - public static HlslSourceInfo GetInfo( + public static HlslShaderSourceInfo GetInfo( Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -508,7 +508,7 @@ public sealed partial class IShaderGenerator /// Whether the static sampler is used by the shader. /// The body of the entry point of the shader. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static HlslSourceInfo GetHlslSourceInfo( + private static HlslShaderSourceInfo GetHlslSourceInfo( ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, @@ -731,9 +731,9 @@ public sealed partial class IShaderGenerator /// /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). /// - /// The input instance to use. + /// The input instance to use. /// The non dynamic HLSL source code. - public static string GetNonDynamicHlslSource(HlslSourceInfo hlslSourceInfo) + public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo) { return hlslSourceInfo.HeaderAndThreadsX + "" + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 3e887061..50af3d93 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -71,7 +71,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the // same step as parts are shared in following sub-branches in the incremental generator pipeline. - IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = + IncrementalValuesProvider<(Result Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => @@ -93,7 +93,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator dispatchDataDiagnostics); // BuildHlslString() info - HlslSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( + HlslShaderSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( item.Right, item.Left.Syntax, item.Left.Symbol, @@ -107,7 +107,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator return ( dispatchDataInfo, - new Result(hlslSourceInfo, hlslSourceDiagnostics), + new Result(hlslSourceInfo, hlslSourceDiagnostics), new Result(threadIds, threadIdsDiagnostics)); }); @@ -117,10 +117,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors)); // Filter all items to enable caching at a coarse level, and remove diagnostics - IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = + IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = shaderInfoWithErrors .Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value)) - .WithComparers(DispatchDataInfo.Comparer.Default, HlslSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); + .WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default); // Get a filtered sequence to enable caching IncrementalValuesProvider dispatchDataInfo = @@ -142,10 +142,10 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator }); // Get the filtered sequence to enable caching - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> hlslSourceInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo)> hlslSourceInfo = shaderInfo .Select(static (item, token) => (item.Dispatch.Hierarchy, item.Hlsl)) - .WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); + .WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default); // Generate the BuildHlslString() methods context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs new file mode 100644 index 00000000..40788938 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL method. +/// +/// The metadata name for the method. +/// The meethod entry point. +/// The discovered declared types. +/// The discovered defined constants. +/// The dependent captured methods. +internal sealed record HlslMethodSourceInfo( + string MetadataName, + string EntryPoint, + ImmutableArray<(string Name, string Definition)> DefinedTypes, + ImmutableArray<(string Name, string Value)> DefinedConstants, + ImmutableArray<(string Signature, string Definition)> DependentMethods) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(HlslMethodSourceInfo? x, HlslMethodSourceInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.MetadataName == y.MetadataName && + x.EntryPoint == y.EntryPoint && + x.DefinedTypes.SequenceEqual(y.DefinedTypes) && + x.DefinedConstants.SequenceEqual(y.DefinedConstants) && + x.DependentMethods.SequenceEqual(y.DependentMethods); + } + + /// + public int GetHashCode(HlslMethodSourceInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.MetadataName); + hashCode.Add(obj.EntryPoint); + hashCode.AddRange(obj.DefinedTypes); + hashCode.AddRange(obj.DefinedConstants); + hashCode.AddRange(obj.DependentMethods); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs similarity index 93% rename from src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs rename to src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index 630884e2..82067efa 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Models; /// The names of defined constants. /// The signatures for captured methods. /// The list of delegate fields. -internal sealed record HlslSourceInfo( +internal sealed record HlslShaderSourceInfo( string HeaderAndThreadsX, string ThreadsY, string ThreadsZ, @@ -39,9 +39,9 @@ internal sealed record HlslSourceInfo( ImmutableArray Delegates) { /// - /// An implementation for . + /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : IEqualityComparer { /// /// The singleton instance. @@ -49,7 +49,7 @@ internal sealed record HlslSourceInfo( public static Comparer Default { get; } = new(); /// - public bool Equals(HlslSourceInfo? x, HlslSourceInfo? y) + public bool Equals(HlslShaderSourceInfo? x, HlslShaderSourceInfo? y) { if (x is null && y is null) { @@ -84,7 +84,7 @@ internal sealed record HlslSourceInfo( } /// - public int GetHashCode(HlslSourceInfo obj) + public int GetHashCode(HlslShaderSourceInfo obj) { HashCode hashCode = default; diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs deleted file mode 100644 index 8349eb3f..00000000 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators; - -/// -public sealed partial class ShaderMethodSourceGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } } methodDeclaration && - context.SemanticModel.GetDeclaredSymbol(methodDeclaration) is IMethodSymbol methodSymbol && - context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(ShaderMethodAttribute).FullName) is INamedTypeSymbol attributeSymbol && - methodSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol))) - { - this.gatheredInfo.Add(new Item(methodDeclaration, methodSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered method to process. - /// - /// The instance for the target method declaration. - /// The instance for . - public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol); - } -} diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 4d569fa0..ad462f9a 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,17 +1,18 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; +using System.Linq; using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -22,129 +23,164 @@ namespace ComputeSharp.SourceGenerators; /// /// A source generator for processing static methods referenced from compute shaders. /// -[Generator] -public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator { /// - public void Initialize(GeneratorInitializationContext context) + public void Initialize(IncrementalGeneratorInitializationContext context) { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } + // Get all declared methods with the [ShaderMethod] attribute + IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> structDeclarations = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } methodDeclaration, + static (context, token) => ( + Syntax: (MethodDeclarationSyntax)context.Node, + Symbol: (IMethodSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))) + .Where(static item => item.Symbol is not null && + item.Symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(ShaderMethodAttribute).FullName))!; - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - SemanticModelProvider semanticModel = new(context.Compilation); - - try + // Get the source info for each method + IncrementalValuesProvider> methodSourceInfoWithErrors = + structDeclarations + .Combine(context.CompilationProvider) + .Select(static (item, token) => { - OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol); - } - catch - { - context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol); - } - } + HlslMethodSourceInfo sourceInfo = Execute.GetData( + item.Right, + item.Left.Syntax, + item.Left.Symbol, + out ImmutableArray diagnostics); + + return new Result(sourceInfo, diagnostics); + }); + + // Output the diagnostics + context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors)); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider methodSourceInfo = + methodSourceInfoWithErrors + .Select(static (item, token) => item.Value) + .WithComparer(HlslMethodSourceInfo.Comparer.Default); + + // Generate the [ShaderMethodSource] attributes + context.RegisterSourceOutput(methodSourceInfo, static (context, item) => + { + CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item); + string filename = item.MetadataName.Replace('`', '-').Replace('+', '.'); + + context.AddSource(filename, SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// - /// Processes a given target method. + /// A helper with all logic to generate the attribute declarations. /// - /// The input instance to use. - /// The node to process. - /// The with metadata on the types being processed. - /// The for . - private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol) + private static class Execute { - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); - var processedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes); - var processedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions); - - // Create the compilation unit with the source attribute - var source = - CompilationUnit().AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(NestedArrayExpression(processedTypes)), - AttributeArgument(NestedArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants))))) - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - // Add the method source attribute - context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of processed methods from a target method declaration. - /// - /// The current generator context in use. - /// The instance for the current method. - /// The instance for the method to process. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of processed methods in (main method and all captured methods). - [Pure] - private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods( - GeneratorExecutionContext context, - MethodDeclarationSyntax methodDeclaration, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); - - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, diagnostics); - - foreach (Diagnostic diagnostic in diagnostics.ToImmutable()) + /// + /// Processes a given target method. + /// + /// The input object currently in use. + /// The node to process. + /// The instance for the current method. + /// The resulting diagnostics from the processing operation. + public static HlslMethodSourceInfo GetData( + Compilation compilation, + MethodDeclarationSyntax methodDeclaration, + IMethodSymbol methodSymbol, + out ImmutableArray diagnostics) { - context.ReportDiagnostic(diagnostic); + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // Explore the syntax tree and extract the processed info + var semanticModel = new SemanticModelProvider(compilation); + var (entryPoint, dependentMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, constantDefinitions, out diagnostics); + var definedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes); + var definedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions); + + return new( + methodSymbol.GetFullMetadataName(includeParameters: true), + entryPoint, + definedTypes, + definedConstants, + dependentMethods); } - // Rewrite the method syntax tree - var targetMethod = shaderSourceRewriter - .Visit(methodDeclaration)! - .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) - .WithoutTrivia() - .NormalizeWhitespace(eol: "\n") - .ToFullString(); - - List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count); - - // Emit the extracted local functions - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + /// + /// Gets a sequence of processed methods from a target method declaration. + /// + /// The instance for the current method. + /// The instance for the method to process. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// The resulting diagnostics from the processing operation. + /// A sequence of processed methods in (main method and all captured methods). + [Pure] + private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( + MethodDeclarationSyntax methodDeclaration, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + out ImmutableArray diagnostics) { - processedMethods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, builder); + + diagnostics = builder.ToImmutable(); + + // Rewrite the method syntax tree + var targetMethod = shaderSourceRewriter + .Visit(methodDeclaration)! + .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) + .WithoutTrivia() + .NormalizeWhitespace(eol: "\n") + .ToFullString(); + + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(shaderSourceRewriter.LocalFunctions.Count); + + // Emit the extracted local functions + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + // Emit the discovered static methods + foreach (var staticMethod in staticMethods.Values) + { + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (targetMethod, methods.ToImmutable()); } - // Emit the discovered static methods - foreach (var staticMethod in staticMethods.Values) + /// + /// Creates a instance with the processed attribute. + /// + /// The input instance to use. + public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo) { - processedMethods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + return + CompilationUnit().AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))), + AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)), + AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)), + AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants))))) + .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) + .NormalizeWhitespace(eol: "\n"); } - - return (targetMethod, processedMethods); } } From 771f8515c712469d7eba2e5fd0244d489037370b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 14:29:08 +0100 Subject: [PATCH 34/36] Remove leftover code and diagnostics --- .../AnalyzerReleases.Shipped.md | 13 ++-- .../Diagnostics/DiagnosticDescriptors.cs | 68 +++---------------- .../Extensions/ISymbolExtensions.cs | 11 --- .../DiagnosticsTests.cs | 24 +++---- 4 files changed, 27 insertions(+), 89 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 9507ad4e..74fadd53 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -43,16 +43,13 @@ CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentatio CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0037 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0038 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0039 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0040 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0041 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0048 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0049 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0050 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0051 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 1e5cf347..7f11ded0 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -496,59 +496,11 @@ internal static class DiagnosticDescriptors description: "String literal expressions cannot be used in a compute shader.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator AutoConstructorGenerator failed to execute on type {0}, and its constructor might not be available". - /// - /// - public static readonly DiagnosticDescriptor AutoConstructorGeneratorError = new( - id: "CMPS0037", - title: $"Internal error for {nameof(AutoConstructorGenerator)}", - messageFormat: $"The generator {nameof(AutoConstructorGenerator)} failed to execute on type {{0}}, and its constructor might not be available", - category: typeof(AutoConstructorGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(AutoConstructorGenerator)} generator encountered an error while processing a type, and its constructor might not be available. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". - /// - /// - public static readonly DiagnosticDescriptor IShaderGeneratorError = new( - id: "CMPS0040", - title: $"Internal error for {nameof(IShaderGenerator)}", - messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IShaderGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator ShaderMethodSourceGenerator failed to execute on method {0}, and using it in a shader might result in a runtime crash". - /// - /// - public static readonly DiagnosticDescriptor ShaderMethodSourceGeneratorError = new( - id: "CMPS0041", - title: $"Internal error for {nameof(ShaderMethodSourceGenerator)}", - messageFormat: $"The generator {nameof(ShaderMethodSourceGenerator)} failed to execute on method {{0}}, and using it in a shader might result in a runtime crash", - category: typeof(ShaderMethodSourceGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(ShaderMethodSourceGenerator)} generator encountered an error while processing a method, and using it in a shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - /// /// Gets a for an incorrect matrix swizzling property argument. /// public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new( - id: "CMPS0042", + id: "CMPS0037", title: "Non constant matrix swizzled property argument", messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants", category: typeof(ShaderMethodSourceGenerator).FullName, @@ -564,7 +516,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new( - id: "CMPS0043", + id: "CMPS0038", title: "Invalid shader static field type", messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)", category: typeof(IComputeShader).FullName, @@ -577,7 +529,7 @@ internal static class DiagnosticDescriptors /// Gets a for an invalid usage. /// public static readonly DiagnosticDescriptor InvalidDispatchSizeUsage = new( - id: "CMPS0044", + id: "CMPS0039", title: "Invalid DispatchSize usage", messageFormat: "The DispatchSize type can only be used within the main body of a compute shader", category: typeof(IComputeShader).FullName, @@ -590,7 +542,7 @@ internal static class DiagnosticDescriptors /// Gets a for a property declaration. /// public static readonly DiagnosticDescriptor PropertyDeclaration = new( - id: "CMPS0045", + id: "CMPS0040", title: "Property declaration", messageFormat: "Property declarations cannot be used in a compute shader", category: typeof(IComputeShader).FullName, @@ -606,7 +558,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new( - id: "CMPS0046", + id: "CMPS0041", title: "Shader dispatch data size exceeded", messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources", category: typeof(IComputeShader).FullName, @@ -622,7 +574,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor MultipleShaderTypesImplemented = new( - id: "CMPS0047", + id: "CMPS0042", title: "Multiple shader implementations for type declaration", messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface", category: typeof(IShaderGenerator).FullName, @@ -638,7 +590,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new( - id: "CMPS0048", + id: "CMPS0043", title: "Embedded bytecode for dynamic shader", messageFormat: $"The shader of type {{0}} cannot be precompiled, as it is dynamic (it captures delegate fields)", category: typeof(IShaderGenerator).FullName, @@ -654,7 +606,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeThreadIds = new( - id: "CMPS0049", + id: "CMPS0044", title: "Invalid thread ids for shader with embedded bytecode", messageFormat: $"The shader of type {{0}} is annotated with invalid thread ids values ({{1}}, {{2}}, {{3}})", category: typeof(IShaderGenerator).FullName, @@ -670,7 +622,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new( - id: "CMPS0050", + id: "CMPS0045", title: "Embedded bytecode compilation failed due to Win32 exception", messageFormat: $"The shader of type {{0}} failed to compile due to a Win32 exception (HRESULT: {{1:X8}}, Message: \"{{2}}\")", category: typeof(IShaderGenerator).FullName, @@ -686,7 +638,7 @@ internal static class DiagnosticDescriptors /// /// public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithHlslCompilationException = new( - id: "CMPS0051", + id: "CMPS0046", title: "Embedded bytecode compilation failed due to an HLSL compiler error", messageFormat: $"The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: \"{{1}}\")", category: typeof(IShaderGenerator).FullName, diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs index aade5e79..dac1c8f9 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -116,17 +116,6 @@ internal static class ISymbolExtensions return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.'); } - /// - /// Gets a valid filename for a target symbol and generator type. - /// - /// The symbol being processed. - /// A filename in the form "<SYMBOL_FULLNAME>" - [Pure] - public static string GetGeneratedFileName(this IMethodSymbol symbol) - { - return symbol.GetFullMetadataName(true).Replace('`', '-').Replace('+', '.'); - } - /// /// Tracks an instance and returns an HLSL compatible object. /// diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 1943477d..4cb19f28 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -167,7 +167,7 @@ public class DiagnosticsTests [DataRow(nameof(GroupIds), "CMPS0007")] [DataRow(nameof(GroupSize), "CMPS0008")] [DataRow(nameof(GridIds), "CMPS0009")] - [DataRow(nameof(DispatchSize), "CMPS0044")] + [DataRow(nameof(DispatchSize), "CMPS0039")] public void InvalidDispatchInfoUsage_LocalFunction(string typeName, string diagnosticsId) { string source = $@" @@ -202,7 +202,7 @@ public class DiagnosticsTests [DataRow(nameof(GroupIds), "CMPS0007")] [DataRow(nameof(GroupSize), "CMPS0008")] [DataRow(nameof(GridIds), "CMPS0009")] - [DataRow(nameof(DispatchSize), "CMPS0044")] + [DataRow(nameof(DispatchSize), "CMPS0039")] public void InvalidDispatchInfoUsage_StaticMethod(string typeName, string diagnosticsId) { string source = $@" @@ -1194,7 +1194,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0042"); + VerifyGeneratedDiagnostics(source, "CMPS0037"); } [TestMethod] @@ -1222,7 +1222,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0043"); + VerifyGeneratedDiagnostics(source, "CMPS0038"); } [TestMethod] @@ -1250,7 +1250,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1281,7 +1281,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1309,7 +1309,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1337,7 +1337,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1371,7 +1371,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0046"); + VerifyGeneratedDiagnostics(source, "CMPS0041"); } [TestMethod] @@ -1396,7 +1396,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0047"); + VerifyGeneratedDiagnostics(source, "CMPS0042"); } [TestMethod] @@ -1430,7 +1430,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0048"); + VerifyGeneratedDiagnostics(source, "CMPS0043"); } [TestMethod] @@ -1469,7 +1469,7 @@ public class DiagnosticsTests }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0049"); + VerifyGeneratedDiagnostics(source, "CMPS0044"); } /// From 44b7620d4add3d1d4bf54e1a92bceb62698c7e79 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 7 Dec 2021 20:24:18 +0100 Subject: [PATCH 35/36] Fix [SkipLocalsInit] lookup in source generator --- src/ComputeSharp.SourceGenerators/IShaderGenerator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 50af3d93..a9b62af0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -27,7 +27,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator context.CompilationProvider .Select(static (compilation, token) => compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && - compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null); + compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute") is not null); // Get all declared struct types and their type symbols IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations = From c1dab2cebf142979414f3ba08c2831323b788620 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 8 Dec 2021 11:57:09 +0100 Subject: [PATCH 36/36] Minor code style tweaks --- src/ComputeSharp.SourceGenerators/IShaderGenerator.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index a9b62af0..aabfe271 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -84,13 +84,12 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator out int root32BitConstantCount, out ImmutableArray dispatchDataDiagnostics); - Result dispatchDataInfo = new(new DispatchDataInfo( + DispatchDataInfo dispatchDataInfo = new( item.Left.Hierarchy, item.Left.Type, fieldInfos, resourceCount, - root32BitConstantCount), - dispatchDataDiagnostics); + root32BitConstantCount); // BuildHlslString() info HlslShaderSourceInfo hlslSourceInfo = BuildHlslString.GetInfo( @@ -106,7 +105,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator out ImmutableArray threadIdsDiagnostics); return ( - dispatchDataInfo, + new Result(dispatchDataInfo, dispatchDataDiagnostics), new Result(hlslSourceInfo, hlslSourceDiagnostics), new Result(threadIds, threadIdsDiagnostics)); });