From e26b74d27687b70d7454409b452c7f87a6a06e82 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Aug 2019 12:56:58 +0200 Subject: [PATCH 1/4] Lazy evaluation for the captured variables --- .../Translation/ShaderLoader.cs | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 3ac67495..8a16eeba 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -26,11 +26,6 @@ namespace ComputeSharp.Shaders.Translation /// private readonly Action Action; - /// - /// The closure for the field - /// - private readonly Type ShaderType; - /// /// The closure instance for the field /// @@ -39,7 +34,7 @@ namespace ComputeSharp.Shaders.Translation /// /// The sequence of fields in the targeted closure /// - private readonly IReadOnlyList ShaderFields; + private readonly IReadOnlyList ShaderFields; /// /// Creates a new with the specified parameters @@ -53,17 +48,25 @@ namespace ComputeSharp.Shaders.Translation ShaderFields = ShaderType.GetFields().ToArray(); } + /// + /// Gets the closure for the field + /// + public Type ShaderType { get; } + /// /// Gets the array for the current shader /// public RootParameter[] RootParameters { get; private set; } - private readonly List<(int, GraphicsResource)> _Buffers = new List<(int, GraphicsResource)>(); + /// + /// The of instances mapping the captured buffers in the current shader + /// + private readonly List _BufferFields = new List(); /// /// Gets the ordered collection of buffers used as fields in the current shader /// - public IReadOnlyList<(int Index, GraphicsResource Resource)> Buffers => _Buffers; + public IEnumerable<(int Index, GraphicsResource Resource)> Buffers => _BufferFields.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(ShaderInstance))); private readonly List _BuffersList = new List(); @@ -79,12 +82,15 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyList FieldsList => _FieldsList; - private readonly List _FieldValuesList = new List(); + /// + /// The of instances mapping the captured scalar/vector variables in the current shader + /// + private readonly List _VariableFields = new List(); /// /// Gets the collection of values of the captured fields for the current shader /// - public IReadOnlyList FieldValuesList => _FieldValuesList; + public IEnumerable FieldValuesList => _VariableFields.Select(field => field.GetValue(ShaderInstance)); /// /// Gets the name of the variable used as input for the shader method @@ -132,15 +138,14 @@ namespace ComputeSharp.Shaders.Translation { Type fieldType = fieldInfo.FieldType; string fieldName = fieldInfo.Name; - object fieldValue = fieldInfo.GetValue(ShaderInstance); // Constant buffer if (HlslKnownTypes.IsConstantBufferType(fieldType)) { descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount)); - // Reference to the underlying buffer - _Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + // Track the buffer field + _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); _BuffersList.Add(new ConstantBufferFieldInfo(typeName, fieldName, constantBuffersCount++)); @@ -150,8 +155,8 @@ namespace ComputeSharp.Shaders.Translation // Root parameter for a readonly buffer descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, readOnlyBuffersCount)); - // Reference to the underlying buffer - _Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + // Track the buffer field + _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadOnlyBufferFieldInfo(typeName, fieldName, readOnlyBuffersCount++)); @@ -161,8 +166,8 @@ namespace ComputeSharp.Shaders.Translation // Root parameter for a read write buffer descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount)); - // Reference to the underlying buffer - _Buffers.Add((descriptorRanges.Count - 1, (GraphicsResource)fieldValue)); + // Track the buffer field + _BufferFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++)); @@ -170,7 +175,7 @@ namespace ComputeSharp.Shaders.Translation else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { // Register the captured field - _FieldValuesList.Add(fieldValue); + _VariableFields.Add(fieldInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(typeName, fieldName)); } From 45b991ff59bea657a2689e0bfc1470996976ce72 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Aug 2019 13:00:32 +0200 Subject: [PATCH 2/4] Code refactoring --- src/ComputeSharp.Shaders/Translation/ShaderLoader.cs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 8a16eeba..27f03881 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -31,11 +31,6 @@ namespace ComputeSharp.Shaders.Translation /// private readonly object ShaderInstance; - /// - /// The sequence of fields in the targeted closure - /// - private readonly IReadOnlyList ShaderFields; - /// /// Creates a new with the specified parameters /// @@ -45,7 +40,6 @@ namespace ComputeSharp.Shaders.Translation Action = action; ShaderType = action.Method.DeclaringType; ShaderInstance = action.Target; - ShaderFields = ShaderType.GetFields().ToArray(); } /// @@ -123,7 +117,8 @@ namespace ComputeSharp.Shaders.Translation /// private void LoadFieldsInfo() { - if (ShaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); + IReadOnlyList shaderFields = ShaderType.GetFields().ToArray(); + if (shaderFields.Any(fieldInfo => fieldInfo.IsStatic)) throw new InvalidOperationException("Empty shader body"); List descriptorRanges = new List(); int constantBuffersCount = 0; @@ -134,7 +129,7 @@ namespace ComputeSharp.Shaders.Translation descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, constantBuffersCount++)); // Inspect the captured fields - foreach (FieldInfo fieldInfo in ShaderFields) + foreach (FieldInfo fieldInfo in shaderFields) { Type fieldType = fieldInfo.FieldType; string fieldName = fieldInfo.Name; From 72b4a05d270b386a3818eceac27543fea9ed3119 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Aug 2019 13:09:43 +0200 Subject: [PATCH 3/4] Implemented external loading for captured values --- src/ComputeSharp.Shaders/ShaderRunner.cs | 4 +-- .../Translation/ShaderLoader.cs | 30 ++++++++----------- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 09cf2fd2..a424548d 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -89,13 +89,13 @@ namespace ComputeSharp.Shaders commandList.SetPipelineState(pipelineState); // Load the captured buffers - foreach (var buffer in shaderLoader.Buffers) + foreach (var buffer in shaderLoader.GetBuffers(action)) { commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); } // Initialize the loop targets - IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderLoader.FieldValuesList).ToArray(); + IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderLoader.GetVariables(action)).ToArray(); using GraphicsResource variablesBuffer = device.AllocateConstantBufferFromReflectedValues(variables); commandList.SetComputeRootDescriptorTable(0, variablesBuffer); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 27f03881..4bbb7a80 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -26,11 +26,6 @@ namespace ComputeSharp.Shaders.Translation /// private readonly Action Action; - /// - /// The closure instance for the field - /// - private readonly object ShaderInstance; - /// /// Creates a new with the specified parameters /// @@ -39,7 +34,6 @@ namespace ComputeSharp.Shaders.Translation { Action = action; ShaderType = action.Method.DeclaringType; - ShaderInstance = action.Target; } /// @@ -60,7 +54,19 @@ namespace ComputeSharp.Shaders.Translation /// /// Gets the ordered collection of buffers used as fields in the current shader /// - public IEnumerable<(int Index, GraphicsResource Resource)> Buffers => _BufferFields.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(ShaderInstance))); + /// The to use to build the shader + public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) => _BufferFields.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(action.Target))); + + /// + /// The of instances mapping the captured scalar/vector variables in the current shader + /// + private readonly List _VariableFields = new List(); + + /// + /// Gets the collection of values of the captured fields for the current shader + /// + /// The to use to build the shader + public IEnumerable GetVariables(Action action) => _VariableFields.Select(field => field.GetValue(action.Target)); private readonly List _BuffersList = new List(); @@ -76,16 +82,6 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyList FieldsList => _FieldsList; - /// - /// The of instances mapping the captured scalar/vector variables in the current shader - /// - private readonly List _VariableFields = new List(); - - /// - /// Gets the collection of values of the captured fields for the current shader - /// - public IEnumerable FieldValuesList => _VariableFields.Select(field => field.GetValue(ShaderInstance)); - /// /// Gets the name of the variable used as input for the shader method /// From 543fc00003d0a593ebc232d2413abb450a5d8af4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 17 Aug 2019 13:26:25 +0200 Subject: [PATCH 4/4] Implemented shader caching --- src/ComputeSharp.Shaders/ShaderRunner.cs | 54 +++++++++++++++--------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index a424548d..9d0b99e0 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -37,6 +37,11 @@ namespace ComputeSharp.Shaders Run(device, x, y, z, threadsX, threadsY, threadsZ, action); } + /// + /// The mapping used to cache and reuse compiled shaders + /// + private static readonly Dictionary<(Type type, int ThreadsX, int ThreadsY, int ThreadsZ), (ShaderLoader Loader, ShaderBytecode Bytecode)> ShadersCache = new Dictionary<(Type, int, int, int), (ShaderLoader, ShaderBytecode)>(); + /// /// Compiles and runs the input shader on a target instance, with the specified parameters /// @@ -60,42 +65,51 @@ namespace ComputeSharp.Shaders groupsY = y / threadsY + (y % threadsY == 0 ? 0 : 1), groupsZ = z / threadsZ + (z % threadsZ == 0 ? 0 : 1); - // Load the input shader - ShaderLoader shaderLoader = ShaderLoader.Load(action); - - // Render the loaded shader - ShaderInfo shaderInfo = new ShaderInfo + // Try to get the cache shader + var key = (action.Method.DeclaringType, threadsX, threadsY, threadsZ); + if (!ShadersCache.TryGetValue(key, out var shaderData)) { - BuffersList = shaderLoader.BuffersList, - FieldsList = shaderLoader.FieldsList, - NumThreadsX = threadsX, - NumThreadsY = threadsY, - NumThreadsZ = threadsZ, - ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, - ShaderBody = shaderLoader.MethodBody - }; - string shaderSource = ShaderRenderer.Instance.Render(shaderInfo); + // Load the input shader + ShaderLoader shaderLoader = ShaderLoader.Load(action); - // Compile the loaded shader to HLSL bytecode - ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource); + // Render the loaded shader + ShaderInfo shaderInfo = new ShaderInfo + { + BuffersList = shaderLoader.BuffersList, + FieldsList = shaderLoader.FieldsList, + NumThreadsX = threadsX, + NumThreadsY = threadsY, + NumThreadsZ = threadsZ, + ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName, + ShaderBody = shaderLoader.MethodBody + }; + string shaderSource = ShaderRenderer.Instance.Render(shaderInfo); + + // Compile the loaded shader to HLSL bytecode + ShaderBytecode shaderBytecode = ShaderCompiler.Instance.CompileShader(shaderSource); + + // Cache for later use + shaderData = (shaderLoader, shaderBytecode); + ShadersCache.Add(key, shaderData); + } // Create the root signature for the pipeline and get the pipeline state - RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderLoader.RootParameters); + RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, shaderData.Loader.RootParameters); RootSignature rootSignature = device.CreateRootSignature(rootSignatureDescription); - PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); + PipelineState pipelineState = new PipelineState(device, rootSignature, shaderData.Bytecode); // Create the commands list and set the pipeline state using CommandList commandList = new CommandList(device, CommandListType.Compute); commandList.SetPipelineState(pipelineState); // Load the captured buffers - foreach (var buffer in shaderLoader.GetBuffers(action)) + foreach (var buffer in shaderData.Loader.GetBuffers(action)) { commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); } // Initialize the loop targets - IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderLoader.GetVariables(action)).ToArray(); + IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderData.Loader.GetVariables(action)).ToArray(); using GraphicsResource variablesBuffer = device.AllocateConstantBufferFromReflectedValues(variables); commandList.SetComputeRootDescriptorTable(0, variablesBuffer);