From ba1d3b7f82eac7115f6d73947536d9a152030b31 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 5 Oct 2022 21:51:50 +0200 Subject: [PATCH 1/8] Port ObjectPool and ImmutableArrayBuilder --- .../ComputeSharp.SourceGeneration.projitems | 2 + .../Helpers/ImmutableArrayBuilder{T}.cs | 89 ++++++++++ .../Helpers/ObjectPool{T}.cs | 163 ++++++++++++++++++ 3 files changed, 254 insertions(+) create mode 100644 src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs create mode 100644 src/ComputeSharp.SourceGeneration/Helpers/ObjectPool{T}.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 83b77644..f7dcbdd3 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -18,6 +18,8 @@ + + diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs new file mode 100644 index 00000000..bfd2ce02 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -0,0 +1,89 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A helper type to build instances with pooled buffers. +/// +/// The type of items to create arrays for. +internal ref struct ImmutableArrayBuilder +{ + /// + /// The shared instance to share objects. + /// + private static readonly ObjectPool.Builder> sharedObjectPool = new(ImmutableArray.CreateBuilder); + + /// + /// The owner instance. + /// + private readonly ObjectPool.Builder> objectPool; + + /// + /// The rented instance to use. + /// + private ImmutableArray.Builder? builder; + + /// + /// Rents a new pooled instance through a new value. + /// + /// A to interact with the underlying instance. + public static ImmutableArrayBuilder Rent() + { + return new(sharedObjectPool, sharedObjectPool.Allocate()); + } + + /// + /// Creates a new object with the specified parameters. + /// + /// + /// + private ImmutableArrayBuilder(ObjectPool.Builder> objectPool, ImmutableArray.Builder builder) + { + this.objectPool = objectPool; + this.builder = builder; + } + + /// + public readonly int Count + { + get => this.builder!.Count; + } + + /// + public readonly void Add(T item) + { + this.builder!.Add(item); + } + + /// + public readonly ImmutableArray ToImmutable() + { + return this.builder!.ToImmutable(); + } + + /// + public readonly T[] ToArray() + { + return this.builder!.ToArray(); + } + + /// + public void Dispose() + { + ImmutableArray.Builder? builder = this.builder; + + this.builder = null; + + if (builder is not null) + { + builder.Clear(); + + this.objectPool.Free(builder); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ObjectPool{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ObjectPool{T}.cs new file mode 100644 index 00000000..b025cf9f --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/ObjectPool{T}.cs @@ -0,0 +1,163 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// Ported from Roslyn, see: https://github.com/dotnet/roslyn/blob/main/src/Dependencies/PooledObjects/ObjectPool%601.cs. + +using System; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// +/// Generic implementation of object pooling pattern with predefined pool size limit. The main purpose +/// is that limited number of frequently used objects can be kept in the pool for further recycling. +/// +/// +/// Notes: +/// +/// +/// It is not the goal to keep all returned objects. Pool is not meant for storage. If there +/// is no space in the pool, extra returned objects will be dropped. +/// +/// +/// It is implied that if object was obtained from a pool, the caller will return it back in +/// a relatively short time. Keeping checked out objects for long durations is ok, but +/// reduces usefulness of pooling. Just new up your own. +/// +/// +/// +/// +/// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice. +/// Rationale: if there is no intent for reusing the object, do not use pool - just use "new". +/// +/// +/// The type of objects to pool. +internal sealed class ObjectPool + where T : class +{ + /// + /// The factory is stored for the lifetime of the pool. We will call this only when pool needs to + /// expand. compared to "new T()", Func gives more flexibility to implementers and faster than "new T()". + /// + private readonly Func factory; + + /// + /// The array of cached items. + /// + private readonly Element[] items; + + /// + /// Storage for the pool objects. The first item is stored in a dedicated field + /// because we expect to be able to satisfy most requests from it. + /// + private T? firstItem; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input factory to produce items. + public ObjectPool(Func factory) + : this(factory, Environment.ProcessorCount * 2) + { + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input factory to produce items. + /// The pool size to use. + public ObjectPool(Func factory, int size) + { + this.factory = factory; + this.items = new Element[size - 1]; + } + + /// + /// Produces a instance. + /// + /// The returned item to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Allocate() + { + T? item = this.firstItem; + + if (item is null || item != Interlocked.CompareExchange(ref this.firstItem, null, item)) + { + item = AllocateSlow(); + } + + return item; + } + + /// + /// Returns a given instance to the pool. + /// + /// The instance to return. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Free(T obj) + { + if (this.firstItem is null) + { + this.firstItem = obj; + } + else + { + FreeSlow(obj); + } + } + + /// + /// Allocates a new item. + /// + /// The returned item to use. + [MethodImpl(MethodImplOptions.NoInlining)] + private T AllocateSlow() + { + foreach (ref Element element in this.items.AsSpan()) + { + T? instance = element.Value; + + if (instance is not null) + { + if (instance == Interlocked.CompareExchange(ref element.Value, null, instance)) + { + return instance; + } + } + } + + return this.factory(); + } + + /// + /// Frees a given item. + /// + /// The item to return to the pool. + [MethodImpl(MethodImplOptions.NoInlining)] + private void FreeSlow(T obj) + { + foreach (ref Element element in this.items.AsSpan()) + { + if (element.Value is null) + { + element.Value = obj; + + break; + } + } + } + + /// + /// A container for a produced item (using a wrapper to avoid covariance checks). + /// + private struct Element + { + /// + /// The value held at the current element. + /// + internal T? Value; + } +} \ No newline at end of file From 48408005664c2b35410ab5ee0eb040fe27c24d62 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 5 Oct 2022 21:52:49 +0200 Subject: [PATCH 2/8] Move SemanticModelProvider type --- .../ComputeSharp.SourceGeneration.Hlsl.projitems | 1 + .../Helpers/SemanticModelProvider.cs | 0 .../ComputeSharp.SourceGeneration.projitems | 1 - 3 files changed, 1 insertion(+), 1 deletion(-) rename src/{ComputeSharp.SourceGeneration => ComputeSharp.SourceGeneration.Hlsl}/Helpers/SemanticModelProvider.cs (100%) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index d609eae6..a7a8d8e5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -12,6 +12,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Helpers/SemanticModelProvider.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SemanticModelProvider.cs similarity index 100% rename from src/ComputeSharp.SourceGeneration/Helpers/SemanticModelProvider.cs rename to src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SemanticModelProvider.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index f7dcbdd3..6adf7894 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -20,7 +20,6 @@ - From f9e75e25266b303d23346716f9d997a7b47cf7e6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 6 Oct 2022 00:06:45 +0200 Subject: [PATCH 3/8] Add more polyfills to ImmutableArrayBuilder --- .../Helpers/ImmutableArrayBuilder{T}.cs | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index bfd2ce02..d682f0cf 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -4,6 +4,8 @@ using System; using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace ComputeSharp.SourceGeneration.Helpers; @@ -60,6 +62,48 @@ internal ref struct ImmutableArrayBuilder this.builder!.Add(item); } + /// + /// Adds the specified items to the end of the array. + /// + /// The items to add at the end of the array. + public readonly unsafe void AddRange(ReadOnlySpan items) + { + if (items.IsEmpty) + { + return; + } + + int offset = this.builder!.Count; + + this.builder!.Count += items.Length; + + ref T firstItem = ref Unsafe.AsRef(in this.builder!.ItemRef(offset)); + + if (typeof(T) == typeof(char)) + { + int sizeInBytes = checked(items.Length * Unsafe.SizeOf()); + + fixed (void* source = &Unsafe.As(ref MemoryMarshal.GetReference(items))) + fixed (void* destination = &Unsafe.As(ref firstItem)) + { + new ReadOnlySpan(source, sizeInBytes).CopyTo(new Span(destination, sizeInBytes)); + } + } + else + { + ref T lastItem = ref Unsafe.Add(ref firstItem, items.Length); + ref T sourceItem = ref MemoryMarshal.GetReference(items); + + while (Unsafe.IsAddressLessThan(ref firstItem, ref lastItem)) + { + firstItem = sourceItem; + + firstItem = ref Unsafe.Add(ref firstItem, 1); + sourceItem = ref Unsafe.Add(ref sourceItem, 1); + } + } + } + /// public readonly ImmutableArray ToImmutable() { @@ -72,6 +116,21 @@ internal ref struct ImmutableArrayBuilder return this.builder!.ToArray(); } + /// + public override readonly unsafe string ToString() + { + if (typeof(T) == typeof(char) && + this.builder!.Count > 0) + { + fixed (char* p = &Unsafe.As(ref Unsafe.AsRef(in this.builder!.ItemRef(0)))) + { + return new ReadOnlySpan(p, this.builder!.Count).ToString(); + } + } + + return this.builder!.ToString(); + } + /// public void Dispose() { From a751d128a34bb73f9843ed282215cdb41bb0c25e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 7 Oct 2022 12:37:29 +0200 Subject: [PATCH 4/8] Optimize ImmutableArrayBuilder type --- .../Helpers/ImmutableArrayBuilder{T}.cs | 196 +++++++++++------- 1 file changed, 122 insertions(+), 74 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index d682f0cf..a87e467b 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -5,35 +5,34 @@ using System; using System.Collections.Immutable; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; namespace ComputeSharp.SourceGeneration.Helpers; /// -/// A helper type to build instances with pooled buffers. +/// A helper type to build sequences of values with pooled buffers. /// -/// The type of items to create arrays for. +/// The type of items to create sequences for. internal ref struct ImmutableArrayBuilder { /// - /// The shared instance to share objects. + /// The shared instance to share objects. /// - private static readonly ObjectPool.Builder> sharedObjectPool = new(ImmutableArray.CreateBuilder); + private static readonly ObjectPool sharedObjectPool = new(static () => new Writer()); /// /// The owner instance. /// - private readonly ObjectPool.Builder> objectPool; + private readonly ObjectPool objectPool; /// - /// The rented instance to use. + /// The rented instance to use. /// - private ImmutableArray.Builder? builder; + private Writer? writer; /// - /// Rents a new pooled instance through a new value. + /// Creates a value with a pooled underlying data writer. /// - /// A to interact with the underlying instance. + /// A instance to write data to. public static ImmutableArrayBuilder Rent() { return new(sharedObjectPool, sharedObjectPool.Allocate()); @@ -42,107 +41,156 @@ internal ref struct ImmutableArrayBuilder /// /// Creates a new object with the specified parameters. /// - /// - /// - private ImmutableArrayBuilder(ObjectPool.Builder> objectPool, ImmutableArray.Builder builder) + /// The target to return to. + /// The target data writer to use. + private ImmutableArrayBuilder(ObjectPool objectPool, Writer writer) { this.objectPool = objectPool; - this.builder = builder; - } - - /// - public readonly int Count - { - get => this.builder!.Count; + this.writer = writer; } /// public readonly void Add(T item) { - this.builder!.Add(item); + this.writer!.Add(item); } /// /// Adds the specified items to the end of the array. /// /// The items to add at the end of the array. - public readonly unsafe void AddRange(ReadOnlySpan items) + public readonly void AddRange(ReadOnlySpan items) { - if (items.IsEmpty) - { - return; - } - - int offset = this.builder!.Count; - - this.builder!.Count += items.Length; - - ref T firstItem = ref Unsafe.AsRef(in this.builder!.ItemRef(offset)); - - if (typeof(T) == typeof(char)) - { - int sizeInBytes = checked(items.Length * Unsafe.SizeOf()); - - fixed (void* source = &Unsafe.As(ref MemoryMarshal.GetReference(items))) - fixed (void* destination = &Unsafe.As(ref firstItem)) - { - new ReadOnlySpan(source, sizeInBytes).CopyTo(new Span(destination, sizeInBytes)); - } - } - else - { - ref T lastItem = ref Unsafe.Add(ref firstItem, items.Length); - ref T sourceItem = ref MemoryMarshal.GetReference(items); - - while (Unsafe.IsAddressLessThan(ref firstItem, ref lastItem)) - { - firstItem = sourceItem; - - firstItem = ref Unsafe.Add(ref firstItem, 1); - sourceItem = ref Unsafe.Add(ref sourceItem, 1); - } - } + this.writer!.AddRange(items); } /// public readonly ImmutableArray ToImmutable() { - return this.builder!.ToImmutable(); + T[] array = this.writer!.WrittenSpan.ToArray(); + + return Unsafe.As>(ref array); } /// public readonly T[] ToArray() { - return this.builder!.ToArray(); + return this.writer!.WrittenSpan.ToArray(); } /// - public override readonly unsafe string ToString() + public override readonly string ToString() { - if (typeof(T) == typeof(char) && - this.builder!.Count > 0) - { - fixed (char* p = &Unsafe.As(ref Unsafe.AsRef(in this.builder!.ItemRef(0)))) - { - return new ReadOnlySpan(p, this.builder!.Count).ToString(); - } - } - - return this.builder!.ToString(); + return this.writer!.WrittenSpan.ToString(); } /// public void Dispose() { - ImmutableArray.Builder? builder = this.builder; + Writer? writer = this.writer; - this.builder = null; + this.writer = null; - if (builder is not null) + if (writer is not null) { - builder.Clear(); + writer.Clear(); - this.objectPool.Free(builder); + this.objectPool.Free(writer); + } + } + + /// + /// A class handling the actual buffer writing. + /// + private sealed class Writer + { + /// + /// The underlying array. + /// + private T[] array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Creates a new instance with the specified parameters. + /// + public Writer() + { + this.array = new T[8]; + this.index = 0; + } + + /// + /// Gets the data written to the underlying buffer so far, as a . + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new(this.array, 0, this.index); + } + + /// + public void Add(T value) + { + EnsureCapacity(1); + + this.array[this.index++] = value; + } + + /// + public void AddRange(ReadOnlySpan items) + { + EnsureCapacity(items.Length); + + items.CopyTo(this.array.AsSpan(this.index)); + + this.index += items.Length; + } + + /// + /// Clears the items in the current writer. + /// + public void Clear() + { + if (typeof(T) != typeof(char)) + { + this.array.AsSpan(0, this.index).Clear(); + } + + this.index = 0; + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureCapacity(int requestedSize) + { + if (requestedSize > this.array.Length - this.index) + { + ResizeBuffer(requestedSize); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.NoInlining)] + private void ResizeBuffer(int sizeHint) + { + int minimumSize = this.index + sizeHint; + int requestedSize = Math.Max(this.array.Length * 2, minimumSize); + + T[] newArray = new T[requestedSize]; + + Array.Copy(this.array, newArray, this.index); + + this.array = newArray; } } } \ No newline at end of file From a15fce2a54d0e24679d4a9c4b4c7fa656d027d22 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 7 Oct 2022 12:55:59 +0200 Subject: [PATCH 5/8] Use ImmutableArrayBuilder for bytecode text --- .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 - ...aderGenerator.CreateLoadBytecodeMethod.Syntax.cs | 13 ++++++------- .../Helpers/ImmutableArrayBuilder{T}.cs | 10 +++++++++- .../ComputeSharp.SourceGenerators.csproj | 1 - ...aderGenerator.CreateLoadBytecodeMethod.Syntax.cs | 12 ++++++------ 5 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index 4b3aee1f..d6125b6b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -63,7 +63,6 @@ - diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 32b042eb..fea4c8b3 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -2,9 +2,9 @@ using System.Globalization; using System.Linq; using System.Text; -using ComputeSharp.__Internals; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -216,18 +216,17 @@ partial class ID2D1ShaderGenerator /// A formatted with the serialized data. internal 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); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); - builder.Append(formattedBytes[bytecode[0]]); + builder.AddRange(formattedBytes[bytecode[0]].AsSpan()); foreach (byte b in bytecode.Slice(1)) { - builder.Append(", "); - builder.Append(formattedBytes[b]); + builder.AddRange(", ".AsSpan()); + builder.AddRange(formattedBytes[b].AsSpan()); } - return builder.WrittenSpan.ToString(); + return builder.ToString(); } } } diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index a87e467b..cb98574e 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -119,7 +119,15 @@ internal ref struct ImmutableArrayBuilder /// public Writer() { - this.array = new T[8]; + if (typeof(T) == typeof(char)) + { + this.array = new T[1024]; + } + else + { + this.array = new T[8]; + } + this.index = 0; } diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 5942d30d..fde18d60 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -82,7 +82,6 @@ - diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 37ecf4dc..544c1189 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -1,6 +1,7 @@ using System; using System.Text; using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -237,18 +238,17 @@ partial class IShaderGenerator /// 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); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); - builder.Append(formattedBytes[bytecode[0]]); + builder.AddRange(formattedBytes[bytecode[0]].AsSpan()); foreach (byte b in bytecode.Slice(1)) { - builder.Append(", "); - builder.Append(formattedBytes[b]); + builder.AddRange(", ".AsSpan()); + builder.AddRange(formattedBytes[b].AsSpan()); } - return builder.WrittenSpan.ToString(); + return builder.ToString(); } } } From eb34817073cbf9ce04b6ed73ec2604939c6fd56a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 7 Oct 2022 14:00:33 +0200 Subject: [PATCH 6/8] Remove allocations when checking duplicate resource indices --- ...rator.CreateLoadInputDescriptionsMethod.cs | 16 +++++++++++----- ...teLoadResourceTextureDescriptionsMethod.cs | 19 ++++++++++++++----- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index ca9a12e4..c1b9182c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; @@ -71,14 +70,21 @@ partial class ID2D1ShaderGenerator return; } - HashSet inputDescriptionIndices = new(inputDescriptionsBuilder.Select(description => description.Index)); + Span selectedInputDescriptionIndices = stackalloc bool[8]; // All input description indices must be unique - if (inputDescriptionIndices.Count != inputDescriptionsBuilder.Count) + foreach (InputDescription inputDescription in inputDescriptionsBuilder) { - diagnostics.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); + ref bool isInputDescriptionIndexUsed = ref selectedInputDescriptionIndices[(int)inputDescription.Index]; - return; + if (isInputDescriptionIndexUsed) + { + diagnostics.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + isInputDescriptionIndexUsed = true; } inputDescriptions = inputDescriptionsBuilder.ToImmutable(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index 3a128e56..c9fd1576 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System; using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; @@ -99,12 +99,21 @@ partial class ID2D1ShaderGenerator return; } - HashSet resourceTextureIndices = new(resourceTextureInfos.Where(info => info.Index.HasValue).Select(info => info.Index!.Value)); + Span selectedResourceTextureIndices = stackalloc bool[16]; - // All input description indices must be unique - if (resourceTextureIndices.Count != resourceTextureInfos.Count(info => info.Index.HasValue)) + // All input description indices must be unique (also take this path for invalid indices) + foreach ((int? index, _) in resourceTextureInfos) { - diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol); + ref bool isResourceTextureIndexUsed = ref selectedResourceTextureIndices[index ?? 0]; + + if (isResourceTextureIndexUsed) + { + diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + isResourceTextureIndexUsed = true; } } } From d4b1e71c39d27c402334ff14e3a55e6006013772 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 7 Oct 2022 14:18:32 +0200 Subject: [PATCH 7/8] Remove allocations when validating D2D1 input indices --- ...haderGenerator.CreateGetInputTypeMethod.cs | 44 +++++++++++++------ 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index d9583b49..1245ba01 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -83,31 +82,48 @@ partial class ID2D1ShaderGenerator return; } - HashSet inputSimpleIndicesAsSet = new(inputSimpleIndicesBuilder); - HashSet inputComplexIndicesAsSet = new(inputComplexIndicesBuilder); + Span selectedSimpleInputIndices = stackalloc bool[8]; + Span selectedComplexInputIndices = stackalloc bool[8]; // All simple indices must be unique - if (inputSimpleIndicesAsSet.Count != inputSimpleIndicesBuilder.Count) + foreach (int index in inputSimpleIndicesBuilder) { - diagnostics.Add(RepeatedD2DInputSimpleIndices, structDeclarationSymbol, structDeclarationSymbol); + ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index]; - return; + if (isInputIndexUsed) + { + diagnostics.Add(RepeatedD2DInputSimpleIndices, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + isInputIndexUsed = true; } - // All complex indices must be unique - if (inputComplexIndicesAsSet.Count != inputComplexIndicesBuilder.Count) + // All complex indices must be unique as well + foreach (int index in inputComplexIndicesBuilder) { - diagnostics.Add(RepeatedD2DInputComplexIndices, structDeclarationSymbol, structDeclarationSymbol); + ref bool isInputIndexUsed = ref selectedComplexInputIndices[index]; - return; + if (isInputIndexUsed) + { + diagnostics.Add(RepeatedD2DInputComplexIndices, structDeclarationSymbol, structDeclarationSymbol); + + return; + } + + isInputIndexUsed = true; } // Simple and complex indices can't have indices in common - if (inputSimpleIndicesAsSet.Intersect(inputComplexIndicesAsSet).Any()) + for (int i = 0; i < rawInputCount; i++) { - diagnostics.Add(InvalidSimpleAndComplexIndicesCombination, structDeclarationSymbol, structDeclarationSymbol); + if (selectedSimpleInputIndices[i] && selectedComplexInputIndices[i]) + { + diagnostics.Add(InvalidSimpleAndComplexIndicesCombination, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } // Build the combined input types list now that inputs have been validated @@ -120,7 +136,7 @@ partial class ID2D1ShaderGenerator // input is present in the set of explicitly simple inputs. These values will map to // values from D2D1PixelShaderInputType, which has Simple and Complex as members. // So, simple inputs map to 0, and complex inputs map to 1. - combinedBuilder.Add(inputSimpleIndicesAsSet.Contains(i) ? 0u : 1u); + combinedBuilder.Add(selectedSimpleInputIndices[i] ? 0u : 1u); } combinedInputTypes = combinedBuilder.MoveToImmutable(); From 883d99ca9fcf2ceac8e0db9bfbfbac1f0b7913df Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 7 Oct 2022 14:43:42 +0200 Subject: [PATCH 8/8] Use pooled array builders in all generators --- .../AutoConstructorGenerator.cs | 10 +- .../D2DPixelShaderSourceGenerator.Execute.cs | 9 +- .../D2DPixelShaderSourceGenerator.cs | 3 +- ...erGenerator.CreateBuildHlslSourceMethod.cs | 32 +++-- ...haderGenerator.CreateGetInputTypeMethod.cs | 36 +++-- ...InitializeFromDispatchDataMethod.Syntax.cs | 3 +- ...haderGenerator.CreateLoadBytecodeMethod.cs | 3 +- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 61 ++++---- ...rGenerator.CreateLoadDispatchDataMethod.cs | 7 +- ...reateLoadInputDescriptionsMethod.Syntax.cs | 7 +- ...rator.CreateLoadInputDescriptionsMethod.cs | 18 ++- ...esourceTextureDescriptionsMethod.Syntax.cs | 7 +- ...teLoadResourceTextureDescriptionsMethod.cs | 36 +++-- .../ID2D1ShaderGenerator.cs | 3 +- .../SyntaxRewriters/HlslSourceRewriter.cs | 5 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 5 +- .../SyntaxRewriters/StaticFieldRewriter.cs | 3 +- .../Extensions/DiagnosticsExtensions.cs | 5 +- .../Helpers/ImmutableArrayBuilder{T}.cs | 69 ++++++++- .../Models/HierarchyInfo.cs | 2 +- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 3 +- ...erGenerator.CreateBuildHlslSourceMethod.cs | 37 ++--- ...haderGenerator.CreateLoadBytecodeMethod.cs | 3 +- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 133 +++++++++--------- ...rGenerator.CreateLoadDispatchDataMethod.cs | 7 +- ...CreateLoadDispatchMetadataMethod.Syntax.cs | 3 +- ...erator.CreateLoadDispatchMetadataMethod.cs | 4 +- .../IShaderGenerator.cs | 3 +- .../ShaderMethodSourceGenerator.cs | 6 +- src/ComputeSharp/Shaders/ComputeContext.cs | 1 - .../ComputeSharp.Tests/ShaderRewriterTests.cs | 1 - 31 files changed, 320 insertions(+), 205 deletions(-) diff --git a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs index 6d78bed9..9d573fd3 100644 --- a/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.Core.SourceGenerators/AutoConstructorGenerator.cs @@ -1,8 +1,8 @@ -using System.Collections.Immutable; -using System.Linq; +using System.Linq; using System.Text; using ComputeSharp.Core.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -66,8 +66,8 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator /// The instance for . public static ConstructorInfo GetData(INamedTypeSymbol structDeclarationSymbol) { - ImmutableArray.Builder parameters = ImmutableArray.CreateBuilder(); - ImmutableArray.Builder defaulted = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder parameters = ImmutableArrayBuilder.Rent(); + using ImmutableArrayBuilder defaulted = ImmutableArrayBuilder.Rent(); foreach (IFieldSymbol fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -93,7 +93,7 @@ public sealed class AutoConstructorGenerator : IIncrementalGenerator } } - return new(parameters.ToImmutableArray(), defaulted.ToImmutableArray()); + return new(parameters.ToImmutable(), defaulted.ToImmutable()); } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index e475010c..b346673b 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -7,6 +7,7 @@ using ComputeSharp.D2D1.Exceptions; using ComputeSharp.D2D1.Shaders.Translation; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using TerraFX.Interop.DirectX; @@ -29,7 +30,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The HLSL source to compile, if present. - public static string? GetInvalidReturnType(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static string? GetInvalidReturnType(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { if (!(methodSymbol.ReturnType is INamedTypeSymbol { @@ -58,7 +59,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The HLSL source to compile, if present. - public static string GetHlslSource(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static string GetHlslSource(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { _ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData); @@ -80,7 +81,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The shader profile to use to compile the shader, if present. - public static D2D1ShaderProfile GetShaderProfile(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static D2D1ShaderProfile GetShaderProfile(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DShaderProfileAttribute", out AttributeData? attributeData)) { @@ -107,7 +108,7 @@ partial class D2DPixelShaderSourceGenerator /// The collection of produced instances. /// The input instance to process. /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions GetCompileOptions(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + public static D2D1CompileOptions GetCompileOptions(ImmutableArrayBuilder diagnostics, IMethodSymbol methodSymbol) { if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index 431050d1..0d96cb7e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -32,7 +33,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato MethodDeclarationSyntax methodDeclaration = (MethodDeclarationSyntax)context.TargetNode; IMethodSymbol methodSymbol = (IMethodSymbol)context.TargetSymbol; - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // Get the processed HLSL first and check for cancellation string hlslSource = Execute.GetHlslSource(diagnostics, methodSymbol); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs index 4b3ee9b2..f9687982 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -38,7 +38,7 @@ partial class ID2D1ShaderGenerator /// The indicess of the complex shader inputs. /// The HLSL source for the shader. public static string GetHlslSource( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -102,14 +102,14 @@ partial class ID2D1ShaderGenerator /// The sequence of captured fields in . /// The sequence of captured resource textures in . private static void GetInstanceFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types, out ImmutableArray<(string Name, string HlslType)> valueFields, out ImmutableArray<(string Name, string HlslType, int Index)> resourceTextureFields) { - ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); - ImmutableArray<(string, string, int)>.Builder resourceTextures = ImmutableArray.CreateBuilder<(string, string, int)>(); + using ImmutableArrayBuilder<(string, string)> values = ImmutableArrayBuilder<(string, string)>.Rent(); + using ImmutableArrayBuilder<(string, string, int)> resourceTextures = ImmutableArrayBuilder<(string, string, int)>.Rent(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -193,7 +193,7 @@ partial class ID2D1ShaderGenerator /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -201,7 +201,7 @@ partial class ID2D1ShaderGenerator IDictionary constantDefinitions, out bool needsD2D1RequiresScenePosition) { - ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + using ImmutableArrayBuilder<(string, string, string?)> builder = ImmutableArrayBuilder<(string, string, string?)>.Rent(); needsD2D1RequiresScenePosition = false; @@ -264,7 +264,7 @@ partial class ID2D1ShaderGenerator /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, @@ -281,7 +281,8 @@ partial class ID2D1ShaderGenerator select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + + using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); needsD2D1RequiresScenePosition = false; @@ -359,7 +360,7 @@ partial class ID2D1ShaderGenerator /// A sequence of discovered constants to declare in the shader. private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); foreach (var constant in constantDefinitions) { @@ -369,7 +370,7 @@ partial class ID2D1ShaderGenerator builder.Add((constantName, constant.Value)); } - return builder.MoveToImmutable(); + return builder.ToImmutable(); } /// @@ -381,13 +382,14 @@ partial class ID2D1ShaderGenerator /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types, IReadOnlyDictionary instanceMethods) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); - IReadOnlyCollection invalidTypes; + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); + + IReadOnlyCollection invalidTypes; // Process the discovered types foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) @@ -449,7 +451,7 @@ partial class ID2D1ShaderGenerator /// /// The collection of produced instances. /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { foreach (var memberSymbol in structDeclarationSymbol.GetMembers()) { @@ -475,7 +477,7 @@ partial class ID2D1ShaderGenerator /// Whether the shader type is declaring the need for scene position. /// Whether the shader is using APIs that rely on scene position. private static void ReportInvalidD2DRequiresScenePositionUse( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool requiresScenePosition, bool usesPositionDependentMethods) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index 1245ba01..53bc8909 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -26,7 +26,7 @@ partial class ID2D1ShaderGenerator /// The indices of the complex shader inputs. /// The combined and serialized input types for each available input. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, out int inputCount, out ImmutableArray inputSimpleIndices, @@ -40,8 +40,8 @@ partial class ID2D1ShaderGenerator inputCount = 0; - ImmutableArray.Builder inputSimpleIndicesBuilder = ImmutableArray.CreateBuilder(); - ImmutableArray.Builder inputComplexIndicesBuilder = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder inputSimpleIndicesBuilder = ImmutableArrayBuilder.Rent(); + using ImmutableArrayBuilder inputComplexIndicesBuilder = ImmutableArrayBuilder.Rent(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { @@ -75,18 +75,32 @@ partial class ID2D1ShaderGenerator } // All simple indices must be in range - if (inputSimpleIndicesBuilder.Concat(inputComplexIndicesBuilder).Any(i => (uint)i >= rawInputCount)) + foreach (int index in inputSimpleIndicesBuilder.WrittenSpan) { - diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); + if ((uint)index >= rawInputCount) + { + diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } + } + + // All complex indices must be in range as well + foreach (int index in inputComplexIndicesBuilder.WrittenSpan) + { + if ((uint)index >= rawInputCount) + { + diagnostics.Add(OutOfRangeInputIndex, structDeclarationSymbol, structDeclarationSymbol); + + return; + } } Span selectedSimpleInputIndices = stackalloc bool[8]; Span selectedComplexInputIndices = stackalloc bool[8]; // All simple indices must be unique - foreach (int index in inputSimpleIndicesBuilder) + foreach (int index in inputSimpleIndicesBuilder.WrittenSpan) { ref bool isInputIndexUsed = ref selectedSimpleInputIndices[index]; @@ -101,7 +115,7 @@ partial class ID2D1ShaderGenerator } // All complex indices must be unique as well - foreach (int index in inputComplexIndicesBuilder) + foreach (int index in inputComplexIndicesBuilder.WrittenSpan) { ref bool isInputIndexUsed = ref selectedComplexInputIndices[index]; @@ -127,7 +141,7 @@ partial class ID2D1ShaderGenerator } // Build the combined input types list now that inputs have been validated - ImmutableArray.Builder combinedBuilder = ImmutableArray.CreateBuilder(inputCount); + using ImmutableArrayBuilder combinedBuilder = ImmutableArrayBuilder.Rent(); for (int i = 0; i < inputCount; i++) { @@ -139,7 +153,7 @@ partial class ID2D1ShaderGenerator combinedBuilder.Add(selectedSimpleInputIndices[i] ? 0u : 1u); } - combinedInputTypes = combinedBuilder.MoveToImmutable(); + combinedInputTypes = combinedBuilder.ToImmutable(); } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs index ec17de8f..fc8709d8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInitializeFromDispatchDataMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -50,7 +51,7 @@ partial class ID2D1ShaderGenerator return ImmutableArray.Empty; } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // Insert the fallback for empty shaders. This will generate the following code: // diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index 2661e394..624f9b69 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -9,6 +9,7 @@ using ComputeSharp.D2D1.Exceptions; using ComputeSharp.D2D1.Shaders.Translation; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using TerraFX.Interop.DirectX; @@ -51,7 +52,7 @@ partial class ID2D1ShaderGenerator /// The collection of produced instances. /// The input instance to process. /// The compile options to use to compile the shader, if present. - public static D2D1CompileOptions? GetCompileOptions(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + public static D2D1CompileOptions? GetCompileOptions(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { if (structDeclarationSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index f4f964df..aaace9de 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -63,7 +64,36 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.DefaultKeyword)))))); } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); + + // global::System.Span data = stackalloc byte[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("data")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))))))))))); + + // ref byte r0 = ref data[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("data")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); // Generate loading statements for each captured field foreach (FieldInfo fieldInfo in fieldInfos) @@ -123,35 +153,6 @@ partial class ID2D1ShaderGenerator } } - // global::System.Span data = stackalloc byte[]; - statements.Insert(0, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("data")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes))))))))))); - - // ref byte r0 = ref data[0]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("data")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - // loader.LoadConstantBuffer(data); statements.Add( ExpressionStatement( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs index 25b20138..fa90409d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -29,7 +30,7 @@ partial class ID2D1ShaderGenerator /// The size of the shader constant buffer. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, ITypeSymbol structDeclarationSymbol, out int constantBufferSizeInBytes) { @@ -123,7 +124,7 @@ partial class ID2D1ShaderGenerator // each row needs to be at a multiple of 16 bytes (a float4 register). if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); for (int j = 0; j < rows; j++) { @@ -140,7 +141,7 @@ partial class ID2D1ShaderGenerator elementName!, rows, columns, - builder.MoveToImmutable()); + builder.ToImmutable()); } else { diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs index 3a568749..952fb95a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -62,14 +63,14 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.DefaultKeyword)))))); } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // The size of the buffer with the input descriptions is the number of input descriptions, times the size of each // input description, which is a struct containing three int-sized fields (index, filter, and level of detail). int inputDescriptionSizeInBytes = inputDescriptions.Length * sizeof(int) * 3; // global::System.Span data = stackalloc byte[]; - statements.Insert(0, + statements.Add( LocalDeclarationStatement( VariableDeclaration( GenericName(Identifier("global::System.Span")) @@ -84,7 +85,7 @@ partial class ID2D1ShaderGenerator LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescriptionSizeInBytes))))))))))); // ref byte r0 = ref data[0]; - statements.Insert(1, + statements.Add( LocalDeclarationStatement( VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) .AddVariables( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs index c1b9182c..c8dd433f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -24,12 +24,13 @@ partial class ID2D1ShaderGenerator /// The input instance to process. /// The produced input descriptions for the shader. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, out ImmutableArray inputDescriptions) { int inputCount = 0; - ImmutableArray.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder(); + + using ImmutableArrayBuilder inputDescriptionsBuilder = ImmutableArrayBuilder.Rent(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { @@ -63,17 +64,20 @@ partial class ID2D1ShaderGenerator } // All simple indices must be in range - if (inputDescriptionsBuilder.Any(description => description.Index >= inputCount)) + foreach (InputDescription inputDescription in inputDescriptionsBuilder.WrittenSpan) { - diagnostics.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); + if (inputDescription.Index >= inputCount) + { + diagnostics.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } Span selectedInputDescriptionIndices = stackalloc bool[8]; // All input description indices must be unique - foreach (InputDescription inputDescription in inputDescriptionsBuilder) + foreach (InputDescription inputDescription in inputDescriptionsBuilder.WrittenSpan) { ref bool isInputDescriptionIndexUsed = ref selectedInputDescriptionIndices[(int)inputDescription.Index]; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs index 82bac704..6ebafc2c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -62,14 +63,14 @@ partial class ID2D1ShaderGenerator Token(SyntaxKind.DefaultKeyword)))))); } - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // The size of the buffer with the resource texture descriptions is the number of resurce textures descriptions, // times the size of each input description, which is a struct containing two int-sized fields (index and rank). int resourceTextureDescriptionSizeInBytes = resourceTextureDescriptionsInfo.Length * sizeof(int) * 2; // global::System.Span data = stackalloc byte[]; - statements.Insert(0, + statements.Add( LocalDeclarationStatement( VariableDeclaration( GenericName(Identifier("global::System.Span")) @@ -84,7 +85,7 @@ partial class ID2D1ShaderGenerator LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceTextureDescriptionSizeInBytes))))))))))); // ref byte r0 = ref data[0]; - statements.Insert(1, + statements.Add( LocalDeclarationStatement( VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) .AddVariables( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index c9fd1576..0c788c2f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -26,12 +26,12 @@ partial class ID2D1ShaderGenerator /// The number of inputs for the shader. /// The produced resource texture descriptions for the shader. public static void GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, int inputCount, out ImmutableArray resourceTextureDescriptions) { - ImmutableArray<(int? Index, int Rank)>.Builder resourceTextureInfos = ImmutableArray.CreateBuilder<(int?, int)>(); + using ImmutableArrayBuilder<(int? Index, int Rank)> resourceTextureInfos = ImmutableArrayBuilder<(int? Index, int Rank)>.Rent(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -72,7 +72,15 @@ partial class ID2D1ShaderGenerator } // Extract the resource texture descriptions for the rest of the pipeline - resourceTextureDescriptions = resourceTextureInfos.Select(static info => new ResourceTextureDescription((uint)(info.Index ?? 0), (uint)info.Rank)).ToImmutableArray(); + using (ImmutableArrayBuilder resourceTextureDescriptionsBuilder = ImmutableArrayBuilder.Rent()) + { + foreach ((int? index, int rank) in resourceTextureInfos.WrittenSpan) + { + resourceTextureDescriptionsBuilder.Add(new ResourceTextureDescription((uint)(index ?? 0), (uint)rank)); + } + + resourceTextureDescriptions = resourceTextureDescriptionsBuilder.ToImmutable(); + } // If the input count is invalid, do nothing and avoid emitting potentially incorrect // diagnostics based on the resource texture indices with respect to the input count. @@ -84,25 +92,31 @@ partial class ID2D1ShaderGenerator } // Validate that the resource texture indices don't overlap with the shader inputs - if (resourceTextureInfos.Any(info => info.Index < inputCount)) + foreach ((int? index, _) in resourceTextureInfos.WrittenSpan) { - diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol); + if (index < inputCount) + { + diagnostics.Add(ResourceTextureIndexOverlappingWithInputIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } // Validate that no resource texture has an index greater than or equal to 16 - if (resourceTextureInfos.Any(info => info.Index >= 16)) + foreach ((int? index, _) in resourceTextureInfos.WrittenSpan) { - diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol); + if (index >= 16) + { + diagnostics.Add(OutOfRangeResourceTextureIndex, structDeclarationSymbol, structDeclarationSymbol); - return; + return; + } } Span selectedResourceTextureIndices = stackalloc bool[16]; // All input description indices must be unique (also take this path for invalid indices) - foreach ((int? index, _) in resourceTextureInfos) + foreach ((int? index, _) in resourceTextureInfos.WrittenSpan) { ref bool isResourceTextureIndexUsed = ref selectedResourceTextureIndices[index ?? 0]; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index e4502804..447d3bce 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -50,7 +51,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator return default; } - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // LoadDispatchData() info ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index be59ad0a..bbfe304e 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -45,7 +44,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// /// The collection of produced instances. /// - protected readonly ImmutableArray.Builder Diagnostics; + protected readonly ImmutableArrayBuilder Diagnostics; /// /// Creates a new instance with the specified parameters. @@ -58,7 +57,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArrayBuilder diagnostics) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 400ab405..a80b9e59 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -79,7 +78,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary staticMethods, IDictionary instanceMethods, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, bool isEntryPoint) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { @@ -106,7 +105,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary staticMethods, IDictionary instanceMethods, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArrayBuilder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs index 653d08d5..8e9dab94 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Globalization; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; @@ -31,7 +30,7 @@ internal sealed partial class StaticFieldRewriter : HlslSourceRewriter SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - ImmutableArray.Builder diagnostics) + ImmutableArrayBuilder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { } diff --git a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs index 01923f37..b1404c61 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs @@ -1,4 +1,5 @@ using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; @@ -17,7 +18,7 @@ internal static class DiagnosticsExtensions /// The source to attach the diagnostics to. /// The optional arguments for the formatted message to include. public static void Add( - this ImmutableArray.Builder diagnostics, + this ImmutableArrayBuilder diagnostics, DiagnosticDescriptor descriptor, ISymbol symbol, params object[] args) @@ -33,7 +34,7 @@ internal static class DiagnosticsExtensions /// The source to attach the diagnostics to. /// The optional arguments for the formatted message to include. public static void Add( - this ImmutableArray.Builder diagnostics, + this ImmutableArrayBuilder diagnostics, DiagnosticDescriptor descriptor, SyntaxNode node, params object[] args) diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index cb98574e..40eae510 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -12,7 +12,7 @@ namespace ComputeSharp.SourceGeneration.Helpers; /// A helper type to build sequences of values with pooled buffers. /// /// The type of items to create sequences for. -internal ref struct ImmutableArrayBuilder +internal struct ImmutableArrayBuilder : IDisposable { /// /// The shared instance to share objects. @@ -49,6 +49,24 @@ internal ref struct ImmutableArrayBuilder this.writer = writer; } + /// + /// Gets the data written to the underlying buffer so far, as a . + /// + public readonly ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.writer!.WrittenSpan; + } + + /// + /// Gets the number of elements currently written in the current instance. + /// + public readonly int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.writer!.WrittenSpan.Length; + } + /// public readonly void Add(T item) { @@ -64,6 +82,16 @@ internal ref struct ImmutableArrayBuilder this.writer!.AddRange(items); } + /// + /// Inserts an item to the builder at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The object to insert into the . + public readonly void Insert(int index, T item) + { + this.writer!.Insert(index, item); + } + /// public readonly ImmutableArray ToImmutable() { @@ -84,7 +112,7 @@ internal ref struct ImmutableArrayBuilder return this.writer!.WrittenSpan.ToString(); } - /// + /// public void Dispose() { Writer? writer = this.writer; @@ -131,9 +159,7 @@ internal ref struct ImmutableArrayBuilder this.index = 0; } - /// - /// Gets the data written to the underlying buffer so far, as a . - /// + /// public ReadOnlySpan WrittenSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -158,6 +184,25 @@ internal ref struct ImmutableArrayBuilder this.index += items.Length; } + /// + public void Insert(int index, T item) + { + if (index < 0 || index > this.index) + { + ImmutableArrayBuilder.ThrowArgumentOutOfRangeExceptionForIndex(); + } + + EnsureCapacity(1); + + if (index < this.index) + { + Array.Copy(this.array, index, this.array, index + 1, this.index - index); + } + + this.array[index] = item; + this.index++; + } + /// /// Clears the items in the current writer. /// @@ -201,4 +246,18 @@ internal ref struct ImmutableArrayBuilder this.array = newArray; } } +} + +/// +/// Private helpers for the type. +/// +file static class ImmutableArrayBuilder +{ + /// + /// Throws an for "index". + /// + public static void ThrowArgumentOutOfRangeExceptionForIndex() + { + throw new ArgumentOutOfRangeException("index"); + } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs index 1b069322..511af340 100644 --- a/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/HierarchyInfo.cs @@ -27,7 +27,7 @@ internal sealed partial record HierarchyInfo(string FilenameHint, string FullyQu /// A instance describing . public static HierarchyInfo From(INamedTypeSymbol typeSymbol) { - ImmutableArray.Builder hierarchy = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder hierarchy = ImmutableArrayBuilder.Rent(); for (INamedTypeSymbol? parent = typeSymbol; parent is not null; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 8a8f4556..4d5b5186 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -84,7 +84,8 @@ partial class IShaderGenerator /// The series of statements to build the HLSL source to compile to execute the current shader. private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); + StringBuilder textBuilder = new(); int capturedDelegates = 0; int prologueStatements = 0; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 703cf89f..03aa3fb3 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -37,7 +37,7 @@ partial class IShaderGenerator /// The for . /// The resulting info on the processed shader. public static HlslShaderSourceInfo GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) @@ -101,13 +101,14 @@ partial class IShaderGenerator ImmutableArray<(string MetadataName, string Name, string HlslType)>, ImmutableArray<(string Name, string HlslType)>) GetInstanceFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types, bool isComputeShader) { - ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>(); - ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + using ImmutableArrayBuilder<(string, string, string)> resources = ImmutableArrayBuilder<(string, string, string)>.Rent(); + using ImmutableArrayBuilder<(string, string)> values = ImmutableArrayBuilder<(string, string)>.Rent(); + bool hlslResourceFound = false; foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) @@ -192,14 +193,14 @@ partial class IShaderGenerator /// The collection of discovered constant definitions. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions) { - ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + using ImmutableArrayBuilder<(string, string, string?)> builder = ImmutableArrayBuilder<(string, string, string?)>.Rent(); foreach (var fieldDeclaration in structDeclaration.Members.OfType()) { @@ -259,11 +260,11 @@ partial class IShaderGenerator /// The collection of currently discovered types. /// A sequence of captured members in . private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, ICollection types) { - ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); + using ImmutableArrayBuilder<(string, string, int?)> builder = ImmutableArrayBuilder<(string, string, int?)>.Rent(); foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -321,7 +322,7 @@ partial class IShaderGenerator /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, @@ -337,8 +338,9 @@ partial class IShaderGenerator where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - string? entryPoint = null; - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); + + string ? entryPoint = null; bool isSamplerUsed = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) @@ -424,7 +426,7 @@ partial class IShaderGenerator /// A sequence of discovered constants to declare in the shader. internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); foreach (var constant in constantDefinitions) { @@ -434,7 +436,7 @@ partial class IShaderGenerator builder.Add((constantName, constant.Value)); } - return builder.MoveToImmutable(); + return builder.ToImmutable(); } /// @@ -446,13 +448,14 @@ partial class IShaderGenerator /// The collection of discovered instance methods for custom struct types. /// A sequence of custom type definitions to add to the shader source. internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, ISymbol sourceSymbol, IEnumerable types, IReadOnlyDictionary instanceMethods) { - ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); - IReadOnlyCollection invalidTypes; + using ImmutableArrayBuilder<(string, string)> builder = ImmutableArrayBuilder<(string, string)>.Rent(); + + IReadOnlyCollection invalidTypes; // Process the discovered types foreach (var type in HlslKnownTypes.GetCustomTypes(types, out invalidTypes)) @@ -514,7 +517,7 @@ partial class IShaderGenerator /// /// The collection of produced instances. /// The input instance to process. - private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + private static void DetectAndReportInvalidPropertyDeclarations(ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol) { foreach (var memberSymbol in structDeclarationSymbol.GetMembers()) { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 8443bf2c..61b70547 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -11,6 +11,7 @@ using System.Threading; using ComputeSharp.Exceptions; using ComputeSharp.Shaders.Translation; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; @@ -38,7 +39,7 @@ partial class IShaderGenerator /// Indicates whether or not dynamic shaders are supported. /// The thread ids for the precompiled shader, if available. public static ThreadIdsInfo GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, bool supportsDynamicShaders) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index 53b0caa3..8684d2cc 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -67,14 +68,76 @@ partial class IShaderGenerator int resourceCount, int root32BitConstantsCount) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - bool isComputeShader = shaderType == ShaderType.ComputeShader; + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); + + // global::System.Span span0 = stackalloc uint[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); + + if (resourceCount > 0) + { + // global::System.Span span1 = stackalloc ulong[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount))))))))))); + } + + // ref uint r0 = ref span0[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + if (resourceCount > 0) + { + // ref ulong r1 = ref span1[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + } // Append the statements for the dispatch ranges: // // span0[0] = (uint)x; // span0[1] = (uint)y; - // span0[2] = (uint)z; statements.Add( ExpressionStatement( AssignmentExpression( @@ -91,8 +154,10 @@ partial class IShaderGenerator .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); - // If the shader is a compute shader, also track the bounds on the Z axis - if (isComputeShader) + // If the shader is a compute shader, also track the bounds on the Z axis: + // + // span0[2] = (uint)z; + if (shaderType == ShaderType.ComputeShader) { statements.Add( ExpressionStatement( @@ -173,35 +238,6 @@ partial class IShaderGenerator } } - // global::System.Span span0 = stackalloc uint[]; - statements.Insert(0, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); - - // ref uint r0 = ref span0[0]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - // loader.LoadCapturedValues(span0); statements.Add( ExpressionStatement( @@ -214,35 +250,6 @@ partial class IShaderGenerator if (resourceCount > 0) { - // global::System.Span span1 = stackalloc ulong[]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount))))))))))); - - // ref ulong r1 = ref span1[0]; - statements.Insert(3, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - // loader.LoadCapturedResources(span1); statements.Add( ExpressionStatement( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index bfdb56ec..298f27e4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; @@ -31,7 +32,7 @@ partial class IShaderGenerator /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, ITypeSymbol structDeclarationSymbol, ShaderType shaderType, out int resourceCount, @@ -148,7 +149,7 @@ partial class IShaderGenerator // each row needs to be at a multiple of 16 bytes (a float4 register). if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(rows); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); for (int j = 0; j < rows; j++) { @@ -165,7 +166,7 @@ partial class IShaderGenerator elementName!, rows, columns, - builder.MoveToImmutable()); + builder.ToImmutable()); } else { diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 4ae4f04c..a6807487 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Globalization; using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -54,7 +55,7 @@ partial class IShaderGenerator /// The sequence of instances to load shader dispatch data. private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); // global::System.Span span0 = stackalloc byte[5]; statements.Add( diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index b89652a4..c0f2a926 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -1,4 +1,5 @@ using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGenerators.Models; @@ -26,7 +27,8 @@ partial class IShaderGenerator bool isSamplerUsed, ImmutableArray capturedFields) { - ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder descriptors = ImmutableArrayBuilder.Rent(); + int constantBufferOffset = 1; int readOnlyResourceOffset = 0; int readWriteResourceOffset = 0; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 3c207729..c5b1da2b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; using System.Text; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; @@ -55,7 +56,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator return default; } - ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder diagnostics = ImmutableArrayBuilder.Rent(); // GetDispatchId() info ImmutableArray dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol); diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7985bf26..81356654 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -79,7 +79,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator IMethodSymbol methodSymbol, out ImmutableArray diagnostics) { - ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + using ImmutableArrayBuilder builder = ImmutableArrayBuilder.Rent(); // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); @@ -112,7 +112,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator /// The collection of discovered constant definitions. /// A sequence of processed methods in (main method and all captured methods). private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( - ImmutableArray.Builder diagnostics, + ImmutableArrayBuilder diagnostics, CSharpSyntaxNode methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, @@ -137,7 +137,7 @@ public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator .NormalizeWhitespace(eol: "\n") .ToFullString(); - ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(shaderSourceRewriter.LocalFunctions.Count); + using ImmutableArrayBuilder<(string, string)> methods = ImmutableArrayBuilder<(string, string)>.Rent(); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 951b348d..3a3a2aa5 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -using System.Threading; using System.Threading.Tasks; using CommunityToolkit.Diagnostics; using ComputeSharp.__Internals; diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index ad8033c2..b1a57806 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting;