Minor code refactoring

このコミットが含まれているのは:
Sergio Pedri committed 2019-08-12 14:55:46 +02:00
1 親 ce660d8aa7
コミット 0339cfb6d6
5ファイル変更
+5 -4

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

+200
ファイルの表示
@@ -0,0 +1,200 @@
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that is able to decompile arbitrary methods
/// </summary>
public sealed class MethodDecompiler
{
/// <summary>
/// Gets the singleton <see cref="MethodDecompiler"/> instance to use
/// </summary>
public static MethodDecompiler Instance { get; } = new MethodDecompiler();
/// <summary>
/// The dummy object used to handle concurrent decompilation requests
/// </summary>
private readonly object Lock = new object();
/// <summary>
/// The mapping of available <see cref="CSharpDecompiler"/> instances targeting different assemblies
/// </summary>
private readonly Dictionary<string, CSharpDecompiler> Decompilers = new Dictionary<string, CSharpDecompiler>();
/// <summary>
/// The available <see cref="PEFile"/> instances for the loaded assemblies
/// </summary>
private readonly IReadOnlyList<PEFile> PEFiles;
/// <summary>
/// The mapping of <see cref="PEFile"/> and <see cref="TypeDefinition"/> values for the discovered <see cref="Type"/> instances
/// </summary>
private readonly Dictionary<Type, (PEFile PEFile, TypeDefinition TypeDefinition)> TypeDefinitions = new Dictionary<Type, (PEFile, TypeDefinition)>();
/// <summary>
/// The incremental <see cref="Compilation"/> instance for the shader assembly
/// </summary>
private Compilation _Compilation;
/// <summary>
/// Creates a new <see cref="MethodDecompiler"/> instance
/// </summary>
private MethodDecompiler()
{
// Load the assembly paths for all the available dlls
IReadOnlyList<string> assemblyPaths;
if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location))
{
assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
}
else
{
assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p =>
{
try
{
using PEFile _ = new PEFile(p);
return true;
}
catch
{
return false;
}
}).ToArray();
}
// Load and store all the available PEFile instances
PEFiles = assemblyPaths.Select(p => new PEFile(p)).ToArray();
// Ceate an incremental shader assembly with the available references
IEnumerable<PortableExecutableReference> metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p));
_Compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences);
// Monitor for new assemblies being loaded
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
}
// Increment the shader assembly when a new assembly is loaded
private void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e)
{
if (!e.LoadedAssembly.IsDynamic)
{
PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location);
_Compilation = _Compilation.AddReferences(metadataReference);
}
}
/// <summary>
/// Decompiles a target method and returns its <see cref="SyntaxTree"/> and <see cref="SemanticModel"/> info
/// </summary>
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
/// <param name="rootNode">The root node for the syntax tree of the input method</param>
/// <param name="semanticModel">The semantic model for the input method</param>
public void GetSyntaxTree(MethodInfo methodInfo, out SyntaxNode rootNode, out SemanticModel semanticModel)
{
lock (Lock)
{
// Get the handle of the input method
GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle);
// Get or create a decompiler for the target assembly, and decompile the method
if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler))
{
decompiler = CreateDecompiler(assemblyPath);
Decompilers.Add(assemblyPath, decompiler);
}
string sourceCode = decompiler.DecompileAsString(methodHandle);
// Load the method syntax tree
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
rootNode = syntaxTree.GetRoot();
// Update the incremental compilation and retrieve the syntax tree for the method
_Compilation = _Compilation.AddSyntaxTrees(syntaxTree);
semanticModel = _Compilation.GetSemanticModel(syntaxTree);
}
}
/// <summary>
/// Loads the assembly path and method handle for the input <see cref="MethodInfo"/> instance
/// </summary>
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
/// <param name="assemblyPath">The path of the assembly containing the input method</param>
/// <param name="methodHandle">The handle for the input method</param>
private void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle)
{
// Try to get the method handle from the assembly of the declaring type
Type declaringType = methodInfo.DeclaringType ?? throw new InvalidOperationException("Invalid declaring type");
string path = declaringType.Assembly.Location;
if (!string.IsNullOrEmpty(path))
{
assemblyPath = path;
methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
}
else
{
// Try to get the PEFile and type definition for the method declaring type
if (!TypeDefinitions.TryGetValue(methodInfo.DeclaringType, out (PEFile PEFile, TypeDefinition TypeDefinition) tuple))
{
foreach (PEFile peFile in PEFiles)
{
// If not available, browse through the loaded PEFiles to find the type definition
TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName);
if (!typeDefinitionHandle.IsNil)
{
tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle));
TypeDefinitions.Add(methodInfo.DeclaringType, tuple);
break;
}
}
if (tuple.PEFile is null) throw new InvalidOperationException($"Missing PEFile for declaring type {methodInfo.DeclaringType.FullName}");
}
PEFile peFileForMethod = tuple.PEFile;
TypeDefinition typeDefinition = tuple.TypeDefinition;
// Retrieve the assembly path and method handle from the loaded PEFile and metadata
assemblyPath = peFileForMethod.FileName;
methodHandle = typeDefinition.GetMethods()
.Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name))
.First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length);
}
}
/// <summary>
/// Creates a new <see cref="CSharpDecompiler"/> instance targeting a given assembly
/// </summary>
/// <param name="assemblyPath">The path of the assembly to decompile</param>
/// <returns>A <see cref="CSharpDecompiler"/> instance that can be used on the targeted assembly</returns>
[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);
}
}
}
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System;
using System.Diagnostics.Contracts;
using DotNetDxc;
using SharpDX.Direct3D12;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that uses the <see cref="HlslDxcLib"/> APIs to compile compute shaders
/// </summary>
public sealed class ShaderCompiler
{
/// <summary>
/// Gets the singleton <see cref="ShaderCompiler"/> instance to use
/// </summary>
public static ShaderCompiler Instance { get; } = new ShaderCompiler();
/// <summary>
/// The <see cref="IDxcCompiler"/> instance to use to create new HLSL shaders
/// </summary>
private readonly IDxcCompiler Compiler;
/// <summary>
/// The <see cref="IDxcLibrary"/> instance to use to create the bytecode for HLSL sources
/// </summary>
private readonly IDxcLibrary Library;
/// <summary>
/// Creates a new <see cref="ShaderCompiler"/> instance
/// </summary>
private ShaderCompiler()
{
HlslDxcLib.DxcCreateInstanceFn = DefaultDxcLib.GetDxcCreateInstanceFn();
Compiler = HlslDxcLib.CreateDxcCompiler();
Library = HlslDxcLib.CreateDxcLibrary();
}
/// <summary>
/// Compiles a new HLSL shader from the input source code
/// </summary>
/// <param name="source">The HLSL source code to compile</param>
/// <returns>The bytecode for the compiled shader</returns>
[Pure]
public ShaderBytecode CompileShader(string source)
{
const uint CP_UTF16 = 1200;
IDxcBlobEncoding sourceBlob = Library.CreateBlobWithEncodingOnHeapCopy(source, (uint)(source.Length * 2), CP_UTF16);
IDxcOperationResult result = Compiler.Compile(sourceBlob, "", "CSMain", "cs_6_1", new[] { "-Zpr" }, 1, null, 0, Library.CreateIncludeHandler());
// Get the compiled bytecode in case of success
if (result.GetStatus() == 0)
{
IDxcBlob blob = result.GetResult();
byte[] bytecode = GetBytesFromBlob(blob);
return bytecode;
}
// Compile error
string resultText = GetStringFromBlob(Library, result.GetErrors());
throw new Exception(resultText);
}
/// <summary>
/// Reads the buffer content from an input <see cref="IDxcBlob"/> instance
/// </summary>
/// <param name="blob">The input <see cref="IDxcBlob"/> instance to read data from</param>
/// <returns>The read bytes buffer, as an array</returns>
[Pure]
private static unsafe byte[] GetBytesFromBlob(IDxcBlob blob)
{
byte* pMem = (byte*)blob.GetBufferPointer();
uint size = blob.GetBufferSize();
byte[] result = new byte[size];
new Span<byte>(pMem, (int)size).CopyTo(result.AsSpan());
return result;
}
/// <summary>
/// Reads a <see cref="string"/> value from an input <see cref="IDxcBlob"/> instance
/// </summary>
/// <param name="library">The source <see cref="IDxcLibrary"/> to use to load the data</param>
/// <param name="blob">The input <see cref="IDxcBlob"/> instance to read data from</param>
/// <returns>The resulting <see cref="string"/> read from the input data buffer</returns>
[Pure]
private static unsafe string GetStringFromBlob(IDxcLibrary library, IDxcBlob blob)
{
blob = library.GetBlobAstUf16(blob);
return new string(blob.GetBufferPointer(), 0, (int)(blob.GetBufferSize() / 2));
}
}
}
+166
ファイルの表示
@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SharpDX.Direct3D12;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing <see cref="Action{T}"/> instances
/// </summary>
public sealed class ShaderLoader
{
/// <summary>
/// The <see cref="Action{T}"/> that represents the shader to load
/// </summary>
private readonly Action<ThreadIds> Action;
/// <summary>
/// The closure <see cref="Type"/> for the <see cref="Action"/> field
/// </summary>
private readonly Type ShaderType;
/// <summary>
/// The closure instance for the <see cref="Action"/> field
/// </summary>
private readonly object ShaderInstance;
/// <summary>
/// The sequence of fields in the targeted closure
/// </summary>
private readonly IReadOnlyList<FieldInfo> ShaderFields;
/// <summary>
/// Creates a new <see cref="ShaderLoader"/> with the specified parameters
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
private ShaderLoader(Action<ThreadIds> action)
{
Action = action;
ShaderType = action.Method.DeclaringType;
ShaderInstance = action.Target;
ShaderFields = ShaderType.GetFields().ToArray();
}
/// <summary>
/// Gets the <see cref="RootParameter"/> array for the current shader
/// </summary>
public RootParameter[] RootParameters { get; private set; }
/// <summary>
/// Gets the ordered collection of read write buffers used as fields in the current shader
/// </summary>
public IReadOnlyList<GraphicsResource> ReadWriteBuffers { get; private set; }
private readonly List<FieldInfoBase> _FieldsInfo = new List<FieldInfoBase>();
/// <summary>
/// Gets the collection of <see cref="FieldInfoBase"/> items for the shader fields
/// </summary>
public IReadOnlyList<FieldInfoBase> FieldsInfo => _FieldsInfo;
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader
/// </summary>
public string MethodBody { get; private set; }
/// <summary>
/// Loads and processes an input <see cref="Action{T}"/>
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to use to build the shader</param>
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
[Pure]
public static ShaderLoader Load(Action<ThreadIds> action)
{
ShaderLoader @this = new ShaderLoader(action);
@this.LoadFieldsInfo();
@this.LoadMethodSource();
return @this;
}
/// <summary>
/// Loads the fields info for the current shader being loaded
/// </summary>
private void LoadFieldsInfo()
{
if (FieldsInfo.Count > 0) throw new InvalidOperationException("Shader fields already loaded");
List<DescriptorRange> descriptorRanges = new List<DescriptorRange>();
List<GraphicsResource> readWriteBuffers = new List<GraphicsResource>();
int readWriteBuffersCount = 0;
foreach (FieldInfo fieldInfo in ShaderFields)
{
Type fieldType = fieldInfo.FieldType;
string fieldName = fieldInfo.Name;
object fieldValue = fieldInfo.GetValue(ShaderInstance);
FieldInfoBase processedFieldInfo;
// Read write buffer
if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
DescriptorRange range = new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, readWriteBuffersCount);
descriptorRanges.Add(range);
// Reference to the underlying buffer
readWriteBuffers.Add((GraphicsResource)fieldValue);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
processedFieldInfo = new ReadWriteBufferFieldInfo(typeName, fieldName, readWriteBuffersCount++);
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType))
{
// Static scalar field
string typeName = HlslKnownTypes.GetMappedName(fieldType);
processedFieldInfo = new StaticScalarFieldInfo(typeName, fieldName, fieldValue);
}
else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}");
_FieldsInfo.Add(processedFieldInfo);
}
RootParameters = descriptorRanges.Select(range => new RootParameter(ShaderVisibility.All, range)).ToArray();
ReadWriteBuffers = readWriteBuffers;
}
/// <summary>
/// Loads the entry method for the current shader being loaded
/// </summary>
private void LoadMethodSource()
{
// Decompile the shader method
MethodDecompiler.Instance.GetSyntaxTree(Action.Method, out SyntaxNode root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel);
root = syntaxRewriter.Visit(root);
// Get the thread ids identifier name and shader method body
ConstructorDeclarationSyntax methodNode = root.ChildNodes().OfType<ConstructorDeclarationSyntax>().First();
ThreadsIdsVariableName = methodNode.ParameterList.Parameters.First().Identifier.Text;
MethodBody = methodNode.Body.ToFullString();
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"\d+[fFdD]", m => m.Value.Replace("f", ""));
}
}
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using ComputeSharp.Shaders.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A custom <see cref="CSharpSyntaxRewriter"/> <see langword="class"/> that processes C# methods to convert to HLSL
/// </summary>
public class ShaderSyntaxRewriter : CSharpSyntaxRewriter
{
/// <summary>
/// The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance to use to rewrite the decompiled code
/// </summary>
private readonly SemanticModel SemanticModel;
/// <summary>
/// Creates a new <see cref="ShaderSyntaxRewriter"/> instance with the specified parameters
/// </summary>
/// <param name="semanticModel"></param>
public ShaderSyntaxRewriter(SemanticModel semanticModel) => SemanticModel = semanticModel;
/// <inheritdoc/>
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node);
SyntaxTokenList modifiers = new SyntaxTokenList();
if (node.Modifiers.Any(SyntaxKind.StaticKeyword))
{
modifiers = modifiers.Add(SyntaxFactory.Token(default, SyntaxKind.StaticKeyword, SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))));
}
return node.ReplaceType(node.ReturnType).WithModifiers(modifiers);
}
/// <inheritdoc/>
public override SyntaxNode VisitParameter(ParameterSyntax node)
{
node = (ParameterSyntax)base.VisitParameter(node);
node = node.WithAttributeLists(default);
node = node.ReplaceType(node.Type);
return node;
}
/// <inheritdoc/>
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
node = (CastExpressionSyntax)base.VisitCastExpression(node);
return node.ReplaceType(node.Type);
}
/// <inheritdoc/>
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
return node.ReplaceType(node.Declaration.Type);
}
/// <inheritdoc/>
public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
node = (ObjectCreationExpressionSyntax)base.VisitObjectCreationExpression(node);
node = node.ReplaceType(node.Type);
if (node.ArgumentList.Arguments.Count == 0)
{
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
}
return SyntaxFactory.InvocationExpression(node.Type, node.ArgumentList);
}
/// <inheritdoc/>
public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node)
{
node = (DefaultExpressionSyntax)base.VisitDefaultExpression(node);
node = node.ReplaceType(node.Type);
return SyntaxFactory.CastExpression(node.Type, SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(0)));
}
/// <inheritdoc/>
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
node = (MemberAccessExpressionSyntax)base.VisitMemberAccessExpression(node);
return node.ReplaceMember(SemanticModel);
}
}
}