From 734e9a09029c80297c7f1d6e33d13ce434247c51 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 23 Aug 2019 16:58:08 +0200 Subject: [PATCH 1/5] Added draft for the UnwrapSyntaxTree API --- .../Translation/MethodDecompiler.cs | 86 +++++++++++++++---- 1 file changed, 71 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index ae59e697..4901365a 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -99,6 +99,25 @@ namespace ComputeSharp.Shaders.Translation } } + /// + /// Creates a new instance targeting a given assembly + /// + /// The path of the assembly to decompile + /// A instance that can be used on the targeted assembly + [Pure] + private static CSharpDecompiler CreateDecompiler(string assemblyPath) + { + DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) + { + ObjectOrCollectionInitializers = false, + UsingDeclarations = false, + CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString } + }; + + UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); + return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); + } + /// /// A used to preprocess the closure type declarations for both lambda expressions and local methods /// @@ -149,8 +168,11 @@ namespace ComputeSharp.Shaders.Translation methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode); } + // Unwrap the nested fields + string unwrappedCode = UnwrapSyntaxTree(methodFixedCode); + // Load the type syntax tree - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(methodFixedCode); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(unwrappedCode); // Get the root node to return rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); @@ -162,22 +184,56 @@ namespace ComputeSharp.Shaders.Translation } /// - /// Creates a new instance targeting a given assembly + /// A used to find fields that represent nested closure types /// - /// The path of the assembly to decompile - /// A instance that can be used on the targeted assembly - [Pure] - private static CSharpDecompiler CreateDecompiler(string assemblyPath) - { - DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) - { - ObjectOrCollectionInitializers = false, - UsingDeclarations = false, - CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString } - }; + private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled); - UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); - return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); + /// + /// Unwraps all the nested captured fields in the given source code, moving them to the top level + /// + /// The input source code to process + [Pure] + private string UnwrapSyntaxTree(string source) + { + List parsedFields = new List(); + + // Local function to recursively extract all the nested fields + void ParseSyntaxTree(string source) + { + // Find the field declarations + MatchCollection matches = NestedClosureFieldRegex.Matches(source); + if (matches.Count == 0) return; + + foreach (Match match in matches) + { + // Load the nested closure type + string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type + Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); + + // Decompile the type and get a readable source code + EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); + CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; + string + sourceCode = decompiler.DecompileAsString(typeHandle), + typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); + + // Load the syntax tree and retrieve the list of fields + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); + FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); + + // Add the captured fields + foreach (FieldDeclarationSyntax field in fields) + if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) + parsedFields.Add(field); + + // Explore the new decompiled type + ParseSyntaxTree(typeFixedCode); + } + } + + ParseSyntaxTree(source); + + return source; } } } From 1f9c735bd9d787ac34bfa21f6bf2866048cc8b9d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 23 Aug 2019 17:10:19 +0200 Subject: [PATCH 2/5] Implemented field declaration unwrapping in source code --- .../Translation/MethodDecompiler.cs | 61 +++++++++++-------- 1 file changed, 36 insertions(+), 25 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index 4901365a..cd2e083f 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; +using System.Text; using System.Text.RegularExpressions; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; @@ -198,40 +199,50 @@ namespace ComputeSharp.Shaders.Translation List parsedFields = new List(); // Local function to recursively extract all the nested fields - void ParseSyntaxTree(string source) + void ParseNestedFields(string source) { // Find the field declarations - MatchCollection matches = NestedClosureFieldRegex.Matches(source); - if (matches.Count == 0) return; + Match match = NestedClosureFieldRegex.Match(source); + if (!match.Success) return; - foreach (Match match in matches) - { - // Load the nested closure type - string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type - Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); + // Load the nested closure type + string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type + Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); - // Decompile the type and get a readable source code - EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); - CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; - string - sourceCode = decompiler.DecompileAsString(typeHandle), - typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); + // Decompile the type and get a readable source code + EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); + CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; + string + sourceCode = decompiler.DecompileAsString(typeHandle), + typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); - // Load the syntax tree and retrieve the list of fields - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); - FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); + // Load the syntax tree and retrieve the list of fields + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); + FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); - // Add the captured fields - foreach (FieldDeclarationSyntax field in fields) - if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) - parsedFields.Add(field); + // Add the captured fields + foreach (FieldDeclarationSyntax field in fields) + if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) + parsedFields.Add(field); - // Explore the new decompiled type - ParseSyntaxTree(typeFixedCode); - } + // Explore the new decompiled type + ParseNestedFields(typeFixedCode); } - ParseSyntaxTree(source); + ParseNestedFields(source); + + if (parsedFields.Count > 0) + { + // Build the aggregated string with all the captured fields + StringBuilder builder = new StringBuilder(); + foreach (FieldDeclarationSyntax field in parsedFields) + builder.AppendLine(field.ToFullString()); + string fields = builder.ToString().TrimEnd(' ', '\r', '\n'); + + Match match = NestedClosureFieldRegex.Match(source); + source = source.Remove(match.Index - 11, match.Length + 12); + source = source.Insert(match.Index - 11, fields); + } return source; } From 7351489aeb081e3e9b9d4d5f06257a2a6b599ef9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 23 Aug 2019 19:14:40 +0200 Subject: [PATCH 3/5] Minor tweaks to the source code unwrapping --- .../Translation/MethodDecompiler.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index cd2e083f..3046b64f 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -189,6 +189,11 @@ namespace ComputeSharp.Shaders.Translation /// private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled); + /// + /// A used to identify compiler generated fields + /// + private static readonly Regex CompilerGeneratedFieldRegex = new Regex(@"CS\$<>[\w_]+\.", RegexOptions.Compiled); + /// /// Unwraps all the nested captured fields in the given source code, moving them to the top level /// @@ -239,9 +244,13 @@ namespace ComputeSharp.Shaders.Translation builder.AppendLine(field.ToFullString()); string fields = builder.ToString().TrimEnd(' ', '\r', '\n'); + // Replace the field declarations Match match = NestedClosureFieldRegex.Match(source); - source = source.Remove(match.Index - 11, match.Length + 12); + source = source.Remove(match.Index - 11, match.Length + 12); // leading " public " and trailing ";" source = source.Insert(match.Index - 11, fields); + + // Adjust the method body to remove references to compiler generated fields + source = CompilerGeneratedFieldRegex.Replace(source, string.Empty); } return source; From d3f9be837d652459c8bc86262b62e1f3ed10bac2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 23 Aug 2019 19:33:57 +0200 Subject: [PATCH 4/5] Implemented support for captured scopes --- .../Translation/ShaderLoader.cs | 54 +++++++++++++++---- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 669f05c2..5e2f5e4d 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -72,24 +72,46 @@ namespace ComputeSharp.Shaders.Translation /// /// The of instances mapping the captured buffers in the current shader /// - private readonly List _BufferMembers = new List(); + private readonly List<(ReadableMember Member, IEnumerable? Parents)> _BufferMembers = new List<(ReadableMember, IEnumerable?)>(); /// /// Gets the ordered collection of buffers used as fields in the current shader /// /// The to use to build the shader - public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) => _BufferMembers.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(action.Target))); + public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) + { + foreach (var (item, i) in _BufferMembers.Select((item, i) => (item, i))) + { + if (item.Parents == null) yield return (i + 1, (GraphicsResource)item.Member.GetValue(action.Target)); + else + { + object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj)); + yield return (i + 1, (GraphicsResource)item.Member.GetValue(target)); + } + } + } /// /// The of instances mapping the captured scalar/vector variables in the current shader /// - private readonly List _VariableMembers = new List(); + private readonly List<(ReadableMember Member, IEnumerable? Parents)> _VariableMembers = new List<(ReadableMember, IEnumerable?)>(); /// /// 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) => _VariableMembers.Select(field => field.GetValue(action.Target)); + public IEnumerable GetVariables(Action action) + { + foreach (var item in _VariableMembers) + { + if (item.Parents == null) yield return item.Member.GetValue(action.Target); + else + { + object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj)); + yield return item.Member.GetValue(target); + } + } + } private readonly List _BuffersList = new List(); @@ -154,7 +176,8 @@ namespace ComputeSharp.Shaders.Translation /// /// The target to load /// The optional explicit name to use for the field - private void LoadFieldInfo(ReadableMember memberInfo, string? name = null) + /// The list of parent fields to reach the current from a given + private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? parents = null) { Type fieldType = memberInfo.MemberType; string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); @@ -165,7 +188,7 @@ namespace ComputeSharp.Shaders.Translation DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount)); // Track the buffer field - _BufferMembers.Add(memberInfo); + _BufferMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); _BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++)); @@ -176,7 +199,7 @@ namespace ComputeSharp.Shaders.Translation DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount)); // Track the buffer field - _BufferMembers.Add(memberInfo); + _BufferMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++)); @@ -187,7 +210,7 @@ namespace ComputeSharp.Shaders.Translation DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount)); // Track the buffer field - _BufferMembers.Add(memberInfo); + _BufferMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++)); @@ -195,10 +218,23 @@ namespace ComputeSharp.Shaders.Translation else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { // Register the captured field - _VariableMembers.Add(memberInfo); + _VariableMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); } + else if (fieldType.IsClass && fieldName.StartsWith("CS$<>")) + { + // Captured scope, update the parents list + List updatedParents = parents?.ToList() ?? new List(); + updatedParents.Add(memberInfo); + + // Recurse on the new compiler generated class + IReadOnlyList fields = fieldType.GetFields().ToArray(); + foreach (FieldInfo fieldInfo in fields) + { + LoadFieldInfo(fieldInfo, null, updatedParents); + } + } } /// From 0f5fe6776b806e630a5a1ff06b081a91738ee103 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 23 Aug 2019 19:39:49 +0200 Subject: [PATCH 5/5] Code tweaks to the bokeh sample --- samples/ComputeSharp.BokehBlur/Program.cs | 50 ++++++++++++----------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/samples/ComputeSharp.BokehBlur/Program.cs b/samples/ComputeSharp.BokehBlur/Program.cs index f6274586..52208139 100644 --- a/samples/ComputeSharp.BokehBlur/Program.cs +++ b/samples/ComputeSharp.BokehBlur/Program.cs @@ -79,40 +79,42 @@ namespace ComputeSharp.BokehBlur for (int j = 0; j < diameter; j++) kernel[i * diameter + j] /= ones; - // Apply the effect Console.WriteLine(">> Applying effect"); - using ReadOnlyBuffer image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray); - using ReadOnlyBuffer kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel); - using ReadWriteBuffer result_gpu = Gpu.Default.AllocateReadWriteBuffer(vectorArray.Length); - Gpu.Default.For(height, width, id => + using (ReadOnlyBuffer image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray)) + using (ReadOnlyBuffer kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel)) + using (ReadWriteBuffer result_gpu = Gpu.Default.AllocateReadWriteBuffer(vectorArray.Length)) { - Vector4 total = Vector4.Zero; - - for (int y = -Radius; y <= Radius; y++) + // Apply the effect + Gpu.Default.For(height, width, id => { - for (int x = -Radius; x <= Radius; x++) + Vector4 total = Vector4.Zero; + + for (int y = -Radius; y <= Radius; y++) { - int iy = (int)id.X + y; - int jx = (int)id.Y + x; + for (int x = -Radius; x <= Radius; x++) + { + int iy = (int)id.X + y; + int jx = (int)id.Y + x; - if (iy < 0) iy = -iy; - else if (iy > height) iy = 2 * height - iy; - if (jx < 0) jx = -jx; - else if (jx > width) jx = 2 * width - jx; + if (iy < 0) iy = -iy; + else if (iy > height) iy = 2 * height - iy; + if (jx < 0) jx = -jx; + else if (jx > width) jx = 2 * width - jx; - int ki = Radius - y; - int kj = Radius - x; + int ki = Radius - y; + int kj = Radius - x; - total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)]; + total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)]; + } } - } - result_gpu[(uint)(id.X * width + id.Y)] = total; - }); + result_gpu[(uint)(id.X * width + id.Y)] = total; + }); - // Copy data back - Console.WriteLine(">> Copying data back"); - result_gpu.GetData(vectorArray); + // Copy data back + Console.WriteLine(">> Copying data back"); + result_gpu.GetData(vectorArray); + } // Copy the modified image back Console.WriteLine(">> Storing pixel data");