diff --git a/.editorconfig b/.editorconfig index 8a3054287..e5a5e6174 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,8 +1,7 @@ # Remove the line below if you want to inherit .editorconfig settings from higher directories root = true -# C# files -[*.cs] +[*] #### Core EditorConfig Options #### @@ -12,8 +11,11 @@ indent_style = space tab_width = 4 # New line preferences -end_of_line = crlf -insert_final_newline = false +end_of_line = lf +insert_final_newline = true + +# C# files +[*.cs] #### .NET Coding Conventions #### @@ -59,7 +61,7 @@ dotnet_style_prefer_simplified_interpolation = true:suggestion dotnet_style_readonly_field = true:suggestion # Parameter preferences -dotnet_code_quality_unused_parameters = all:suggestion +dotnet_code_quality_unused_parameters = all:silent #### C# Coding Conventions #### @@ -85,7 +87,7 @@ csharp_style_expression_bodied_properties = true:silent # Pattern matching preferences csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion -csharp_style_prefer_switch_expression = true:suggestion +csharp_style_prefer_switch_expression = false:silent # Null-checking preferences csharp_style_conditional_delegate_call = true:suggestion @@ -94,6 +96,7 @@ csharp_style_conditional_delegate_call = true:suggestion csharp_prefer_static_local_function = true:suggestion csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent csharp_style_prefer_readonly_struct = true +csharp_style_prefer_method_group_conversion = true # Code-block preferences csharp_prefer_braces = true:silent @@ -109,6 +112,7 @@ csharp_style_prefer_range_operator = true:suggestion csharp_style_throw_expression = true:suggestion csharp_style_unused_value_assignment_preference = discard_variable:suggestion csharp_style_unused_value_expression_statement_preference = discard_variable:silent +csharp_style_implicit_object_creation_when_type_is_apparent = true # 'using' directive preferences csharp_using_directive_placement = outside_namespace:silent @@ -140,7 +144,6 @@ csharp_space_after_dot = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_after_semicolon_in_for_statement = true csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false csharp_space_before_colon_in_inheritance_clause = true csharp_space_before_comma = false csharp_space_before_dot = false @@ -158,23 +161,31 @@ csharp_space_between_square_brackets = false # Wrapping preferences csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true +csharp_preserve_single_line_statements = false #### Naming styles #### # Naming rules -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i +dotnet_naming_rule.interfaces_should_be_prefixed_with_I.severity = suggestion +dotnet_naming_rule.interfaces_should_be_prefixed_with_I.symbols = interface +dotnet_naming_rule.interfaces_should_be_prefixed_with_I.style = IPascalCase dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.types_should_be_pascal_case.style = PascalCase dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = PascalCase + +dotnet_naming_rule.private_static_readonly_fields_should_be_camel_case_and_prefixed_with__.symbols = private_static_readonly_fields +dotnet_naming_rule.private_static_readonly_fields_should_be_camel_case_and_prefixed_with__.severity = suggestion +dotnet_naming_rule.private_static_readonly_fields_should_be_camel_case_and_prefixed_with__.style = _camelCase + +dotnet_naming_rule.local_constants_should_be_pascal_case.symbols = local_constants +dotnet_naming_rule.local_constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_constants_should_be_pascal_case.style = PascalCase # Symbol specifications @@ -190,14 +201,39 @@ dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, meth dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected dotnet_naming_symbols.non_field_members.required_modifiers = +dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private +dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = static, readonly + +dotnet_naming_symbols.local_constants.applicable_kinds = local +dotnet_naming_symbols.local_constants.applicable_accessibilities = local +dotnet_naming_symbols.local_constants.required_modifiers = const + # Naming styles -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case +dotnet_naming_style._camelCase.required_prefix = _ +dotnet_naming_style._camelCase.required_suffix = +dotnet_naming_style._camelCase.word_separator = +dotnet_naming_style._camelCase.capitalization = camel_case -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case \ No newline at end of file +dotnet_naming_style.PascalCase.required_prefix = +dotnet_naming_style.PascalCase.required_suffix = +dotnet_naming_style.PascalCase.word_separator = +dotnet_naming_style.PascalCase.capitalization = pascal_case + +dotnet_naming_style.IPascalCase.required_prefix = I +dotnet_naming_style.IPascalCase.required_suffix = +dotnet_naming_style.IPascalCase.word_separator = +dotnet_naming_style.IPascalCase.capitalization = pascal_case + +[src/Ryujinx.HLE/HOS/Services/**.cs] +# Disable "mark members as static" rule for services +dotnet_diagnostic.CA1822.severity = none + +[src/Ryujinx.Ava/UI/ViewModels/**.cs] +# Disable "mark members as static" rule for ViewModels +dotnet_diagnostic.CA1822.severity = none + +[src/Ryujinx.Tests/Cpu/*.cs] +# Disable naming rules for CPU tests +dotnet_diagnostic.IDE1006.severity = none diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..587830be1 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,33 @@ +audio: 'src/Ryujinx.Audio*/**' + +cpu: + - 'src/ARMeilleure/**' + - 'src/Ryujinx.Cpu/**' + - 'src/Ryujinx.Memory/**' + +gpu: + - 'src/Ryujinx.Graphics.*/**' + - 'src/Spv.Generator/**' + - 'src/Ryujinx.ShaderTools/**' + +'graphics-backend:opengl': 'src/Ryujinx.Graphics.OpenGL/**' +'graphics-backend:vulkan': + - 'src/Ryujinx.Graphics.Vulkan/**' + - 'src/Spv.Generator/**' + +gui: + - 'src/Ryujinx/**' + - 'src/Ryujinx.Ui.Common/**' + - 'src/Ryujinx.Ui.LocaleGenerator/**' + - 'src/Ryujinx.Ava/**' + +horizon: + - 'src/Ryujinx.HLE/**' + - 'src/Ryujinx.Horizon*/**' + +kernel: 'src/Ryujinx.HLE/HOS/Kernel/**' + +infra: + - '.github/**' + - 'distribution/**' + - 'Directory.Packages.props' \ No newline at end of file diff --git a/.github/reviewers.yml b/.github/reviewers.yml new file mode 100644 index 000000000..c0dc59dd5 --- /dev/null +++ b/.github/reviewers.yml @@ -0,0 +1,32 @@ +audio: + - marysaka + +cpu: + - gdkchan + - riperiperi + - marysaka + - LDj3SNuD + +gpu: + - gdkchan + - riperiperi + - marysaka + +gui: + - Ack77 + - emmauss + - TSRBerry + - marysaka + +horizon: + - gdkchan + - Ack77 + - marysaka + - TSRBerry + +infra: + - marysaka + - TSRBerry + +default: + - marysaka diff --git a/.github/update_reviewers.py b/.github/update_reviewers.py new file mode 100644 index 000000000..14c0cc285 --- /dev/null +++ b/.github/update_reviewers.py @@ -0,0 +1,79 @@ +from pathlib import Path +from typing import List, Set +from github import Github +from github.Repository import Repository +from github.GithubException import GithubException + +import sys +import yaml + + +def add_reviewers( + reviewers: Set[str], team_reviewers: Set[str], new_entries: List[str] +): + for reviewer in new_entries: + if reviewer.startswith("@"): + team_reviewers.add(reviewer[1:]) + else: + reviewers.add(reviewer) + + +def update_reviewers(config, repo: Repository, pr_id: int) -> int: + pull_request = repo.get_pull(pr_id) + + if not pull_request: + sys.stderr.writable(f"Unknown PR #{pr_id}\n") + return 1 + + pull_request_author = pull_request.user.login + reviewers = set() + team_reviewers = set() + + for label in pull_request.labels: + if label.name in config: + add_reviewers(reviewers, team_reviewers, config[label.name]) + + if "default" in config: + add_reviewers(reviewers, team_reviewers, config["default"]) + + if pull_request_author in reviewers: + reviewers.remove(pull_request_author) + + try: + reviewers = list(reviewers) + team_reviewers = list(team_reviewers) + print( + f"Attempting to assign reviewers ({reviewers}) and team_reviewers ({team_reviewers})" + ) + pull_request.create_review_request(reviewers, team_reviewers) + return 0 + except GithubException as e: + sys.stderr.write(f"Cannot assign review request for PR #{pr_id}: {e}\n") + return 1 + + +if __name__ == "__main__": + if len(sys.argv) != 5: + sys.stderr.write("usage: \n") + sys.exit(1) + + token = sys.argv[1] + repo_path = sys.argv[2] + pr_id = int(sys.argv[3]) + config_path = Path(sys.argv[4]) + + g = Github(token) + repo = g.get_repo(repo_path) + + if not repo: + sys.stderr.write("Repository not found!\n") + sys.exit(1) + + if not config_path.exists(): + sys.stderr.write(f'Config "{config_path}" not found!\n') + sys.exit(1) + + with open(config_path, "r") as f: + config = yaml.safe_load(f) + + sys.exit(update_reviewers(config, repo, pr_id)) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 97db387f0..c93fd0d30 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,25 +1,10 @@ name: Build job on: - workflow_dispatch: - inputs: {} - #push: - # branches: [ master ] - # paths-ignore: - # - '.github/*' - # - '.github/ISSUE_TEMPLATE/**' - # - '*.yml' - # - 'README.md' - pull_request: - branches: [ master ] - paths-ignore: - - '.github/*' - - '.github/ISSUE_TEMPLATE/**' - - '*.yml' - - 'README.md' + workflow_call: concurrency: - group: pr-checks-${{ github.event.number }} + group: pr-builds-${{ github.event.number }} cancel-in-progress: true env: diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 000000000..c34d196f2 --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,71 @@ +name: Perform checks + +on: + pull_request: + branches: [ master ] + paths: + - '**' + - '!.github/**' + - '!*.yml' + - '!*.config' + - '!README.md' + - '.github/workflows/*.yml' + +permissions: + pull-requests: write + checks: write + +concurrency: + group: pr-checks-${{ github.event.number }} + cancel-in-progress: true + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - uses: actions/setup-dotnet@v3 + with: + global-json-file: global.json + + - run: dotnet restore + + - name: Print dotnet format version + run: dotnet format --version + + - name: Run dotnet format whitespace + run: | + dotnet format whitespace --verify-no-changes --report ./whitespace-report.json -v d + + - name: Run dotnet format style + run: | + dotnet format style --severity info --verify-no-changes --report ./style-report.json -v d + + # For some reason this step sometimes fails with exit code 139 (segfault?), + # so should that be the case we'll try again (3 tries max). + - name: Run dotnet format analyzers + run: | + attempt=0 + exit_code=139 + until [ $attempt -ge 3 ] || [ $exit_code -ne 139 ]; do + ((attempt+=1)) + exit_code=0 + echo "Attempt: ${attempt}/3" + dotnet format analyzers --severity info --verify-no-changes --report ./analyzers-report.json -v d || exit_code=$? + done + exit $exit_code + + - name: Upload report + if: failure() + uses: actions/upload-artifact@v3 + with: + name: dotnet-format + path: ./*-report.json + + pr_build: + uses: ./.github/workflows/build.yml + needs: format + secrets: inherit diff --git a/.github/workflows/nightly_pr_comment.yml b/.github/workflows/nightly_pr_comment.yml index deabae670..f59a6be1f 100644 --- a/.github/workflows/nightly_pr_comment.yml +++ b/.github/workflows/nightly_pr_comment.yml @@ -1,8 +1,10 @@ name: Comment PR artifacts links + on: workflow_run: - workflows: ['Build job'] + workflows: ['Perform checks'] types: [completed] + jobs: pr_comment: if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' diff --git a/.github/workflows/pr_triage.yml b/.github/workflows/pr_triage.yml new file mode 100644 index 000000000..86e5084f2 --- /dev/null +++ b/.github/workflows/pr_triage.yml @@ -0,0 +1,34 @@ +name: "Pull Request Triage" +on: + pull_request_target: + types: [opened, ready_for_review] + +jobs: + triage: + permissions: + contents: read + pull-requests: write + + runs-on: ubuntu-latest + + steps: + # Grab sources to get update_reviewers.py and reviewers.yml + - name: Fetch sources + uses: actions/checkout@v3 + with: + # Ensure we pin the source origin as pull_request_target run under forks. + fetch-depth: 0 + repository: Ryujinx/Ryujinx + ref: master + + - name: Update labels based on changes + uses: actions/labeler@v4 + with: + sync-labels: true + dot: true + + - name: Assign reviewers + run: | + pip3 install PyGithub + python3 .github/update_reviewers.py ${{ secrets.GITHUB_TOKEN }} ${{ github.repository }} ${{ github.event.pull_request.number }} .github/reviewers.yml + shell: bash diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 98ba34822..63e6d0187 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,9 +6,10 @@ on: push: branches: [ master ] paths-ignore: - - '.github/*' - - '.github/ISSUE_TEMPLATE/**' + - '.github/**' - '*.yml' + - '*.json' + - '*.config' - 'README.md' concurrency: release diff --git a/Directory.Packages.props b/Directory.Packages.props index 9922f0719..bc740afcf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -20,8 +20,8 @@ - - + + @@ -34,7 +34,7 @@ - + @@ -44,9 +44,9 @@ - + - + diff --git a/distribution/macos/Info.plist b/distribution/macos/Info.plist index 6c3f7717c..968814f94 100644 --- a/distribution/macos/Info.plist +++ b/distribution/macos/Info.plist @@ -39,10 +39,15 @@ CSResourcesFileMapped NSHumanReadableCopyright - Copyright © 2018 - 2022 Ryujinx Team and Contributors. + Copyright © 2018 - 2023 Ryujinx Team and Contributors. LSApplicationCategoryType public.app-category.games LSMinimumSystemVersion 11.0 + LSEnvironment + + COMPlus_DefaultStackSize + 200000 + diff --git a/distribution/macos/create_macos_build.sh b/distribution/macos/create_macos_build.sh index 7405073d2..80594a40a 100755 --- a/distribution/macos/create_macos_build.sh +++ b/distribution/macos/create_macos_build.sh @@ -35,12 +35,12 @@ EXECUTABLE_SUB_PATH=Contents/MacOS/Ryujinx rm -rf "$TEMP_DIRECTORY" mkdir -p "$TEMP_DIRECTORY" -DOTNET_COMMON_ARGS="-p:DebugType=embedded -p:Version=$VERSION -p:SourceRevisionId=$SOURCE_REVISION_ID --self-contained true $EXTRA_ARGS" +DOTNET_COMMON_ARGS=(-p:DebugType=embedded -p:Version="$VERSION" -p:SourceRevisionId="$SOURCE_REVISION_ID" --self-contained true $EXTRA_ARGS) dotnet restore -dotnet build -c $CONFIGURATION src/Ryujinx.Ava -dotnet publish -c $CONFIGURATION -r osx-arm64 -o "$TEMP_DIRECTORY/publish_arm64" $DOTNET_COMMON_ARGS src/Ryujinx.Ava -dotnet publish -c $CONFIGURATION -r osx-x64 -o "$TEMP_DIRECTORY/publish_x64" $DOTNET_COMMON_ARGS src/Ryujinx.Ava +dotnet build -c "$CONFIGURATION" src/Ryujinx.Ava +dotnet publish -c "$CONFIGURATION" -r osx-arm64 -o "$TEMP_DIRECTORY/publish_arm64" "${DOTNET_COMMON_ARGS[@]}" src/Ryujinx.Ava +dotnet publish -c "$CONFIGURATION" -r osx-x64 -o "$TEMP_DIRECTORY/publish_x64" "${DOTNET_COMMON_ARGS[@]}" src/Ryujinx.Ava # Get rid of the support library for ARMeilleure for x64 (that's only for arm64) rm -rf "$TEMP_DIRECTORY/publish_x64/libarmeilleure-jitsupport.dylib" @@ -104,10 +104,10 @@ fi echo "Creating archive" pushd "$OUTPUT_DIRECTORY" -tar --exclude "Ryujinx.app/Contents/MacOS/Ryujinx" -cvf $RELEASE_TAR_FILE_NAME Ryujinx.app 1> /dev/null -python3 "$BASE_DIR/distribution/misc/add_tar_exec.py" $RELEASE_TAR_FILE_NAME "Ryujinx.app/Contents/MacOS/Ryujinx" "Ryujinx.app/Contents/MacOS/Ryujinx" -gzip -9 < $RELEASE_TAR_FILE_NAME > $RELEASE_TAR_FILE_NAME.gz -rm $RELEASE_TAR_FILE_NAME +tar --exclude "Ryujinx.app/Contents/MacOS/Ryujinx" -cvf "$RELEASE_TAR_FILE_NAME" Ryujinx.app 1> /dev/null +python3 "$BASE_DIR/distribution/misc/add_tar_exec.py" "$RELEASE_TAR_FILE_NAME" "Ryujinx.app/Contents/MacOS/Ryujinx" "Ryujinx.app/Contents/MacOS/Ryujinx" +gzip -9 < "$RELEASE_TAR_FILE_NAME" > "$RELEASE_TAR_FILE_NAME.gz" +rm "$RELEASE_TAR_FILE_NAME" popd echo "Done" \ No newline at end of file diff --git a/distribution/macos/updater.sh b/distribution/macos/updater.sh index 4d7dcdf23..12e4c3aa1 100755 --- a/distribution/macos/updater.sh +++ b/distribution/macos/updater.sh @@ -5,7 +5,7 @@ set -e INSTALL_DIRECTORY=$1 NEW_APP_DIRECTORY=$2 APP_PID=$3 -APP_ARGUMENTS="${@:4}" +APP_ARGUMENTS=("${@:4}") error_handler() { local lineno="$1" @@ -33,7 +33,7 @@ trap 'error_handler ${LINENO}' ERR attempt=0 while true; do - if lsof -p $APP_PID +r 1 &>/dev/null || ps -p "$APP_PID" &>/dev/null; then + if lsof -p "$APP_PID" +r 1 &>/dev/null || ps -p "$APP_PID" &>/dev/null; then if [ "$attempt" -eq 4 ]; then exit 1 fi @@ -53,5 +53,5 @@ mv "$NEW_APP_DIRECTORY" "$INSTALL_DIRECTORY" if [ "$#" -le 3 ]; then open -a "$INSTALL_DIRECTORY" else - open -a "$INSTALL_DIRECTORY" --args "$APP_ARGUMENTS" -fi + open -a "$INSTALL_DIRECTORY" --args "${APP_ARGUMENTS[@]}" +fi \ No newline at end of file diff --git a/src/ARMeilleure/Allocators.cs b/src/ARMeilleure/Allocators.cs index deabf9a26..ba782b99a 100644 --- a/src/ARMeilleure/Allocators.cs +++ b/src/ARMeilleure/Allocators.cs @@ -23,10 +23,7 @@ namespace ARMeilleure [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ArenaAllocator GetAllocator(ref ArenaAllocator alloc, uint pageSize, uint pageCount) { - if (alloc == null) - { - alloc = new ArenaAllocator(pageSize, pageCount); - } + alloc ??= new ArenaAllocator(pageSize, pageCount); return alloc; } diff --git a/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs b/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs index fdd4d0241..00ffd1958 100644 --- a/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs +++ b/src/ARMeilleure/CodeGen/Arm64/Arm64Optimizer.cs @@ -221,7 +221,7 @@ namespace ARMeilleure.CodeGen.Arm64 2 => Multiplier.x4, 3 => Multiplier.x8, 4 => Multiplier.x16, - _ => Multiplier.x1 + _ => Multiplier.x1, }; baseOp = indexOnSrc2 ? src1 : src2; diff --git a/src/ARMeilleure/CodeGen/Arm64/ArmCondition.cs b/src/ARMeilleure/CodeGen/Arm64/ArmCondition.cs index db27a8104..5db898591 100644 --- a/src/ARMeilleure/CodeGen/Arm64/ArmCondition.cs +++ b/src/ARMeilleure/CodeGen/Arm64/ArmCondition.cs @@ -5,22 +5,22 @@ namespace ARMeilleure.CodeGen.Arm64 { enum ArmCondition { - Eq = 0, - Ne = 1, + Eq = 0, + Ne = 1, GeUn = 2, LtUn = 3, - Mi = 4, - Pl = 5, - Vs = 6, - Vc = 7, + Mi = 4, + Pl = 5, + Vs = 6, + Vc = 7, GtUn = 8, LeUn = 9, - Ge = 10, - Lt = 11, - Gt = 12, - Le = 13, - Al = 14, - Nv = 15 + Ge = 10, + Lt = 11, + Gt = 12, + Le = 13, + Al = 14, + Nv = 15, } static class ComparisonArm64Extensions @@ -29,6 +29,7 @@ namespace ARMeilleure.CodeGen.Arm64 { return comp switch { +#pragma warning disable IDE0055 // Disable formatting Comparison.Equal => ArmCondition.Eq, Comparison.NotEqual => ArmCondition.Ne, Comparison.Greater => ArmCondition.Gt, @@ -39,8 +40,9 @@ namespace ARMeilleure.CodeGen.Arm64 Comparison.Less => ArmCondition.Lt, Comparison.GreaterOrEqualUI => ArmCondition.GeUn, Comparison.LessUI => ArmCondition.LtUn, +#pragma warning restore IDE0055 - _ => throw new ArgumentException(null, nameof(comp)) + _ => throw new ArgumentException(null, nameof(comp)), }; } } diff --git a/src/ARMeilleure/CodeGen/Arm64/ArmExtensionType.cs b/src/ARMeilleure/CodeGen/Arm64/ArmExtensionType.cs index 062a6d0b7..20ccfd4ba 100644 --- a/src/ARMeilleure/CodeGen/Arm64/ArmExtensionType.cs +++ b/src/ARMeilleure/CodeGen/Arm64/ArmExtensionType.cs @@ -9,6 +9,6 @@ namespace ARMeilleure.CodeGen.Arm64 Sxtb = 4, Sxth = 5, Sxtw = 6, - Sxtx = 7 + Sxtx = 7, } } diff --git a/src/ARMeilleure/CodeGen/Arm64/ArmShiftType.cs b/src/ARMeilleure/CodeGen/Arm64/ArmShiftType.cs index d223a1464..f32407c43 100644 --- a/src/ARMeilleure/CodeGen/Arm64/ArmShiftType.cs +++ b/src/ARMeilleure/CodeGen/Arm64/ArmShiftType.cs @@ -6,6 +6,6 @@ namespace ARMeilleure.CodeGen.Arm64 Lsl = 0, Lsr = 1, Asr = 2, - Ror = 3 + Ror = 3, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/Assembler.cs b/src/ARMeilleure/CodeGen/Arm64/Assembler.cs index 0ec0be7cb..41684faf2 100644 --- a/src/ARMeilleure/CodeGen/Arm64/Assembler.cs +++ b/src/ARMeilleure/CodeGen/Arm64/Assembler.cs @@ -188,7 +188,7 @@ namespace ARMeilleure.CodeGen.Arm64 uint rmode = topHalf ? 1u << 19 : 0u; uint ftype = rd.Type == OperandType.FP64 || rn.Type == OperandType.FP64 ? 1u << 22 : 0u; - uint sf = rd.Type == OperandType.I64 || rn.Type == OperandType.I64 ? SfFlag : 0u; + uint sf = rd.Type == OperandType.I64 || rn.Type == OperandType.I64 ? SfFlag : 0u; WriteUInt32(0x1e260000u | (opcode << 16) | rmode | ftype | sf | EncodeReg(rd) | (EncodeReg(rn) << 5)); } @@ -992,7 +992,7 @@ namespace ARMeilleure.CodeGen.Arm64 { OperandType.FP32 => 0, OperandType.FP64 => 1, - _ => 2 + _ => 2, }; instruction = vecInst | ((uint)opc << 30); @@ -1124,10 +1124,11 @@ namespace ARMeilleure.CodeGen.Arm64 OperandType.FP32 => 2, OperandType.FP64 => 3, OperandType.V128 => 4, - _ => throw new ArgumentException($"Invalid type {type}.") + _ => throw new ArgumentException($"Invalid type {type}."), }; } +#pragma warning disable IDE0051 // Remove unused private member private void WriteInt16(short value) { WriteUInt16((ushort)value); @@ -1142,6 +1143,7 @@ namespace ARMeilleure.CodeGen.Arm64 { _stream.WriteByte(value); } +#pragma warning restore IDE0051 private void WriteUInt16(ushort value) { diff --git a/src/ARMeilleure/CodeGen/Arm64/CallingConvention.cs b/src/ARMeilleure/CodeGen/Arm64/CallingConvention.cs index fda8d7867..a487c2ed3 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CallingConvention.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CallingConvention.cs @@ -93,4 +93,4 @@ namespace ARMeilleure.CodeGen.Arm64 return 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenCommon.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenCommon.cs index 8d1e597ba..1f0148d5e 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenCommon.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenCommon.cs @@ -88,4 +88,4 @@ namespace ARMeilleure.CodeGen.Arm64 return true; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs index 0dd5355f4..12ebabddd 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenContext.cs @@ -14,7 +14,7 @@ namespace ARMeilleure.CodeGen.Arm64 private const int CbnzInstLength = 4; private const int LdrLitInstLength = 4; - private Stream _stream; + private readonly Stream _stream; public int StreamOffset => (int)_stream.Length; @@ -32,7 +32,7 @@ namespace ARMeilleure.CodeGen.Arm64 private readonly Dictionary _visitedBlocks; private readonly Dictionary> _pendingBranches; - private struct ConstantPoolEntry + private readonly struct ConstantPoolEntry { public readonly int Offset; public readonly Symbol Symbol; @@ -58,7 +58,7 @@ namespace ARMeilleure.CodeGen.Arm64 private readonly bool _relocatable; - public CodeGenContext(AllocationResult allocResult, int maxCallArgs, int blocksCount, bool relocatable) + public CodeGenContext(AllocationResult allocResult, int maxCallArgs, bool relocatable) { _stream = MemoryStreamManager.Shared.GetStream(); @@ -93,10 +93,10 @@ namespace ARMeilleure.CodeGen.Arm64 if (_pendingBranches.TryGetValue(block, out var list)) { - foreach (var tuple in list) + foreach ((ArmCondition condition, long branchPos) in list) { - _stream.Seek(tuple.BranchPos, SeekOrigin.Begin); - WriteBranch(tuple.Condition, target); + _stream.Seek(branchPos, SeekOrigin.Begin); + WriteBranch(condition, target); } _stream.Seek(target, SeekOrigin.Begin); @@ -284,4 +284,4 @@ namespace ARMeilleure.CodeGen.Arm64 _stream.WriteByte((byte)(value >> 56)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs index fc4fa976e..2df86671a 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGenerator.cs @@ -10,7 +10,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; - using static ARMeilleure.IntermediateRepresentation.Operand; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -31,15 +30,16 @@ namespace ARMeilleure.CodeGen.Arm64 { Byte, Hword, - Auto + Auto, } - private static Action[] _instTable; + private static readonly Action[] _instTable; static CodeGenerator() { _instTable = new Action[EnumUtils.GetCount(typeof(Instruction))]; +#pragma warning disable IDE0055 // Disable formatting Add(Instruction.Add, GenerateAdd); Add(Instruction.BitwiseAnd, GenerateBitwiseAnd); Add(Instruction.BitwiseExclusiveOr, GenerateBitwiseExclusiveOr); @@ -48,7 +48,7 @@ namespace ARMeilleure.CodeGen.Arm64 Add(Instruction.BranchIf, GenerateBranchIf); Add(Instruction.ByteSwap, GenerateByteSwap); Add(Instruction.Call, GenerateCall); - //Add(Instruction.Clobber, GenerateClobber); + // Add(Instruction.Clobber, GenerateClobber); Add(Instruction.Compare, GenerateCompare); Add(Instruction.CompareAndSwap, GenerateCompareAndSwap); Add(Instruction.CompareAndSwap16, GenerateCompareAndSwap16); @@ -100,6 +100,7 @@ namespace ARMeilleure.CodeGen.Arm64 Add(Instruction.ZeroExtend16, GenerateZeroExtend16); Add(Instruction.ZeroExtend32, GenerateZeroExtend32); Add(Instruction.ZeroExtend8, GenerateZeroExtend8); +#pragma warning restore IDE0055 static void Add(Instruction inst, Action func) { @@ -131,7 +132,7 @@ namespace ARMeilleure.CodeGen.Arm64 StackAllocator stackAlloc = new(); - PreAllocator.RunPass(cctx, stackAlloc, out int maxCallArgs); + PreAllocator.RunPass(cctx, out int maxCallArgs); Logger.EndPass(PassName.PreAllocation, cfg); @@ -168,11 +169,9 @@ namespace ARMeilleure.CodeGen.Arm64 Logger.StartPass(PassName.CodeGeneration); - //Console.Error.WriteLine(IRDumper.GetDump(cfg)); - bool relocatable = (cctx.Options & CompilerOptions.Relocatable) != 0; - CodeGenContext context = new(allocResult, maxCallArgs, cfg.Blocks.Count, relocatable); + CodeGenContext context = new(allocResult, maxCallArgs, relocatable); UnwindInfo unwindInfo = WritePrologue(context); @@ -294,7 +293,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateBitwiseNot(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); ValidateUnOp(dest, source); @@ -332,7 +331,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateByteSwap(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); ValidateUnOp(dest, source); @@ -366,15 +365,15 @@ namespace ARMeilleure.CodeGen.Arm64 { if (operation.SourcesCount == 5) // CompareAndSwap128 has 5 sources, compared to CompareAndSwap64/32's 3. { - Operand actualLow = operation.GetDestination(0); - Operand actualHigh = operation.GetDestination(1); - Operand temp0 = operation.GetDestination(2); - Operand temp1 = operation.GetDestination(3); - Operand address = operation.GetSource(0); - Operand expectedLow = operation.GetSource(1); + Operand actualLow = operation.GetDestination(0); + Operand actualHigh = operation.GetDestination(1); + Operand temp0 = operation.GetDestination(2); + Operand temp1 = operation.GetDestination(3); + Operand address = operation.GetSource(0); + Operand expectedLow = operation.GetSource(1); Operand expectedHigh = operation.GetSource(2); - Operand desiredLow = operation.GetSource(3); - Operand desiredHigh = operation.GetSource(4); + Operand desiredLow = operation.GetSource(3); + Operand desiredHigh = operation.GetSource(4); GenerateAtomicDcas( context, @@ -390,11 +389,11 @@ namespace ARMeilleure.CodeGen.Arm64 } else { - Operand actual = operation.GetDestination(0); - Operand result = operation.GetDestination(1); - Operand address = operation.GetSource(0); + Operand actual = operation.GetDestination(0); + Operand result = operation.GetDestination(1); + Operand address = operation.GetSource(0); Operand expected = operation.GetSource(1); - Operand desired = operation.GetSource(2); + Operand desired = operation.GetSource(2); GenerateAtomicCas(context, address, expected, desired, actual, result, AccessSize.Auto); } @@ -402,22 +401,22 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateCompareAndSwap16(CodeGenContext context, Operation operation) { - Operand actual = operation.GetDestination(0); - Operand result = operation.GetDestination(1); - Operand address = operation.GetSource(0); + Operand actual = operation.GetDestination(0); + Operand result = operation.GetDestination(1); + Operand address = operation.GetSource(0); Operand expected = operation.GetSource(1); - Operand desired = operation.GetSource(2); + Operand desired = operation.GetSource(2); GenerateAtomicCas(context, address, expected, desired, actual, result, AccessSize.Hword); } private static void GenerateCompareAndSwap8(CodeGenContext context, Operation operation) { - Operand actual = operation.GetDestination(0); - Operand result = operation.GetDestination(1); - Operand address = operation.GetSource(0); + Operand actual = operation.GetDestination(0); + Operand result = operation.GetDestination(1); + Operand address = operation.GetSource(0); Operand expected = operation.GetSource(1); - Operand desired = operation.GetSource(2); + Operand desired = operation.GetSource(2); GenerateAtomicCas(context, address, expected, desired, actual, result, AccessSize.Byte); } @@ -446,13 +445,13 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(dest.Type.IsInteger()); Debug.Assert(src1.Type == OperandType.I32); - context.Assembler.Cmp (src1, Const(src1.Type, 0)); + context.Assembler.Cmp(src1, Const(src1.Type, 0)); context.Assembler.Csel(dest, src2, src3, ArmCondition.Ne); } private static void GenerateConvertI64ToI32(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.I32 && source.Type == OperandType.I64); @@ -462,7 +461,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateConvertToFP(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.FP32 || dest.Type == OperandType.FP64); @@ -481,7 +480,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateConvertToFPUI(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.FP32 || dest.Type == OperandType.FP64); @@ -493,7 +492,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateCopy(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); EnsureSameType(dest, source); @@ -525,7 +524,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateCountLeadingZeros(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); EnsureSameType(dest, source); @@ -537,9 +536,9 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateDivide(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand dividend = operation.GetSource(0); - Operand divisor = operation.GetSource(1); + Operand divisor = operation.GetSource(1); ValidateBinOp(dest, dividend, divisor); @@ -555,9 +554,9 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateDivideUI(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand dividend = operation.GetSource(0); - Operand divisor = operation.GetSource(1); + Operand divisor = operation.GetSource(1); ValidateBinOp(dest, dividend, divisor); @@ -566,7 +565,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateLoad(CodeGenContext context, Operation operation) { - Operand value = operation.Destination; + Operand value = operation.Destination; Operand address = operation.GetSource(0); context.Assembler.Ldr(value, address); @@ -574,7 +573,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateLoad16(CodeGenContext context, Operation operation) { - Operand value = operation.Destination; + Operand value = operation.Destination; Operand address = operation.GetSource(0); Debug.Assert(value.Type.IsInteger()); @@ -584,7 +583,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateLoad8(CodeGenContext context, Operation operation) { - Operand value = operation.Destination; + Operand value = operation.Destination; Operand address = operation.GetSource(0); Debug.Assert(value.Type.IsInteger()); @@ -643,7 +642,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateNegate(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); ValidateUnOp(dest, source); @@ -730,7 +729,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateSignExtend16(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -740,7 +739,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateSignExtend32(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -750,7 +749,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateSignExtend8(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -760,7 +759,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateFill(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand offset = operation.GetSource(0); Debug.Assert(offset.Kind == OperandKind.Constant); @@ -801,7 +800,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateStackAlloc(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand offset = operation.GetSource(0); Debug.Assert(offset.Kind == OperandKind.Constant); @@ -813,7 +812,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateStore(CodeGenContext context, Operation operation) { - Operand value = operation.GetSource(1); + Operand value = operation.GetSource(1); Operand address = operation.GetSource(0); context.Assembler.Str(value, address); @@ -821,7 +820,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateStore16(CodeGenContext context, Operation operation) { - Operand value = operation.GetSource(1); + Operand value = operation.GetSource(1); Operand address = operation.GetSource(0); Debug.Assert(value.Type.IsInteger()); @@ -831,7 +830,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateStore8(CodeGenContext context, Operation operation) { - Operand value = operation.GetSource(1); + Operand value = operation.GetSource(1); Operand address = operation.GetSource(0); Debug.Assert(value.Type.IsInteger()); @@ -878,7 +877,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateVectorCreateScalar(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); if (dest != default) @@ -1024,7 +1023,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateVectorZeroUpper64(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.V128 && source.Type == OperandType.V128); @@ -1034,7 +1033,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateVectorZeroUpper96(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.V128 && source.Type == OperandType.V128); @@ -1044,7 +1043,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateZeroExtend16(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1054,7 +1053,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateZeroExtend32(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1070,7 +1069,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static void GenerateZeroExtend8(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1080,7 +1079,7 @@ namespace ARMeilleure.CodeGen.Arm64 private static UnwindInfo WritePrologue(CodeGenContext context) { - List pushEntries = new List(); + List pushEntries = new(); Operand rsp = Register(SpRegister); @@ -1570,11 +1569,13 @@ namespace ARMeilleure.CodeGen.Arm64 Debug.Assert(op1.Type == op3.Type); } +#pragma warning disable IDE0051 // Remove unused private member private static void EnsureSameType(Operand op1, Operand op2, Operand op3, Operand op4) { Debug.Assert(op1.Type == op2.Type); Debug.Assert(op1.Type == op3.Type); Debug.Assert(op1.Type == op4.Type); } +#pragma warning restore IDE0051 } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/CodeGeneratorIntrinsic.cs b/src/ARMeilleure/CodeGen/Arm64/CodeGeneratorIntrinsic.cs index aaa00bb65..b87370557 100644 --- a/src/ARMeilleure/CodeGen/Arm64/CodeGeneratorIntrinsic.cs +++ b/src/ARMeilleure/CodeGen/Arm64/CodeGeneratorIntrinsic.cs @@ -179,6 +179,35 @@ namespace ARMeilleure.CodeGen.Arm64 (uint)operation.GetSource(2).AsInt32()); break; + case IntrinsicType.Vector128Unary: + GenerateVectorUnary( + context, + 1, + 0, + info.Inst, + operation.Destination, + operation.GetSource(0)); + break; + case IntrinsicType.Vector128Binary: + GenerateVectorBinary( + context, + 1, + 0, + info.Inst, + operation.Destination, + operation.GetSource(0), + operation.GetSource(1)); + break; + case IntrinsicType.Vector128BinaryRd: + GenerateVectorUnary( + context, + 1, + 0, + info.Inst, + operation.Destination, + operation.GetSource(1)); + break; + case IntrinsicType.VectorUnary: GenerateVectorUnary( context, @@ -659,4 +688,4 @@ namespace ARMeilleure.CodeGen.Arm64 context.Assembler.WriteInstruction(instruction, rd, rn); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/HardwareCapabilities.cs b/src/ARMeilleure/CodeGen/Arm64/HardwareCapabilities.cs index 99ff299e9..86afc2b4d 100644 --- a/src/ARMeilleure/CodeGen/Arm64/HardwareCapabilities.cs +++ b/src/ARMeilleure/CodeGen/Arm64/HardwareCapabilities.cs @@ -1,7 +1,4 @@ using System; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.Arm; using System.Runtime.Versioning; @@ -35,7 +32,7 @@ namespace ARMeilleure.CodeGen.Arm64 } } -#region Linux + #region Linux private const ulong AT_HWCAP = 16; private const ulong AT_HWCAP2 = 26; @@ -46,88 +43,88 @@ namespace ARMeilleure.CodeGen.Arm64 [Flags] public enum LinuxFeatureFlagsHwCap : ulong { - Fp = 1 << 0, - Asimd = 1 << 1, - Evtstrm = 1 << 2, - Aes = 1 << 3, - Pmull = 1 << 4, - Sha1 = 1 << 5, - Sha2 = 1 << 6, - Crc32 = 1 << 7, - Atomics = 1 << 8, - FpHp = 1 << 9, - AsimdHp = 1 << 10, - CpuId = 1 << 11, - AsimdRdm = 1 << 12, - Jscvt = 1 << 13, - Fcma = 1 << 14, - Lrcpc = 1 << 15, - DcpOp = 1 << 16, - Sha3 = 1 << 17, - Sm3 = 1 << 18, - Sm4 = 1 << 19, - AsimdDp = 1 << 20, - Sha512 = 1 << 21, - Sve = 1 << 22, - AsimdFhm = 1 << 23, - Dit = 1 << 24, - Uscat = 1 << 25, - Ilrcpc = 1 << 26, - FlagM = 1 << 27, - Ssbs = 1 << 28, - Sb = 1 << 29, - Paca = 1 << 30, - Pacg = 1UL << 31 + Fp = 1 << 0, + Asimd = 1 << 1, + Evtstrm = 1 << 2, + Aes = 1 << 3, + Pmull = 1 << 4, + Sha1 = 1 << 5, + Sha2 = 1 << 6, + Crc32 = 1 << 7, + Atomics = 1 << 8, + FpHp = 1 << 9, + AsimdHp = 1 << 10, + CpuId = 1 << 11, + AsimdRdm = 1 << 12, + Jscvt = 1 << 13, + Fcma = 1 << 14, + Lrcpc = 1 << 15, + DcpOp = 1 << 16, + Sha3 = 1 << 17, + Sm3 = 1 << 18, + Sm4 = 1 << 19, + AsimdDp = 1 << 20, + Sha512 = 1 << 21, + Sve = 1 << 22, + AsimdFhm = 1 << 23, + Dit = 1 << 24, + Uscat = 1 << 25, + Ilrcpc = 1 << 26, + FlagM = 1 << 27, + Ssbs = 1 << 28, + Sb = 1 << 29, + Paca = 1 << 30, + Pacg = 1UL << 31, } [Flags] public enum LinuxFeatureFlagsHwCap2 : ulong { - Dcpodp = 1 << 0, - Sve2 = 1 << 1, - SveAes = 1 << 2, - SvePmull = 1 << 3, - SveBitperm = 1 << 4, - SveSha3 = 1 << 5, - SveSm4 = 1 << 6, - FlagM2 = 1 << 7, - Frint = 1 << 8, - SveI8mm = 1 << 9, - SveF32mm = 1 << 10, - SveF64mm = 1 << 11, - SveBf16 = 1 << 12, - I8mm = 1 << 13, - Bf16 = 1 << 14, - Dgh = 1 << 15, - Rng = 1 << 16, - Bti = 1 << 17, - Mte = 1 << 18, - Ecv = 1 << 19, - Afp = 1 << 20, - Rpres = 1 << 21, - Mte3 = 1 << 22, - Sme = 1 << 23, - Sme_i16i64 = 1 << 24, - Sme_f64f64 = 1 << 25, - Sme_i8i32 = 1 << 26, - Sme_f16f32 = 1 << 27, - Sme_b16f32 = 1 << 28, - Sme_f32f32 = 1 << 29, - Sme_fa64 = 1 << 30, - Wfxt = 1UL << 31, - Ebf16 = 1UL << 32, - Sve_Ebf16 = 1UL << 33, - Cssc = 1UL << 34, - Rprfm = 1UL << 35, - Sve2p1 = 1UL << 36 + Dcpodp = 1 << 0, + Sve2 = 1 << 1, + SveAes = 1 << 2, + SvePmull = 1 << 3, + SveBitperm = 1 << 4, + SveSha3 = 1 << 5, + SveSm4 = 1 << 6, + FlagM2 = 1 << 7, + Frint = 1 << 8, + SveI8mm = 1 << 9, + SveF32mm = 1 << 10, + SveF64mm = 1 << 11, + SveBf16 = 1 << 12, + I8mm = 1 << 13, + Bf16 = 1 << 14, + Dgh = 1 << 15, + Rng = 1 << 16, + Bti = 1 << 17, + Mte = 1 << 18, + Ecv = 1 << 19, + Afp = 1 << 20, + Rpres = 1 << 21, + Mte3 = 1 << 22, + Sme = 1 << 23, + Sme_i16i64 = 1 << 24, + Sme_f64f64 = 1 << 25, + Sme_i8i32 = 1 << 26, + Sme_f16f32 = 1 << 27, + Sme_b16f32 = 1 << 28, + Sme_f32f32 = 1 << 29, + Sme_fa64 = 1 << 30, + Wfxt = 1UL << 31, + Ebf16 = 1UL << 32, + Sve_Ebf16 = 1UL << 33, + Cssc = 1UL << 34, + Rprfm = 1UL << 35, + Sve2p1 = 1UL << 36, } public static LinuxFeatureFlagsHwCap LinuxFeatureInfoHwCap { get; } = 0; public static LinuxFeatureFlagsHwCap2 LinuxFeatureInfoHwCap2 { get; } = 0; -#endregion + #endregion -#region macOS + #region macOS [LibraryImport("libSystem.dylib", SetLastError = true)] private static unsafe partial int sysctlbyname([MarshalAs(UnmanagedType.LPStr)] string name, out int oldValue, ref ulong oldSize, IntPtr newValue, ulong newValueSize); @@ -143,7 +140,7 @@ namespace ARMeilleure.CodeGen.Arm64 return false; } - private static string[] _sysctlNames = new string[] + private static readonly string[] _sysctlNames = new string[] { "hw.optional.floatingpoint", "hw.optional.AdvSIMD", @@ -153,26 +150,26 @@ namespace ARMeilleure.CodeGen.Arm64 "hw.optional.arm.FEAT_LSE", "hw.optional.armv8_crc32", "hw.optional.arm.FEAT_SHA1", - "hw.optional.arm.FEAT_SHA256" + "hw.optional.arm.FEAT_SHA256", }; [Flags] public enum MacOsFeatureFlags { - Fp = 1 << 0, + Fp = 1 << 0, AdvSimd = 1 << 1, - Fp16 = 1 << 2, - Aes = 1 << 3, - Pmull = 1 << 4, - Lse = 1 << 5, - Crc32 = 1 << 6, - Sha1 = 1 << 7, - Sha256 = 1 << 8 + Fp16 = 1 << 2, + Aes = 1 << 3, + Pmull = 1 << 4, + Lse = 1 << 5, + Crc32 = 1 << 6, + Sha1 = 1 << 7, + Sha256 = 1 << 8, } public static MacOsFeatureFlags MacOsFeatureInfo { get; } = 0; -#endregion + #endregion public static bool SupportsAdvSimd => LinuxFeatureInfoHwCap.HasFlag(LinuxFeatureFlagsHwCap.Asimd) || MacOsFeatureInfo.HasFlag(MacOsFeatureFlags.AdvSimd); public static bool SupportsAes => LinuxFeatureInfoHwCap.HasFlag(LinuxFeatureFlagsHwCap.Aes) || MacOsFeatureInfo.HasFlag(MacOsFeatureFlags.Aes); diff --git a/src/ARMeilleure/CodeGen/Arm64/IntrinsicInfo.cs b/src/ARMeilleure/CodeGen/Arm64/IntrinsicInfo.cs index 8695db903..956fc778d 100644 --- a/src/ARMeilleure/CodeGen/Arm64/IntrinsicInfo.cs +++ b/src/ARMeilleure/CodeGen/Arm64/IntrinsicInfo.cs @@ -1,8 +1,8 @@ namespace ARMeilleure.CodeGen.Arm64 { - struct IntrinsicInfo + readonly struct IntrinsicInfo { - public uint Inst { get; } + public uint Inst { get; } public IntrinsicType Type { get; } public IntrinsicInfo(uint inst, IntrinsicType type) @@ -11,4 +11,4 @@ namespace ARMeilleure.CodeGen.Arm64 Type = type; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/IntrinsicTable.cs b/src/ARMeilleure/CodeGen/Arm64/IntrinsicTable.cs index a309d56d9..dbd5bdd10 100644 --- a/src/ARMeilleure/CodeGen/Arm64/IntrinsicTable.cs +++ b/src/ARMeilleure/CodeGen/Arm64/IntrinsicTable.cs @@ -5,12 +5,13 @@ namespace ARMeilleure.CodeGen.Arm64 { static class IntrinsicTable { - private static IntrinsicInfo[] _intrinTable; + private static readonly IntrinsicInfo[] _intrinTable; static IntrinsicTable() { _intrinTable = new IntrinsicInfo[EnumUtils.GetCount(typeof(Intrinsic))]; +#pragma warning disable IDE0055 // Disable formatting Add(Intrinsic.Arm64AbsS, new IntrinsicInfo(0x5e20b800u, IntrinsicType.ScalarUnary)); Add(Intrinsic.Arm64AbsV, new IntrinsicInfo(0x0e20b800u, IntrinsicType.VectorUnary)); Add(Intrinsic.Arm64AddhnV, new IntrinsicInfo(0x0e204000u, IntrinsicType.VectorTernaryRd)); @@ -19,8 +20,8 @@ namespace ARMeilleure.CodeGen.Arm64 Add(Intrinsic.Arm64AddvV, new IntrinsicInfo(0x0e31b800u, IntrinsicType.VectorUnary)); Add(Intrinsic.Arm64AddS, new IntrinsicInfo(0x5e208400u, IntrinsicType.ScalarBinary)); Add(Intrinsic.Arm64AddV, new IntrinsicInfo(0x0e208400u, IntrinsicType.VectorBinary)); - Add(Intrinsic.Arm64AesdV, new IntrinsicInfo(0x4e285800u, IntrinsicType.Vector128Unary)); - Add(Intrinsic.Arm64AeseV, new IntrinsicInfo(0x4e284800u, IntrinsicType.Vector128Unary)); + Add(Intrinsic.Arm64AesdV, new IntrinsicInfo(0x4e285800u, IntrinsicType.Vector128BinaryRd)); + Add(Intrinsic.Arm64AeseV, new IntrinsicInfo(0x4e284800u, IntrinsicType.Vector128BinaryRd)); Add(Intrinsic.Arm64AesimcV, new IntrinsicInfo(0x4e287800u, IntrinsicType.Vector128Unary)); Add(Intrinsic.Arm64AesmcV, new IntrinsicInfo(0x4e286800u, IntrinsicType.Vector128Unary)); Add(Intrinsic.Arm64AndV, new IntrinsicInfo(0x0e201c00u, IntrinsicType.VectorBinaryBitwise)); @@ -448,6 +449,7 @@ namespace ARMeilleure.CodeGen.Arm64 Add(Intrinsic.Arm64XtnV, new IntrinsicInfo(0x0e212800u, IntrinsicType.VectorUnary)); Add(Intrinsic.Arm64Zip1V, new IntrinsicInfo(0x0e003800u, IntrinsicType.VectorBinary)); Add(Intrinsic.Arm64Zip2V, new IntrinsicInfo(0x0e007800u, IntrinsicType.VectorBinary)); +#pragma warning restore IDE0055 } private static void Add(Intrinsic intrin, IntrinsicInfo info) @@ -460,4 +462,4 @@ namespace ARMeilleure.CodeGen.Arm64 return _intrinTable[(int)intrin]; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/IntrinsicType.cs b/src/ARMeilleure/CodeGen/Arm64/IntrinsicType.cs index 800eca93c..7538575c9 100644 --- a/src/ARMeilleure/CodeGen/Arm64/IntrinsicType.cs +++ b/src/ARMeilleure/CodeGen/Arm64/IntrinsicType.cs @@ -23,6 +23,10 @@ namespace ARMeilleure.CodeGen.Arm64 ScalarTernaryShlRd, ScalarTernaryShrRd, + Vector128Unary, + Vector128Binary, + Vector128BinaryRd, + VectorUnary, VectorUnaryBitwise, VectorUnaryByElem, @@ -50,10 +54,7 @@ namespace ARMeilleure.CodeGen.Arm64 VectorTernaryShlRd, VectorTernaryShrRd, - Vector128Unary, - Vector128Binary, - GetRegister, - SetRegister + SetRegister, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs b/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs index 6ea9d2397..f66bb66e6 100644 --- a/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs +++ b/src/ARMeilleure/CodeGen/Arm64/PreAllocator.cs @@ -1,4 +1,3 @@ -using ARMeilleure.CodeGen.RegisterAllocators; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; @@ -31,7 +30,7 @@ namespace ARMeilleure.CodeGen.Arm64 } } - public static void RunPass(CompilerContext cctx, StackAllocator stackAlloc, out int maxCallArgs) + public static void RunPass(CompilerContext cctx, out int maxCallArgs) { maxCallArgs = -1; @@ -41,7 +40,7 @@ namespace ARMeilleure.CodeGen.Arm64 for (BasicBlock block = cctx.Cfg.Blocks.First; block != null; block = block.ListNext) { - ConstantDict constants = new ConstantDict(); + ConstantDict constants = new(); Operation nextNode; @@ -92,7 +91,7 @@ namespace ARMeilleure.CodeGen.Arm64 InsertReturnCopy(block.Operations, node); break; case Instruction.Tailcall: - InsertTailcallCopies(constants, block.Operations, stackAlloc, node, node); + InsertTailcallCopies(constants, block.Operations, node, node); break; } } @@ -138,10 +137,7 @@ namespace ARMeilleure.CodeGen.Arm64 { src2 = node.GetSource(1); - Operand temp = src1; - - src1 = src2; - src2 = temp; + (src2, src1) = (src1, src2); node.SetSource(0, src1); node.SetSource(1, src2); @@ -265,9 +261,9 @@ namespace ARMeilleure.CodeGen.Arm64 Operand dest = operation.Destination; - List sources = new List + List sources = new() { - operation.GetSource(0) + operation.GetSource(0), }; int argsCount = operation.SourcesCount - 1; @@ -302,10 +298,10 @@ namespace ARMeilleure.CodeGen.Arm64 if (source.Type == OperandType.V128 && passOnReg) { // V128 is a struct, we pass each half on a GPR if possible. - Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); + Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); Operand argReg2 = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); - nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0))); + nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0))); nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg2, source, Const(1))); continue; @@ -339,7 +335,7 @@ namespace ARMeilleure.CodeGen.Arm64 { if (dest.Type == OperandType.V128) { - Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); + Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); Operand retHReg = Gpr(CallingConvention.GetIntReturnRegisterHigh(), OperandType.I64); node = nodes.AddAfter(node, Operation(Instruction.VectorCreateScalar, dest, retLReg)); @@ -364,16 +360,14 @@ namespace ARMeilleure.CodeGen.Arm64 operation.SetSources(sources.ToArray()); } - private static void InsertTailcallCopies( - ConstantDict constants, + private static void InsertTailcallCopies(ConstantDict constants, IntrusiveList nodes, - StackAllocator stackAlloc, Operation node, Operation operation) { - List sources = new List + List sources = new() { - operation.GetSource(0) + operation.GetSource(0), }; int argsCount = operation.SourcesCount - 1; @@ -403,7 +397,7 @@ namespace ARMeilleure.CodeGen.Arm64 if (source.Type == OperandType.V128 && passOnReg) { // V128 is a struct, we pass each half on a GPR if possible. - Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); + Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); Operand argReg2 = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0))); @@ -519,7 +513,7 @@ namespace ARMeilleure.CodeGen.Arm64 if (source.Type == OperandType.V128) { - Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); + Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); Operand retHReg = Gpr(CallingConvention.GetIntReturnRegisterHigh(), OperandType.I64); nodes.AddBefore(node, Operation(Instruction.VectorExtract, retLReg, source, Const(0))); @@ -746,6 +740,7 @@ namespace ARMeilleure.CodeGen.Arm64 info.Type == IntrinsicType.ScalarTernaryFPRdByElem || info.Type == IntrinsicType.ScalarTernaryShlRd || info.Type == IntrinsicType.ScalarTernaryShrRd || + info.Type == IntrinsicType.Vector128BinaryRd || info.Type == IntrinsicType.VectorBinaryRd || info.Type == IntrinsicType.VectorInsertByElem || info.Type == IntrinsicType.VectorTernaryRd || diff --git a/src/ARMeilleure/CodeGen/CompiledFunction.cs b/src/ARMeilleure/CodeGen/CompiledFunction.cs index 0560bf2e9..3844cbfc9 100644 --- a/src/ARMeilleure/CodeGen/CompiledFunction.cs +++ b/src/ARMeilleure/CodeGen/CompiledFunction.cs @@ -35,9 +35,9 @@ namespace ARMeilleure.CodeGen /// Relocation info internal CompiledFunction(byte[] code, UnwindInfo unwindInfo, RelocInfo relocInfo) { - Code = code; + Code = code; UnwindInfo = unwindInfo; - RelocInfo = relocInfo; + RelocInfo = relocInfo; } /// @@ -65,4 +65,4 @@ namespace ARMeilleure.CodeGen return Marshal.GetDelegateForFunctionPointer(codePointer); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Linking/RelocEntry.cs b/src/ARMeilleure/CodeGen/Linking/RelocEntry.cs index a27bfded2..d103bc395 100644 --- a/src/ARMeilleure/CodeGen/Linking/RelocEntry.cs +++ b/src/ARMeilleure/CodeGen/Linking/RelocEntry.cs @@ -35,4 +35,4 @@ namespace ARMeilleure.CodeGen.Linking return $"({nameof(Position)} = {Position}, {nameof(Symbol)} = {Symbol})"; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Linking/RelocInfo.cs b/src/ARMeilleure/CodeGen/Linking/RelocInfo.cs index caaf08e3d..01ff0347b 100644 --- a/src/ARMeilleure/CodeGen/Linking/RelocInfo.cs +++ b/src/ARMeilleure/CodeGen/Linking/RelocInfo.cs @@ -29,4 +29,4 @@ namespace ARMeilleure.CodeGen.Linking _entries = entries; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Linking/SymbolType.cs b/src/ARMeilleure/CodeGen/Linking/SymbolType.cs index b05b69692..ed348751b 100644 --- a/src/ARMeilleure/CodeGen/Linking/SymbolType.cs +++ b/src/ARMeilleure/CodeGen/Linking/SymbolType.cs @@ -23,6 +23,6 @@ /// /// Refers to a special symbol which is handled by . /// - Special + Special, } } diff --git a/src/ARMeilleure/CodeGen/Optimizations/ConstantFolding.cs b/src/ARMeilleure/CodeGen/Optimizations/ConstantFolding.cs index c5a22a537..be3dff58c 100644 --- a/src/ARMeilleure/CodeGen/Optimizations/ConstantFolding.cs +++ b/src/ARMeilleure/CodeGen/Optimizations/ConstantFolding.cs @@ -164,7 +164,7 @@ namespace ARMeilleure.CodeGen.Optimizations } break; - case Instruction.Multiply: + case Instruction.Multiply: if (type == OperandType.I32) { EvaluateBinaryI32(operation, (x, y) => x * y); @@ -343,4 +343,4 @@ namespace ARMeilleure.CodeGen.Optimizations operation.TurnIntoCopy(Const(op(x, y))); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Optimizations/Optimizer.cs b/src/ARMeilleure/CodeGen/Optimizations/Optimizer.cs index a45bb4551..1afc3a782 100644 --- a/src/ARMeilleure/CodeGen/Optimizations/Optimizer.cs +++ b/src/ARMeilleure/CodeGen/Optimizations/Optimizer.cs @@ -182,7 +182,7 @@ namespace ARMeilleure.CodeGen.Optimizations private static void PropagateCopy(ref Span buffer, Operation copyOp) { // Propagate copy source operand to all uses of the destination operand. - Operand dest = copyOp.Destination; + Operand dest = copyOp.Destination; Operand source = copyOp.GetSource(0); Span uses = dest.GetUses(ref buffer); @@ -249,4 +249,4 @@ namespace ARMeilleure.CodeGen.Optimizations return operation.Destination.Type == operation.GetSource(0).Type; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Optimizations/Simplification.cs b/src/ARMeilleure/CodeGen/Optimizations/Simplification.cs index a439d6424..53a7f3ede 100644 --- a/src/ARMeilleure/CodeGen/Optimizations/Simplification.cs +++ b/src/ARMeilleure/CodeGen/Optimizations/Simplification.cs @@ -171,13 +171,12 @@ namespace ARMeilleure.CodeGen.Optimizations private static ulong AllOnes(OperandType type) { - switch (type) + return type switch { - case OperandType.I32: return ~0U; - case OperandType.I64: return ~0UL; - } - - throw new ArgumentException("Invalid operand type \"" + type + "\"."); + OperandType.I32 => ~0U, + OperandType.I64 => ~0UL, + _ => throw new ArgumentException("Invalid operand type \"" + type + "\"."), + }; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/AllocationResult.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/AllocationResult.cs index 43e5c7e2c..7b9c2f77f 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/AllocationResult.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/AllocationResult.cs @@ -4,7 +4,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { public int IntUsedRegisters { get; } public int VecUsedRegisters { get; } - public int SpillRegionSize { get; } + public int SpillRegionSize { get; } public AllocationResult( int intUsedRegisters, @@ -13,7 +13,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { IntUsedRegisters = intUsedRegisters; VecUsedRegisters = vecUsedRegisters; - SpillRegionSize = spillRegionSize; + SpillRegionSize = spillRegionSize; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/CopyResolver.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/CopyResolver.cs index 587b1a024..af10330ba 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/CopyResolver.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/CopyResolver.cs @@ -1,7 +1,6 @@ using ARMeilleure.IntermediateRepresentation; using System; using System.Collections.Generic; - using static ARMeilleure.IntermediateRepresentation.Operand.Factory; using static ARMeilleure.IntermediateRepresentation.Operation.Factory; @@ -13,16 +12,16 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { private readonly struct Copy { - public Register Dest { get; } + public Register Dest { get; } public Register Source { get; } public OperandType Type { get; } public Copy(Register dest, Register source, OperandType type) { - Dest = dest; + Dest = dest; Source = source; - Type = type; + Type = type; } } @@ -42,19 +41,19 @@ namespace ARMeilleure.CodeGen.RegisterAllocators public void Sequence(List sequence) { - Dictionary locations = new Dictionary(); - Dictionary sources = new Dictionary(); + Dictionary locations = new(); + Dictionary sources = new(); - Dictionary types = new Dictionary(); + Dictionary types = new(); - Queue pendingQueue = new Queue(); - Queue readyQueue = new Queue(); + Queue pendingQueue = new(); + Queue readyQueue = new(); foreach (Copy copy in _copies) { locations[copy.Source] = copy.Source; - sources[copy.Dest] = copy.Source; - types[copy.Dest] = copy.Type; + sources[copy.Dest] = copy.Source; + types[copy.Dest] = copy.Type; pendingQueue.Enqueue(copy.Dest); } @@ -91,7 +90,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators } } - copyDest = current; + copyDest = current; origSource = sources[copyDest]; copySource = locations[origSource]; @@ -186,10 +185,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private void AddSplitFill(LiveInterval left, LiveInterval right, OperandType type) { - if (_fillQueue == null) - { - _fillQueue = new Queue(); - } + _fillQueue ??= new Queue(); Operand register = GetRegister(right.Register, type); Operand offset = Const(left.SpillOffset); @@ -201,10 +197,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private void AddSplitSpill(LiveInterval left, LiveInterval right, OperandType type) { - if (_spillQueue == null) - { - _spillQueue = new Queue(); - } + _spillQueue ??= new Queue(); Operand offset = Const(right.SpillOffset); Operand register = GetRegister(left.Register, type); @@ -216,10 +209,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private void AddSplitCopy(LiveInterval left, LiveInterval right, OperandType type) { - if (_parallelCopy == null) - { - _parallelCopy = new ParallelCopy(); - } + _parallelCopy ??= new ParallelCopy(); _parallelCopy.AddCopy(right.Register, left.Register, type); @@ -228,7 +218,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators public Operation[] Sequence() { - List sequence = new List(); + List sequence = new(); if (_spillQueue != null) { @@ -256,4 +246,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators return Register(reg.Index, reg.Type, type); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/HybridAllocator.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/HybridAllocator.cs index 25952c775..5f1d6ce89 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/HybridAllocator.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/HybridAllocator.cs @@ -20,7 +20,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators public BlockInfo(bool hasCall, int intFixedRegisters, int vecFixedRegisters) { - HasCall = hasCall; + HasCall = hasCall; IntFixedRegisters = intFixedRegisters; VecFixedRegisters = vecFixedRegisters; } @@ -39,7 +39,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private int _first; private int _last; - public bool IsBlockLocal => _first == _last; + public readonly bool IsBlockLocal => _first == _last; public LocalInfo(OperandType type, int uses, int blkIndex) { @@ -53,7 +53,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators SpillOffset = default; _first = -1; - _last = -1; + _last = -1; SetBlockIndex(blkIndex); } @@ -348,17 +348,17 @@ namespace ARMeilleure.CodeGen.RegisterAllocators if (dest.Type.IsInteger()) { intLocalFreeRegisters &= ~(1 << selectedReg); - intUsedRegisters |= 1 << selectedReg; + intUsedRegisters |= 1 << selectedReg; } else { vecLocalFreeRegisters &= ~(1 << selectedReg); - vecUsedRegisters |= 1 << selectedReg; + vecUsedRegisters |= 1 << selectedReg; } } else { - info.Register = default; + info.Register = default; info.SpillOffset = Const(stackAlloc.Allocate(dest.Type.GetSizeInBytes())); } } @@ -382,7 +382,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators : GetSpillTemp(dest, vecSpillTempRegisters, ref vecLocalAsg); info.Sequence = sequence; - info.Temp = temp; + info.Temp = temp; } dest = temp; @@ -408,7 +408,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private static int SelectSpillTemps(int mask0, int mask1) { int selection = 0; - int count = 0; + int count = 0; while (count < MaxIROperands && mask0 != 0) { @@ -451,4 +451,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators return local.AssignmentsCount + local.UsesCount; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/IRegisterAllocator.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/IRegisterAllocator.cs index 8f236c253..7d4ce2ea6 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/IRegisterAllocator.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/IRegisterAllocator.cs @@ -9,4 +9,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators StackAllocator stackAlloc, RegisterMasks regMasks); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs index d80157afb..f156e0886 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LinearScanAllocator.cs @@ -14,7 +14,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators // http://www.christianwimmer.at/Publications/Wimmer04a/Wimmer04a.pdf class LinearScanAllocator : IRegisterAllocator { - private const int InstructionGap = 2; + private const int InstructionGap = 2; private const int InstructionGapMask = InstructionGap - 1; private HashSet _blockEdges; @@ -33,7 +33,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators public StackAllocator StackAlloc { get; } - public BitMap Active { get; } + public BitMap Active { get; } public BitMap Inactive { get; } public int IntUsedRegisters { get; set; } @@ -47,9 +47,9 @@ namespace ARMeilleure.CodeGen.RegisterAllocators public AllocationContext(StackAllocator stackAlloc, RegisterMasks masks, int intervalsCount) { StackAlloc = stackAlloc; - Masks = masks; + Masks = masks; - Active = new BitMap(Allocators.Default, intervalsCount); + Active = new BitMap(Allocators.Default, intervalsCount); Inactive = new BitMap(Allocators.Default, intervalsCount); PopulateFreePositions(RegisterType.Integer, out _intFreePositions, out _intFreePositionsCount); @@ -443,7 +443,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators if (highest < current) { - highest = current; + highest = current; selected = index; if (current == int.MaxValue) @@ -485,9 +485,9 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private void SplitAndSpillOverlappingInterval( AllocationContext context, - LiveInterval current, - LiveInterval interval, - int registersCount) + LiveInterval current, + LiveInterval interval, + int registersCount) { // If there's a next use after the start of the current interval, // we need to split the spilled interval twice, and re-insert it @@ -530,8 +530,8 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private void InsertInterval(LiveInterval interval, int registersCount) { Debug.Assert(interval.UsesCount != 0, "Trying to insert a interval without uses."); - Debug.Assert(!interval.IsEmpty, "Trying to insert a empty interval."); - Debug.Assert(!interval.IsSpilled, "Trying to insert a spilled interval."); + Debug.Assert(!interval.IsEmpty, "Trying to insert a empty interval."); + Debug.Assert(!interval.IsSpilled, "Trying to insert a spilled interval."); int startIndex = registersCount * 2; @@ -545,9 +545,9 @@ namespace ARMeilleure.CodeGen.RegisterAllocators _intervals.Insert(insertIndex, interval); } - private void Spill(AllocationContext context, LiveInterval interval) + private static void Spill(AllocationContext context, LiveInterval interval) { - Debug.Assert(!interval.IsFixed, "Trying to spill a fixed interval."); + Debug.Assert(!interval.IsFixed, "Trying to spill a fixed interval."); Debug.Assert(interval.UsesCount == 0, "Trying to spill a interval with uses."); // We first check if any of the siblings were spilled, if so we can reuse @@ -561,7 +561,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private void InsertSplitCopies() { - Dictionary copyResolvers = new Dictionary(); + Dictionary copyResolvers = new(); CopyResolver GetCopyResolver(int position) { @@ -668,18 +668,15 @@ namespace ARMeilleure.CodeGen.RegisterAllocators continue; } - int lEnd = _blockRanges[block.Index].End - 1; + int lEnd = _blockRanges[block.Index].End - 1; int rStart = _blockRanges[succIndex].Start; - LiveInterval left = interval.GetSplitChild(lEnd); + LiveInterval left = interval.GetSplitChild(lEnd); LiveInterval right = interval.GetSplitChild(rStart); if (left != default && right != default && left != right) { - if (copyResolver == null) - { - copyResolver = new CopyResolver(); - } + copyResolver ??= new CopyResolver(); copyResolver.AddSplit(left, right); } @@ -856,14 +853,14 @@ namespace ARMeilleure.CodeGen.RegisterAllocators int mapSize = _intervals.Count; - BitMap[] blkLiveGen = new BitMap[cfg.Blocks.Count]; + BitMap[] blkLiveGen = new BitMap[cfg.Blocks.Count]; BitMap[] blkLiveKill = new BitMap[cfg.Blocks.Count]; // Compute local live sets. for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext) { - BitMap liveGen = new BitMap(Allocators.Default, mapSize); - BitMap liveKill = new BitMap(Allocators.Default, mapSize); + BitMap liveGen = new(Allocators.Default, mapSize); + BitMap liveKill = new(Allocators.Default, mapSize); for (Operation node = block.Operations.First; node != default; node = node.ListNext) { @@ -910,17 +907,17 @@ namespace ARMeilleure.CodeGen.RegisterAllocators } } - blkLiveGen [block.Index] = liveGen; + blkLiveGen[block.Index] = liveGen; blkLiveKill[block.Index] = liveKill; } // Compute global live sets. - BitMap[] blkLiveIn = new BitMap[cfg.Blocks.Count]; + BitMap[] blkLiveIn = new BitMap[cfg.Blocks.Count]; BitMap[] blkLiveOut = new BitMap[cfg.Blocks.Count]; for (int index = 0; index < cfg.Blocks.Count; index++) { - blkLiveIn [index] = new BitMap(Allocators.Default, mapSize); + blkLiveIn[index] = new BitMap(Allocators.Default, mapSize); blkLiveOut[index] = new BitMap(Allocators.Default, mapSize); } @@ -945,9 +942,9 @@ namespace ARMeilleure.CodeGen.RegisterAllocators BitMap liveIn = blkLiveIn[block.Index]; - liveIn.Set (liveOut); + liveIn.Set(liveOut); liveIn.Clear(blkLiveKill[block.Index]); - liveIn.Set (blkLiveGen [block.Index]); + liveIn.Set(blkLiveGen[block.Index]); } } while (modified); @@ -969,7 +966,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators int instCount = Math.Max(block.Operations.Count, 1); int blockStart = operationPos - instCount * InstructionGap; - int blockEnd = operationPos; + int blockEnd = operationPos; _blockRanges[block.Index] = new LiveRange(blockStart, blockEnd); @@ -1061,7 +1058,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { int regIndex = BitOperations.TrailingZeroCount(mask); - Register callerSavedReg = new Register(regIndex, regType); + Register callerSavedReg = new(regIndex, regType); LiveInterval interval = _intervals[GetRegisterId(callerSavedReg)]; @@ -1098,4 +1095,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators kind == OperandKind.Register; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveInterval.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveInterval.cs index d739ad281..333d3951b 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveInterval.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveInterval.cs @@ -240,8 +240,10 @@ namespace ARMeilleure.CodeGen.RegisterAllocators public LiveInterval Split(int position) { - LiveInterval result = new(Local, Parent); - result.End = End; + LiveInterval result = new(Local, Parent) + { + End = End, + }; LiveRange prev = PrevRange; LiveRange curr = CurrRange; @@ -393,4 +395,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators return string.Join(", ", GetRanges()); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs index 06b979ead..d999d767b 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveIntervalList.cs @@ -8,8 +8,8 @@ namespace ARMeilleure.CodeGen.RegisterAllocators private int _count; private int _capacity; - public int Count => _count; - public Span Span => new(_items, _count); + public readonly int Count => _count; + public readonly Span Span => new(_items, _count); public void Add(LiveInterval interval) { @@ -37,4 +37,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators _count++; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveRange.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveRange.cs index e38b5190d..412d597e8 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/LiveRange.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/LiveRange.cs @@ -71,4 +71,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators return $"[{Start}, {End})"; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/RegisterMasks.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/RegisterMasks.cs index bc948f95f..e6972cf0f 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/RegisterMasks.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/RegisterMasks.cs @@ -5,8 +5,8 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { readonly struct RegisterMasks { - public int IntAvailableRegisters { get; } - public int VecAvailableRegisters { get; } + public int IntAvailableRegisters { get; } + public int VecAvailableRegisters { get; } public int IntCallerSavedRegisters { get; } public int VecCallerSavedRegisters { get; } public int IntCalleeSavedRegisters { get; } @@ -22,13 +22,13 @@ namespace ARMeilleure.CodeGen.RegisterAllocators int vecCalleeSavedRegisters, int registersCount) { - IntAvailableRegisters = intAvailableRegisters; - VecAvailableRegisters = vecAvailableRegisters; + IntAvailableRegisters = intAvailableRegisters; + VecAvailableRegisters = vecAvailableRegisters; IntCallerSavedRegisters = intCallerSavedRegisters; VecCallerSavedRegisters = vecCallerSavedRegisters; IntCalleeSavedRegisters = intCalleeSavedRegisters; VecCalleeSavedRegisters = vecCalleeSavedRegisters; - RegistersCount = registersCount; + RegistersCount = registersCount; } public int GetAvailableRegisters(RegisterType type) @@ -47,4 +47,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/StackAllocator.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/StackAllocator.cs index 038312fed..13995bc8d 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/StackAllocator.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/StackAllocator.cs @@ -22,4 +22,4 @@ namespace ARMeilleure.CodeGen.RegisterAllocators return offset; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs b/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs index c89f0854d..a945eccf4 100644 --- a/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs +++ b/src/ARMeilleure/CodeGen/RegisterAllocators/UseList.cs @@ -6,15 +6,15 @@ namespace ARMeilleure.CodeGen.RegisterAllocators { private int* _items; private int _capacity; - private int _count; - public int Count => _count; - public int FirstUse => _count > 0 ? _items[_count - 1] : LiveInterval.NotFound; - public Span Span => new(_items, _count); + public int Count { get; private set; } + + public readonly int FirstUse => Count > 0 ? _items[Count - 1] : LiveInterval.NotFound; + public readonly Span Span => new(_items, Count); public void Add(int position) { - if (_count + 1 > _capacity) + if (Count + 1 > _capacity) { var oldSpan = Span; @@ -28,7 +28,7 @@ namespace ARMeilleure.CodeGen.RegisterAllocators // Use positions are usually inserted in descending order, so inserting in descending order is faster, // since the number of half exchanges is reduced. - int i = _count - 1; + int i = Count - 1; while (i >= 0 && _items[i] < position) { @@ -36,19 +36,19 @@ namespace ARMeilleure.CodeGen.RegisterAllocators } _items[i + 1] = position; - _count++; + Count++; } - public int NextUse(int position) + public readonly int NextUse(int position) { int index = NextUseIndex(position); return index != LiveInterval.NotFound ? _items[index] : LiveInterval.NotFound; } - public int NextUseIndex(int position) + public readonly int NextUseIndex(int position) { - int i = _count - 1; + int i = Count - 1; if (i == -1 || position > _items[0]) { @@ -69,16 +69,18 @@ namespace ARMeilleure.CodeGen.RegisterAllocators // Since the list is in descending order, the new split list takes the front of the list and the current // list takes the back of the list. - UseList result = new(); - result._count = index + 1; - result._capacity = result._count; + UseList result = new() + { + Count = index + 1, + }; + result._capacity = result.Count; result._items = _items; - _count = _count - result._count; - _capacity = _count; - _items = _items + result._count; + Count -= result.Count; + _capacity = Count; + _items += result.Count; return result; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Unwinding/UnwindInfo.cs b/src/ARMeilleure/CodeGen/Unwinding/UnwindInfo.cs index 3d0bc21d5..127b84231 100644 --- a/src/ARMeilleure/CodeGen/Unwinding/UnwindInfo.cs +++ b/src/ARMeilleure/CodeGen/Unwinding/UnwindInfo.cs @@ -13,4 +13,4 @@ namespace ARMeilleure.CodeGen.Unwinding PrologSize = prologSize; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Unwinding/UnwindPseudoOp.cs b/src/ARMeilleure/CodeGen/Unwinding/UnwindPseudoOp.cs index 4a8288a28..2045019a3 100644 --- a/src/ARMeilleure/CodeGen/Unwinding/UnwindPseudoOp.cs +++ b/src/ARMeilleure/CodeGen/Unwinding/UnwindPseudoOp.cs @@ -2,10 +2,10 @@ namespace ARMeilleure.CodeGen.Unwinding { enum UnwindPseudoOp { - PushReg = 0, - SetFrame = 1, + PushReg = 0, + SetFrame = 1, AllocStack = 2, - SaveReg = 3, - SaveXmm128 = 4 + SaveReg = 3, + SaveXmm128 = 4, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/Unwinding/UnwindPushEntry.cs b/src/ARMeilleure/CodeGen/Unwinding/UnwindPushEntry.cs index fd8ea402b..507ace598 100644 --- a/src/ARMeilleure/CodeGen/Unwinding/UnwindPushEntry.cs +++ b/src/ARMeilleure/CodeGen/Unwinding/UnwindPushEntry.cs @@ -17,4 +17,4 @@ namespace ARMeilleure.CodeGen.Unwinding StackOffsetOrAllocSize = stackOffsetOrAllocSize; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/Assembler.cs b/src/ARMeilleure/CodeGen/X86/Assembler.cs index 67736a31f..55bf07248 100644 --- a/src/ARMeilleure/CodeGen/X86/Assembler.cs +++ b/src/ARMeilleure/CodeGen/X86/Assembler.cs @@ -15,7 +15,7 @@ namespace ARMeilleure.CodeGen.X86 private const int OpModRMBits = 24; - private const byte RexPrefix = 0x40; + private const byte RexPrefix = 0x40; private const byte RexWPrefix = 0x48; private const byte LockPrefix = 0xf0; @@ -799,7 +799,7 @@ namespace ARMeilleure.CodeGen.X86 { JumpIndex = _jumps.Count - 1, Position = (int)_stream.Position, - Symbol = source.Symbol + Symbol = source.Symbol, }); } @@ -959,7 +959,7 @@ namespace ARMeilleure.CodeGen.X86 } } - bool needsSibByte = false; + bool needsSibByte = false; bool needsDisplacement = false; int sib = 0; @@ -971,7 +971,7 @@ namespace ARMeilleure.CodeGen.X86 X86Register baseRegLow = (X86Register)(baseReg.Index & 0b111); - needsSibByte = memOp.Index != default || baseRegLow == X86Register.Rsp; + needsSibByte = memOp.Index != default || baseRegLow == X86Register.Rsp; needsDisplacement = memOp.Displacement != 0 || baseRegLow == X86Register.Rbp; if (needsDisplacement) @@ -1049,7 +1049,7 @@ namespace ARMeilleure.CodeGen.X86 InstructionFlags.Prefix66 => 1, InstructionFlags.PrefixF3 => 2, InstructionFlags.PrefixF2 => 3, - _ => 0 + _ => 0, }; if (src1 != default) @@ -1081,11 +1081,19 @@ namespace ARMeilleure.CodeGen.X86 switch (opCodeHigh) { - case 0xf: vexByte1 |= 1; break; - case 0xf38: vexByte1 |= 2; break; - case 0xf3a: vexByte1 |= 3; break; + case 0xf: + vexByte1 |= 1; + break; + case 0xf38: + vexByte1 |= 2; + break; + case 0xf3a: + vexByte1 |= 3; + break; - default: Debug.Assert(false, $"Failed to VEX encode opcode 0x{opCode:X}."); break; + default: + Debug.Assert(false, $"Failed to VEX encode opcode 0x{opCode:X}."); + break; } vexByte2 |= (rexPrefix & 8) << 4; @@ -1191,11 +1199,19 @@ namespace ARMeilleure.CodeGen.X86 switch ((ushort)(opCode >> 8)) { - case 0xf00: mm = 0b01; break; - case 0xf38: mm = 0b10; break; - case 0xf3a: mm = 0b11; break; + case 0xf00: + mm = 0b01; + break; + case 0xf38: + mm = 0b10; + break; + case 0xf3a: + mm = 0b11; + break; - default: Debug.Fail($"Failed to EVEX encode opcode 0x{opCode:X}."); break; + default: + Debug.Fail($"Failed to EVEX encode opcode 0x{opCode:X}."); + break; } WriteByte( @@ -1217,7 +1233,7 @@ namespace ARMeilleure.CodeGen.X86 InstructionFlags.Prefix66 => 0b01, InstructionFlags.PrefixF3 => 0b10, InstructionFlags.PrefixF2 => 0b11, - _ => 0 + _ => 0, }; WriteByte( (byte)( @@ -1233,11 +1249,19 @@ namespace ARMeilleure.CodeGen.X86 byte ll = 0b00; switch (registerWidth) { - case 128: ll = 0b00; break; - case 256: ll = 0b01; break; - case 512: ll = 0b10; break; + case 128: + ll = 0b00; + break; + case 256: + ll = 0b01; + break; + case 512: + ll = 0b10; + break; - default: Debug.Fail($"Invalid EVEX vector register width {registerWidth}."); break; + default: + Debug.Fail($"Invalid EVEX vector register width {registerWidth}."); + break; } // Embedded broadcast in the case of a memory operand bool bcast = broadcast; @@ -1315,10 +1339,7 @@ namespace ARMeilleure.CodeGen.X86 ref Jump jump = ref jumps[i]; // If jump target not resolved yet, resolve it. - if (jump.JumpTarget == null) - { - jump.JumpTarget = _labels[jump.JumpLabel]; - } + jump.JumpTarget ??= _labels[jump.JumpLabel]; long jumpTarget = jump.JumpTarget.Value; long offset = jumpTarget - jump.JumpPosition; @@ -1556,4 +1577,4 @@ namespace ARMeilleure.CodeGen.X86 _stream.WriteByte((byte)(value >> 56)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/AssemblerTable.cs b/src/ARMeilleure/CodeGen/X86/AssemblerTable.cs index e6a2ff07f..e4114a335 100644 --- a/src/ARMeilleure/CodeGen/X86/AssemblerTable.cs +++ b/src/ARMeilleure/CodeGen/X86/AssemblerTable.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; namespace ARMeilleure.CodeGen.X86 { @@ -12,47 +13,48 @@ namespace ARMeilleure.CodeGen.X86 private const int BadOp = 0; [Flags] + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] private enum InstructionFlags { - None = 0, - RegOnly = 1 << 0, - Reg8Src = 1 << 1, + None = 0, + RegOnly = 1 << 0, + Reg8Src = 1 << 1, Reg8Dest = 1 << 2, - RexW = 1 << 3, - Vex = 1 << 4, - Evex = 1 << 5, + RexW = 1 << 3, + Vex = 1 << 4, + Evex = 1 << 5, - PrefixBit = 16, + PrefixBit = 16, PrefixMask = 7 << PrefixBit, - Prefix66 = 1 << PrefixBit, - PrefixF3 = 2 << PrefixBit, - PrefixF2 = 4 << PrefixBit + Prefix66 = 1 << PrefixBit, + PrefixF3 = 2 << PrefixBit, + PrefixF2 = 4 << PrefixBit, } private readonly struct InstructionInfo { - public int OpRMR { get; } - public int OpRMImm8 { get; } + public int OpRMR { get; } + public int OpRMImm8 { get; } public int OpRMImm32 { get; } - public int OpRImm64 { get; } - public int OpRRM { get; } + public int OpRImm64 { get; } + public int OpRRM { get; } public InstructionFlags Flags { get; } public InstructionInfo( - int opRMR, - int opRMImm8, - int opRMImm32, - int opRImm64, - int opRRM, + int opRMR, + int opRMImm8, + int opRMImm32, + int opRImm64, + int opRRM, InstructionFlags flags) { - OpRMR = opRMR; - OpRMImm8 = opRMImm8; + OpRMR = opRMR; + OpRMImm8 = opRMImm8; OpRMImm32 = opRMImm32; - OpRImm64 = opRImm64; - OpRRM = opRRM; - Flags = flags; + OpRImm64 = opRImm64; + OpRRM = opRRM; + Flags = flags; } } @@ -62,6 +64,7 @@ namespace ARMeilleure.CodeGen.X86 { _instTable = new InstructionInfo[(int)X86Instruction.Count]; +#pragma warning disable IDE0055 // Disable formatting // Name RM/R RM/I8 RM/I32 R/I64 R/RM Flags Add(X86Instruction.Add, new InstructionInfo(0x00000001, 0x00000083, 0x00000081, BadOp, 0x00000003, InstructionFlags.None)); Add(X86Instruction.Addpd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f58, InstructionFlags.Vex | InstructionFlags.Prefix66)); @@ -285,6 +288,7 @@ namespace ARMeilleure.CodeGen.X86 Add(X86Instruction.Xor, new InstructionInfo(0x00000031, 0x06000083, 0x06000081, BadOp, 0x00000033, InstructionFlags.None)); Add(X86Instruction.Xorpd, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f57, InstructionFlags.Vex | InstructionFlags.Prefix66)); Add(X86Instruction.Xorps, new InstructionInfo(BadOp, BadOp, BadOp, BadOp, 0x00000f57, InstructionFlags.Vex)); +#pragma warning restore IDE0055 static void Add(X86Instruction inst, in InstructionInfo info) { diff --git a/src/ARMeilleure/CodeGen/X86/CallConvName.cs b/src/ARMeilleure/CodeGen/X86/CallConvName.cs index be3676282..6208da1ec 100644 --- a/src/ARMeilleure/CodeGen/X86/CallConvName.cs +++ b/src/ARMeilleure/CodeGen/X86/CallConvName.cs @@ -3,6 +3,6 @@ namespace ARMeilleure.CodeGen.X86 enum CallConvName { SystemV, - Windows + Windows, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/CallingConvention.cs b/src/ARMeilleure/CodeGen/X86/CallingConvention.cs index 953fef5b0..8433aaea9 100644 --- a/src/ARMeilleure/CodeGen/X86/CallingConvention.cs +++ b/src/ARMeilleure/CodeGen/X86/CallingConvention.cs @@ -20,6 +20,7 @@ namespace ARMeilleure.CodeGen.X86 { if (GetCurrentCallConv() == CallConvName.Windows) { +#pragma warning disable IDE0055 // Disable formatting return (1 << (int)X86Register.Rax) | (1 << (int)X86Register.Rcx) | (1 << (int)X86Register.Rdx) | @@ -39,6 +40,7 @@ namespace ARMeilleure.CodeGen.X86 (1 << (int)X86Register.R9) | (1 << (int)X86Register.R10) | (1 << (int)X86Register.R11); +#pragma warning restore IDE0055 } } @@ -90,22 +92,32 @@ namespace ARMeilleure.CodeGen.X86 { switch (index) { - case 0: return X86Register.Rcx; - case 1: return X86Register.Rdx; - case 2: return X86Register.R8; - case 3: return X86Register.R9; + case 0: + return X86Register.Rcx; + case 1: + return X86Register.Rdx; + case 2: + return X86Register.R8; + case 3: + return X86Register.R9; } } else /* if (GetCurrentCallConv() == CallConvName.SystemV) */ { switch (index) { - case 0: return X86Register.Rdi; - case 1: return X86Register.Rsi; - case 2: return X86Register.Rdx; - case 3: return X86Register.Rcx; - case 4: return X86Register.R8; - case 5: return X86Register.R9; + case 0: + return X86Register.Rdi; + case 1: + return X86Register.Rsi; + case 2: + return X86Register.Rdx; + case 3: + return X86Register.Rcx; + case 4: + return X86Register.R8; + case 5: + return X86Register.R9; } } @@ -155,4 +167,4 @@ namespace ARMeilleure.CodeGen.X86 : CallConvName.SystemV; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/CodeGenContext.cs b/src/ARMeilleure/CodeGen/X86/CodeGenContext.cs index 899487241..d4d4c2058 100644 --- a/src/ARMeilleure/CodeGen/X86/CodeGenContext.cs +++ b/src/ARMeilleure/CodeGen/X86/CodeGenContext.cs @@ -30,7 +30,7 @@ namespace ARMeilleure.CodeGen.X86 Assembler = new Assembler(_stream, relocatable); CallArgsRegionSize = GetCallArgsRegionSize(allocResult, maxCallArgs, out int xmmSaveRegionSize); - XmmSaveRegionSize = xmmSaveRegionSize; + XmmSaveRegionSize = xmmSaveRegionSize; } private static int GetCallArgsRegionSize(AllocationResult allocResult, int maxCallArgs, out int xmmSaveRegionSize) @@ -102,4 +102,4 @@ namespace ARMeilleure.CodeGen.X86 return label; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs b/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs index e7179b517..9e94a077f 100644 --- a/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs +++ b/src/ARMeilleure/CodeGen/X86/CodeGenerator.cs @@ -17,7 +17,7 @@ namespace ARMeilleure.CodeGen.X86 static class CodeGenerator { private const int RegistersCount = 16; - private const int PageSize = 0x1000; + private const int PageSize = 0x1000; private const int StackGuardSize = 0x2000; private static readonly Action[] _instTable; @@ -26,6 +26,7 @@ namespace ARMeilleure.CodeGen.X86 { _instTable = new Action[EnumUtils.GetCount(typeof(Instruction))]; +#pragma warning disable IDE0055 // Disable formatting Add(Instruction.Add, GenerateAdd); Add(Instruction.BitwiseAnd, GenerateBitwiseAnd); Add(Instruction.BitwiseExclusiveOr, GenerateBitwiseExclusiveOr); @@ -85,6 +86,7 @@ namespace ARMeilleure.CodeGen.X86 Add(Instruction.ZeroExtend16, GenerateZeroExtend16); Add(Instruction.ZeroExtend32, GenerateZeroExtend32); Add(Instruction.ZeroExtend8, GenerateZeroExtend8); +#pragma warning restore IDE0055 static void Add(Instruction inst, Action func) { @@ -203,290 +205,290 @@ namespace ARMeilleure.CodeGen.X86 switch (info.Type) { case IntrinsicType.Comis_: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - - switch (operation.Intrinsic) - { - case Intrinsic.X86Comisdeq: - context.Assembler.Comisd(src1, src2); - context.Assembler.Setcc(dest, X86Condition.Equal); - break; - - case Intrinsic.X86Comisdge: - context.Assembler.Comisd(src1, src2); - context.Assembler.Setcc(dest, X86Condition.AboveOrEqual); - break; - - case Intrinsic.X86Comisdlt: - context.Assembler.Comisd(src1, src2); - context.Assembler.Setcc(dest, X86Condition.Below); - break; - - case Intrinsic.X86Comisseq: - context.Assembler.Comiss(src1, src2); - context.Assembler.Setcc(dest, X86Condition.Equal); - break; - - case Intrinsic.X86Comissge: - context.Assembler.Comiss(src1, src2); - context.Assembler.Setcc(dest, X86Condition.AboveOrEqual); - break; - - case Intrinsic.X86Comisslt: - context.Assembler.Comiss(src1, src2); - context.Assembler.Setcc(dest, X86Condition.Below); - break; - } - - context.Assembler.Movzx8(dest, dest, OperandType.I32); - - break; - } - - case IntrinsicType.Mxcsr: - { - Operand offset = operation.GetSource(0); - - Debug.Assert(offset.Kind == OperandKind.Constant); - Debug.Assert(offset.Type == OperandType.I32); - - int offs = offset.AsInt32() + context.CallArgsRegionSize; - - Operand rsp = Register(X86Register.Rsp); - Operand memOp = MemoryOp(OperandType.I32, rsp, default, Multiplier.x1, offs); - - Debug.Assert(HardwareCapabilities.SupportsSse || HardwareCapabilities.SupportsVexEncoding); - - if (operation.Intrinsic == Intrinsic.X86Ldmxcsr) - { - Operand bits = operation.GetSource(1); - Debug.Assert(bits.Type == OperandType.I32); - - context.Assembler.Mov(memOp, bits, OperandType.I32); - context.Assembler.Ldmxcsr(memOp); - } - else if (operation.Intrinsic == Intrinsic.X86Stmxcsr) { Operand dest = operation.Destination; - Debug.Assert(dest.Type == OperandType.I32); + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); - context.Assembler.Stmxcsr(memOp); - context.Assembler.Mov(dest, memOp, OperandType.I32); + switch (operation.Intrinsic) + { + case Intrinsic.X86Comisdeq: + context.Assembler.Comisd(src1, src2); + context.Assembler.Setcc(dest, X86Condition.Equal); + break; + + case Intrinsic.X86Comisdge: + context.Assembler.Comisd(src1, src2); + context.Assembler.Setcc(dest, X86Condition.AboveOrEqual); + break; + + case Intrinsic.X86Comisdlt: + context.Assembler.Comisd(src1, src2); + context.Assembler.Setcc(dest, X86Condition.Below); + break; + + case Intrinsic.X86Comisseq: + context.Assembler.Comiss(src1, src2); + context.Assembler.Setcc(dest, X86Condition.Equal); + break; + + case Intrinsic.X86Comissge: + context.Assembler.Comiss(src1, src2); + context.Assembler.Setcc(dest, X86Condition.AboveOrEqual); + break; + + case Intrinsic.X86Comisslt: + context.Assembler.Comiss(src1, src2); + context.Assembler.Setcc(dest, X86Condition.Below); + break; + } + + context.Assembler.Movzx8(dest, dest, OperandType.I32); + + break; } - break; - } + case IntrinsicType.Mxcsr: + { + Operand offset = operation.GetSource(0); + + Debug.Assert(offset.Kind == OperandKind.Constant); + Debug.Assert(offset.Type == OperandType.I32); + + int offs = offset.AsInt32() + context.CallArgsRegionSize; + + Operand rsp = Register(X86Register.Rsp); + Operand memOp = MemoryOp(OperandType.I32, rsp, default, Multiplier.x1, offs); + + Debug.Assert(HardwareCapabilities.SupportsSse || HardwareCapabilities.SupportsVexEncoding); + + if (operation.Intrinsic == Intrinsic.X86Ldmxcsr) + { + Operand bits = operation.GetSource(1); + Debug.Assert(bits.Type == OperandType.I32); + + context.Assembler.Mov(memOp, bits, OperandType.I32); + context.Assembler.Ldmxcsr(memOp); + } + else if (operation.Intrinsic == Intrinsic.X86Stmxcsr) + { + Operand dest = operation.Destination; + Debug.Assert(dest.Type == OperandType.I32); + + context.Assembler.Stmxcsr(memOp); + context.Assembler.Mov(dest, memOp, OperandType.I32); + } + + break; + } case IntrinsicType.PopCount: - { - Operand dest = operation.Destination; - Operand source = operation.GetSource(0); + { + Operand dest = operation.Destination; + Operand source = operation.GetSource(0); - EnsureSameType(dest, source); + EnsureSameType(dest, source); - Debug.Assert(dest.Type.IsInteger()); + Debug.Assert(dest.Type.IsInteger()); - context.Assembler.Popcnt(dest, source, dest.Type); + context.Assembler.Popcnt(dest, source, dest.Type); - break; - } + break; + } case IntrinsicType.Unary: - { - Operand dest = operation.Destination; - Operand source = operation.GetSource(0); + { + Operand dest = operation.Destination; + Operand source = operation.GetSource(0); - EnsureSameType(dest, source); + EnsureSameType(dest, source); - Debug.Assert(!dest.Type.IsInteger()); + Debug.Assert(!dest.Type.IsInteger()); - context.Assembler.WriteInstruction(info.Inst, dest, source); + context.Assembler.WriteInstruction(info.Inst, dest, source); - break; - } + break; + } case IntrinsicType.UnaryToGpr: - { - Operand dest = operation.Destination; - Operand source = operation.GetSource(0); - - Debug.Assert(dest.Type.IsInteger() && !source.Type.IsInteger()); - - if (operation.Intrinsic == Intrinsic.X86Cvtsi2si) { - if (dest.Type == OperandType.I32) - { - context.Assembler.Movd(dest, source); // int _mm_cvtsi128_si32(__m128i a) - } - else /* if (dest.Type == OperandType.I64) */ - { - context.Assembler.Movq(dest, source); // __int64 _mm_cvtsi128_si64(__m128i a) - } - } - else - { - context.Assembler.WriteInstruction(info.Inst, dest, source, dest.Type); - } + Operand dest = operation.Destination; + Operand source = operation.GetSource(0); - break; - } + Debug.Assert(dest.Type.IsInteger() && !source.Type.IsInteger()); + + if (operation.Intrinsic == Intrinsic.X86Cvtsi2si) + { + if (dest.Type == OperandType.I32) + { + context.Assembler.Movd(dest, source); // int _mm_cvtsi128_si32(__m128i a) + } + else /* if (dest.Type == OperandType.I64) */ + { + context.Assembler.Movq(dest, source); // __int64 _mm_cvtsi128_si64(__m128i a) + } + } + else + { + context.Assembler.WriteInstruction(info.Inst, dest, source, dest.Type); + } + + break; + } case IntrinsicType.Binary: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - - EnsureSameType(dest, src1); - - if (!HardwareCapabilities.SupportsVexEncoding) { - EnsureSameReg(dest, src1); - } + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); - Debug.Assert(!dest.Type.IsInteger()); - Debug.Assert(!src2.Type.IsInteger() || src2.Kind == OperandKind.Constant); + EnsureSameType(dest, src1); - context.Assembler.WriteInstruction(info.Inst, dest, src1, src2); + if (!HardwareCapabilities.SupportsVexEncoding) + { + EnsureSameReg(dest, src1); + } - break; - } - - case IntrinsicType.BinaryGpr: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - - EnsureSameType(dest, src1); - - if (!HardwareCapabilities.SupportsVexEncoding) - { - EnsureSameReg(dest, src1); - } - - Debug.Assert(!dest.Type.IsInteger() && src2.Type.IsInteger()); - - context.Assembler.WriteInstruction(info.Inst, dest, src1, src2, src2.Type); - - break; - } - - case IntrinsicType.Crc32: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - - EnsureSameReg(dest, src1); - - Debug.Assert(dest.Type.IsInteger() && src1.Type.IsInteger() && src2.Type.IsInteger()); - - context.Assembler.WriteInstruction(info.Inst, dest, src2, dest.Type); - - break; - } - - case IntrinsicType.BinaryImm: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - - EnsureSameType(dest, src1); - - if (!HardwareCapabilities.SupportsVexEncoding) - { - EnsureSameReg(dest, src1); - } - - Debug.Assert(!dest.Type.IsInteger() && src2.Kind == OperandKind.Constant); - - context.Assembler.WriteInstruction(info.Inst, dest, src1, src2.AsByte()); - - break; - } - - case IntrinsicType.Ternary: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - Operand src3 = operation.GetSource(2); - - EnsureSameType(dest, src1, src2, src3); - - Debug.Assert(!dest.Type.IsInteger()); - - if (info.Inst == X86Instruction.Blendvpd && HardwareCapabilities.SupportsVexEncoding) - { - context.Assembler.WriteInstruction(X86Instruction.Vblendvpd, dest, src1, src2, src3); - } - else if (info.Inst == X86Instruction.Blendvps && HardwareCapabilities.SupportsVexEncoding) - { - context.Assembler.WriteInstruction(X86Instruction.Vblendvps, dest, src1, src2, src3); - } - else if (info.Inst == X86Instruction.Pblendvb && HardwareCapabilities.SupportsVexEncoding) - { - context.Assembler.WriteInstruction(X86Instruction.Vpblendvb, dest, src1, src2, src3); - } - else - { - EnsureSameReg(dest, src1); - - Debug.Assert(src3.GetRegister().Index == 0); + Debug.Assert(!dest.Type.IsInteger()); + Debug.Assert(!src2.Type.IsInteger() || src2.Kind == OperandKind.Constant); context.Assembler.WriteInstruction(info.Inst, dest, src1, src2); + + break; } - break; - } + case IntrinsicType.BinaryGpr: + { + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); + + EnsureSameType(dest, src1); + + if (!HardwareCapabilities.SupportsVexEncoding) + { + EnsureSameReg(dest, src1); + } + + Debug.Assert(!dest.Type.IsInteger() && src2.Type.IsInteger()); + + context.Assembler.WriteInstruction(info.Inst, dest, src1, src2, src2.Type); + + break; + } + + case IntrinsicType.Crc32: + { + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); + + EnsureSameReg(dest, src1); + + Debug.Assert(dest.Type.IsInteger() && src1.Type.IsInteger() && src2.Type.IsInteger()); + + context.Assembler.WriteInstruction(info.Inst, dest, src2, dest.Type); + + break; + } + + case IntrinsicType.BinaryImm: + { + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); + + EnsureSameType(dest, src1); + + if (!HardwareCapabilities.SupportsVexEncoding) + { + EnsureSameReg(dest, src1); + } + + Debug.Assert(!dest.Type.IsInteger() && src2.Kind == OperandKind.Constant); + + context.Assembler.WriteInstruction(info.Inst, dest, src1, src2.AsByte()); + + break; + } + + case IntrinsicType.Ternary: + { + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); + Operand src3 = operation.GetSource(2); + + EnsureSameType(dest, src1, src2, src3); + + Debug.Assert(!dest.Type.IsInteger()); + + if (info.Inst == X86Instruction.Blendvpd && HardwareCapabilities.SupportsVexEncoding) + { + context.Assembler.WriteInstruction(X86Instruction.Vblendvpd, dest, src1, src2, src3); + } + else if (info.Inst == X86Instruction.Blendvps && HardwareCapabilities.SupportsVexEncoding) + { + context.Assembler.WriteInstruction(X86Instruction.Vblendvps, dest, src1, src2, src3); + } + else if (info.Inst == X86Instruction.Pblendvb && HardwareCapabilities.SupportsVexEncoding) + { + context.Assembler.WriteInstruction(X86Instruction.Vpblendvb, dest, src1, src2, src3); + } + else + { + EnsureSameReg(dest, src1); + + Debug.Assert(src3.GetRegister().Index == 0); + + context.Assembler.WriteInstruction(info.Inst, dest, src1, src2); + } + + break; + } case IntrinsicType.TernaryImm: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - Operand src3 = operation.GetSource(2); - - EnsureSameType(dest, src1, src2); - - if (!HardwareCapabilities.SupportsVexEncoding) { - EnsureSameReg(dest, src1); + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); + Operand src3 = operation.GetSource(2); + + EnsureSameType(dest, src1, src2); + + if (!HardwareCapabilities.SupportsVexEncoding) + { + EnsureSameReg(dest, src1); + } + + Debug.Assert(!dest.Type.IsInteger() && src3.Kind == OperandKind.Constant); + + context.Assembler.WriteInstruction(info.Inst, dest, src1, src2, src3.AsByte()); + + break; } - Debug.Assert(!dest.Type.IsInteger() && src3.Kind == OperandKind.Constant); - - context.Assembler.WriteInstruction(info.Inst, dest, src1, src2, src3.AsByte()); - - break; - } - case IntrinsicType.Fma: - { - Operand dest = operation.Destination; - Operand src1 = operation.GetSource(0); - Operand src2 = operation.GetSource(1); - Operand src3 = operation.GetSource(2); + { + Operand dest = operation.Destination; + Operand src1 = operation.GetSource(0); + Operand src2 = operation.GetSource(1); + Operand src3 = operation.GetSource(2); - Debug.Assert(HardwareCapabilities.SupportsVexEncoding); + Debug.Assert(HardwareCapabilities.SupportsVexEncoding); - Debug.Assert(dest.Kind == OperandKind.Register && src1.Kind == OperandKind.Register && src2.Kind == OperandKind.Register); - Debug.Assert(src3.Kind == OperandKind.Register || src3.Kind == OperandKind.Memory); + Debug.Assert(dest.Kind == OperandKind.Register && src1.Kind == OperandKind.Register && src2.Kind == OperandKind.Register); + Debug.Assert(src3.Kind == OperandKind.Register || src3.Kind == OperandKind.Memory); - EnsureSameType(dest, src1, src2, src3); - Debug.Assert(dest.Type == OperandType.V128); + EnsureSameType(dest, src1, src2, src3); + Debug.Assert(dest.Type == OperandType.V128); - Debug.Assert(dest.Value == src1.Value); + Debug.Assert(dest.Value == src1.Value); - context.Assembler.WriteInstruction(info.Inst, dest, src2, src3); + context.Assembler.WriteInstruction(info.Inst, dest, src2, src3); - break; - } + break; + } } } else @@ -592,7 +594,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateBitwiseNot(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); ValidateUnOp(dest, source); @@ -630,7 +632,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateByteSwap(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); ValidateUnOp(dest, source); @@ -761,19 +763,19 @@ namespace ARMeilleure.CodeGen.X86 Operand src2 = operation.GetSource(1); Operand src3 = operation.GetSource(2); - EnsureSameReg (dest, src3); + EnsureSameReg(dest, src3); EnsureSameType(dest, src2, src3); Debug.Assert(dest.Type.IsInteger()); Debug.Assert(src1.Type == OperandType.I32); - context.Assembler.Test (src1, src1, src1.Type); + context.Assembler.Test(src1, src1, src1.Type); context.Assembler.Cmovcc(dest, src2, dest.Type, X86Condition.NotEqual); } private static void GenerateConvertI64ToI32(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.I32 && source.Type == OperandType.I64); @@ -783,7 +785,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateConvertToFP(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.FP32 || dest.Type == OperandType.FP64); @@ -794,7 +796,7 @@ namespace ARMeilleure.CodeGen.X86 if (source.Type.IsInteger()) { - context.Assembler.Xorps (dest, dest, dest); + context.Assembler.Xorps(dest, dest, dest); context.Assembler.Cvtsi2ss(dest, dest, source, source.Type); } else /* if (source.Type == OperandType.FP64) */ @@ -810,7 +812,7 @@ namespace ARMeilleure.CodeGen.X86 if (source.Type.IsInteger()) { - context.Assembler.Xorps (dest, dest, dest); + context.Assembler.Xorps(dest, dest, dest); context.Assembler.Cvtsi2sd(dest, dest, source, source.Type); } else /* if (source.Type == OperandType.FP32) */ @@ -824,7 +826,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateCopy(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); EnsureSameType(dest, source); @@ -837,7 +839,7 @@ namespace ARMeilleure.CodeGen.X86 return; } - if (dest.Kind == OperandKind.Register && + if (dest.Kind == OperandKind.Register && source.Kind == OperandKind.Constant && source.Value == 0) { // Assemble "mov reg, 0" as "xor reg, reg" as the later is more efficient. @@ -855,7 +857,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateCountLeadingZeros(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); EnsureSameType(dest, source); @@ -888,9 +890,9 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateDivide(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand dividend = operation.GetSource(0); - Operand divisor = operation.GetSource(1); + Operand divisor = operation.GetSource(1); if (!dest.Type.IsInteger()) { @@ -938,7 +940,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateFill(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand offset = operation.GetSource(0); Debug.Assert(offset.Kind == OperandKind.Constant); @@ -954,7 +956,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateLoad(CodeGenContext context, Operation operation) { - Operand value = operation.Destination; + Operand value = operation.Destination; Operand address = Memory(operation.GetSource(0), value.Type); GenerateLoad(context, address, value); @@ -962,7 +964,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateLoad16(CodeGenContext context, Operation operation) { - Operand value = operation.Destination; + Operand value = operation.Destination; Operand address = Memory(operation.GetSource(0), value.Type); Debug.Assert(value.Type.IsInteger()); @@ -972,7 +974,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateLoad8(CodeGenContext context, Operation operation) { - Operand value = operation.Destination; + Operand value = operation.Destination; Operand address = Memory(operation.GetSource(0), value.Type); Debug.Assert(value.Type.IsInteger()); @@ -1039,7 +1041,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateNegate(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); ValidateUnOp(dest, source); @@ -1102,7 +1104,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateSignExtend16(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1112,7 +1114,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateSignExtend32(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1122,7 +1124,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateSignExtend8(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1158,7 +1160,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateStackAlloc(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand offset = operation.GetSource(0); Debug.Assert(offset.Kind == OperandKind.Constant); @@ -1174,7 +1176,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateStore(CodeGenContext context, Operation operation) { - Operand value = operation.GetSource(1); + Operand value = operation.GetSource(1); Operand address = Memory(operation.GetSource(0), value.Type); GenerateStore(context, address, value); @@ -1182,7 +1184,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateStore16(CodeGenContext context, Operation operation) { - Operand value = operation.GetSource(1); + Operand value = operation.GetSource(1); Operand address = Memory(operation.GetSource(0), value.Type); Debug.Assert(value.Type.IsInteger()); @@ -1192,7 +1194,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateStore8(CodeGenContext context, Operation operation) { - Operand value = operation.GetSource(1); + Operand value = operation.GetSource(1); Operand address = Memory(operation.GetSource(0), value.Type); Debug.Assert(value.Type.IsInteger()); @@ -1231,7 +1233,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateVectorCreateScalar(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(!dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1278,7 +1280,7 @@ namespace ARMeilleure.CodeGen.X86 mask1 = BitUtils.RotateRight(mask1, 8 - index * 2, 8); context.Assembler.Pshufd(src1, src1, (byte)mask0); - context.Assembler.Movd (dest, src1); + context.Assembler.Movd(dest, src1); context.Assembler.Pshufd(src1, src1, (byte)mask1); } } @@ -1294,11 +1296,11 @@ namespace ARMeilleure.CodeGen.X86 } else { - const byte mask = 0b01_00_11_10; + const byte Mask = 0b01_00_11_10; - context.Assembler.Pshufd(src1, src1, mask); - context.Assembler.Movq (dest, src1); - context.Assembler.Pshufd(src1, src1, mask); + context.Assembler.Pshufd(src1, src1, Mask); + context.Assembler.Movq(dest, src1); + context.Assembler.Pshufd(src1, src1, Mask); } } else @@ -1308,7 +1310,7 @@ namespace ARMeilleure.CodeGen.X86 (index == 1 && dest.Type == OperandType.FP64)) { context.Assembler.Movhlps(dest, dest, src1); - context.Assembler.Movq (dest, dest); + context.Assembler.Movq(dest, dest); } else { @@ -1455,11 +1457,11 @@ namespace ARMeilleure.CodeGen.X86 int mask0 = 0b11_10_01_00; int mask1 = 0b11_10_01_00; - mask0 = BitUtils.RotateRight(mask0, index * 2, 8); + mask0 = BitUtils.RotateRight(mask0, index * 2, 8); mask1 = BitUtils.RotateRight(mask1, 8 - index * 2, 8); context.Assembler.Pshufd(src1, src1, (byte)mask0); // Lane to be inserted in position 0. - context.Assembler.Movss (dest, src1, src2); // dest[127:0] = src1[127:32] | src2[31:0] + context.Assembler.Movss(dest, src1, src2); // dest[127:0] = src1[127:32] | src2[31:0] context.Assembler.Pshufd(dest, dest, (byte)mask1); // Inserted lane in original position. if (dest.GetRegister() != src1.GetRegister()) @@ -1555,7 +1557,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateVectorZeroUpper64(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.V128 && source.Type == OperandType.V128); @@ -1565,7 +1567,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateVectorZeroUpper96(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type == OperandType.V128 && source.Type == OperandType.V128); @@ -1575,7 +1577,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateZeroExtend16(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1585,7 +1587,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateZeroExtend32(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1601,7 +1603,7 @@ namespace ARMeilleure.CodeGen.X86 private static void GenerateZeroExtend8(CodeGenContext context, Operation operation) { - Operand dest = operation.Destination; + Operand dest = operation.Destination; Operand source = operation.GetSource(0); Debug.Assert(dest.Type.IsInteger() && source.Type.IsInteger()); @@ -1613,13 +1615,25 @@ namespace ARMeilleure.CodeGen.X86 { switch (value.Type) { - case OperandType.I32: context.Assembler.Mov (value, address, OperandType.I32); break; - case OperandType.I64: context.Assembler.Mov (value, address, OperandType.I64); break; - case OperandType.FP32: context.Assembler.Movd (value, address); break; - case OperandType.FP64: context.Assembler.Movq (value, address); break; - case OperandType.V128: context.Assembler.Movdqu(value, address); break; + case OperandType.I32: + context.Assembler.Mov(value, address, OperandType.I32); + break; + case OperandType.I64: + context.Assembler.Mov(value, address, OperandType.I64); + break; + case OperandType.FP32: + context.Assembler.Movd(value, address); + break; + case OperandType.FP64: + context.Assembler.Movq(value, address); + break; + case OperandType.V128: + context.Assembler.Movdqu(value, address); + break; - default: Debug.Assert(false); break; + default: + Debug.Assert(false); + break; } } @@ -1627,13 +1641,25 @@ namespace ARMeilleure.CodeGen.X86 { switch (value.Type) { - case OperandType.I32: context.Assembler.Mov (address, value, OperandType.I32); break; - case OperandType.I64: context.Assembler.Mov (address, value, OperandType.I64); break; - case OperandType.FP32: context.Assembler.Movd (address, value); break; - case OperandType.FP64: context.Assembler.Movq (address, value); break; - case OperandType.V128: context.Assembler.Movdqu(address, value); break; + case OperandType.I32: + context.Assembler.Mov(address, value, OperandType.I32); + break; + case OperandType.I64: + context.Assembler.Mov(address, value, OperandType.I64); + break; + case OperandType.FP32: + context.Assembler.Movd(address, value); + break; + case OperandType.FP64: + context.Assembler.Movq(address, value); + break; + case OperandType.V128: + context.Assembler.Movdqu(address, value); + break; - default: Debug.Assert(false); break; + default: + Debug.Assert(false); + break; } } @@ -1670,21 +1696,21 @@ namespace ARMeilleure.CodeGen.X86 [Conditional("DEBUG")] private static void ValidateUnOp(Operand dest, Operand source) { - EnsureSameReg (dest, source); + EnsureSameReg(dest, source); EnsureSameType(dest, source); } [Conditional("DEBUG")] private static void ValidateBinOp(Operand dest, Operand src1, Operand src2) { - EnsureSameReg (dest, src1); + EnsureSameReg(dest, src1); EnsureSameType(dest, src1, src2); } [Conditional("DEBUG")] private static void ValidateShift(Operand dest, Operand src1, Operand src2) { - EnsureSameReg (dest, src1); + EnsureSameReg(dest, src1); EnsureSameType(dest, src1); Debug.Assert(dest.Type.IsInteger() && src2.Type == OperandType.I32); @@ -1722,7 +1748,7 @@ namespace ARMeilleure.CodeGen.X86 private static UnwindInfo WritePrologue(CodeGenContext context) { - List pushEntries = new List(); + List pushEntries = new(); Operand rsp = Register(X86Register.Rsp); @@ -1827,11 +1853,11 @@ namespace ARMeilleure.CodeGen.X86 // that the OS will map all pages that we'll use. We do that by // doing a dummy read on those pages, forcing a page fault and // the OS to map them. If they are already mapped, nothing happens. - const int pageMask = PageSize - 1; + const int PageMask = PageSize - 1; - size = (size + pageMask) & ~pageMask; + size = (size + PageMask) & ~PageMask; - Operand rsp = Register(X86Register.Rsp); + Operand rsp = Register(X86Register.Rsp); Operand temp = Register(CallingConvention.GetIntReturnRegister()); for (int offset = PageSize; offset < size; offset += PageSize) @@ -1862,4 +1888,4 @@ namespace ARMeilleure.CodeGen.X86 return Operand.Factory.Register((int)register, RegisterType.Vector, OperandType.V128); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs b/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs index 07cdcd096..4f6f1e87b 100644 --- a/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs +++ b/src/ARMeilleure/CodeGen/X86/HardwareCapabilities.cs @@ -47,7 +47,7 @@ namespace ARMeilleure.CodeGen.X86 0xc3, // ret }; - using MemoryBlock memGetXcr0 = new MemoryBlock((ulong)asmGetXcr0.Length); + using MemoryBlock memGetXcr0 = new((ulong)asmGetXcr0.Length); memGetXcr0.Write(0, asmGetXcr0); @@ -62,7 +62,7 @@ namespace ARMeilleure.CodeGen.X86 public enum FeatureFlags1Edx { Sse = 1 << 25, - Sse2 = 1 << 26 + Sse2 = 1 << 26, } [Flags] @@ -79,7 +79,7 @@ namespace ARMeilleure.CodeGen.X86 Xsave = 1 << 26, Osxsave = 1 << 27, Avx = 1 << 28, - F16c = 1 << 29 + F16c = 1 << 29, } [Flags] @@ -90,7 +90,7 @@ namespace ARMeilleure.CodeGen.X86 Avx512dq = 1 << 17, Sha = 1 << 29, Avx512bw = 1 << 30, - Avx512vl = 1 << 31 + Avx512vl = 1 << 31, } [Flags] @@ -106,7 +106,7 @@ namespace ARMeilleure.CodeGen.X86 YmmHi128 = 1 << 2, Opmask = 1 << 5, ZmmHi256 = 1 << 6, - Hi16Zmm = 1 << 7 + Hi16Zmm = 1 << 7, } public static FeatureFlags1Edx FeatureInfo1Edx { get; } @@ -141,4 +141,4 @@ namespace ARMeilleure.CodeGen.X86 public static bool SupportsVexEncoding => SupportsAvx && !ForceLegacySse; public static bool SupportsEvexEncoding => SupportsAvx512F && !ForceLegacySse; } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/IntrinsicInfo.cs b/src/ARMeilleure/CodeGen/X86/IntrinsicInfo.cs index 302bf4d3c..16054c616 100644 --- a/src/ARMeilleure/CodeGen/X86/IntrinsicInfo.cs +++ b/src/ARMeilleure/CodeGen/X86/IntrinsicInfo.cs @@ -3,7 +3,7 @@ namespace ARMeilleure.CodeGen.X86 readonly struct IntrinsicInfo { public X86Instruction Inst { get; } - public IntrinsicType Type { get; } + public IntrinsicType Type { get; } public IntrinsicInfo(X86Instruction inst, IntrinsicType type) { @@ -11,4 +11,4 @@ namespace ARMeilleure.CodeGen.X86 Type = type; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/IntrinsicTable.cs b/src/ARMeilleure/CodeGen/X86/IntrinsicTable.cs index e3d94b7ae..daa1f8f60 100644 --- a/src/ARMeilleure/CodeGen/X86/IntrinsicTable.cs +++ b/src/ARMeilleure/CodeGen/X86/IntrinsicTable.cs @@ -5,12 +5,13 @@ namespace ARMeilleure.CodeGen.X86 { static class IntrinsicTable { - private static IntrinsicInfo[] _intrinTable; + private static readonly IntrinsicInfo[] _intrinTable; static IntrinsicTable() { _intrinTable = new IntrinsicInfo[EnumUtils.GetCount(typeof(Intrinsic))]; +#pragma warning disable IDE0055 // Disable formatting Add(Intrinsic.X86Addpd, new IntrinsicInfo(X86Instruction.Addpd, IntrinsicType.Binary)); Add(Intrinsic.X86Addps, new IntrinsicInfo(X86Instruction.Addps, IntrinsicType.Binary)); Add(Intrinsic.X86Addsd, new IntrinsicInfo(X86Instruction.Addsd, IntrinsicType.Binary)); @@ -185,6 +186,7 @@ namespace ARMeilleure.CodeGen.X86 Add(Intrinsic.X86Vpternlogd, new IntrinsicInfo(X86Instruction.Vpternlogd, IntrinsicType.TernaryImm)); Add(Intrinsic.X86Xorpd, new IntrinsicInfo(X86Instruction.Xorpd, IntrinsicType.Binary)); Add(Intrinsic.X86Xorps, new IntrinsicInfo(X86Instruction.Xorps, IntrinsicType.Binary)); +#pragma warning restore IDE0055 } private static void Add(Intrinsic intrin, IntrinsicInfo info) @@ -197,4 +199,4 @@ namespace ARMeilleure.CodeGen.X86 return _intrinTable[(int)intrin]; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/IntrinsicType.cs b/src/ARMeilleure/CodeGen/X86/IntrinsicType.cs index 5a9c14afa..7c3ef354d 100644 --- a/src/ARMeilleure/CodeGen/X86/IntrinsicType.cs +++ b/src/ARMeilleure/CodeGen/X86/IntrinsicType.cs @@ -13,6 +13,6 @@ namespace ARMeilleure.CodeGen.X86 Crc32, Ternary, TernaryImm, - Fma + Fma, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/Mxcsr.cs b/src/ARMeilleure/CodeGen/X86/Mxcsr.cs index c61eac31a..83d7a5845 100644 --- a/src/ARMeilleure/CodeGen/X86/Mxcsr.cs +++ b/src/ARMeilleure/CodeGen/X86/Mxcsr.cs @@ -10,6 +10,6 @@ namespace ARMeilleure.CodeGen.X86 Rlo = 1 << 13, // Round Mode low bit. Um = 1 << 11, // Underflow Mask. Dm = 1 << 8, // Denormal Mask. - Daz = 1 << 6 // Denormals Are Zero. + Daz = 1 << 6, // Denormals Are Zero. } } diff --git a/src/ARMeilleure/CodeGen/X86/PreAllocator.cs b/src/ARMeilleure/CodeGen/X86/PreAllocator.cs index cb742d67f..590c35c7b 100644 --- a/src/ARMeilleure/CodeGen/X86/PreAllocator.cs +++ b/src/ARMeilleure/CodeGen/X86/PreAllocator.cs @@ -104,11 +104,11 @@ namespace ARMeilleure.CodeGen.X86 case Instruction.Tailcall: if (callConv == CallConvName.Windows) { - PreAllocatorWindows.InsertTailcallCopies(block.Operations, stackAlloc, node); + PreAllocatorWindows.InsertTailcallCopies(block.Operations, node); } else { - PreAllocatorSystemV.InsertTailcallCopies(block.Operations, stackAlloc, node); + PreAllocatorSystemV.InsertTailcallCopies(block.Operations, node); } break; @@ -177,10 +177,7 @@ namespace ARMeilleure.CodeGen.X86 { src2 = node.GetSource(1); - Operand temp = src1; - - src1 = src2; - src2 = temp; + (src2, src1) = (src1, src2); node.SetSource(0, src1); node.SetSource(1, src2); @@ -228,151 +225,151 @@ namespace ARMeilleure.CodeGen.X86 case Instruction.CompareAndSwap: case Instruction.CompareAndSwap16: case Instruction.CompareAndSwap8: - { - OperandType type = node.GetSource(1).Type; - - if (type == OperandType.V128) { - // Handle the many restrictions of the compare and exchange (16 bytes) instruction: - // - The expected value should be in RDX:RAX. - // - The new value to be written should be in RCX:RBX. - // - The value at the memory location is loaded to RDX:RAX. - void SplitOperand(Operand source, Operand lr, Operand hr) + OperandType type = node.GetSource(1).Type; + + if (type == OperandType.V128) { - nodes.AddBefore(node, Operation(Instruction.VectorExtract, lr, source, Const(0))); - nodes.AddBefore(node, Operation(Instruction.VectorExtract, hr, source, Const(1))); + // Handle the many restrictions of the compare and exchange (16 bytes) instruction: + // - The expected value should be in RDX:RAX. + // - The new value to be written should be in RCX:RBX. + // - The value at the memory location is loaded to RDX:RAX. + void SplitOperand(Operand source, Operand lr, Operand hr) + { + nodes.AddBefore(node, Operation(Instruction.VectorExtract, lr, source, Const(0))); + nodes.AddBefore(node, Operation(Instruction.VectorExtract, hr, source, Const(1))); + } + + Operand rax = Gpr(X86Register.Rax, OperandType.I64); + Operand rbx = Gpr(X86Register.Rbx, OperandType.I64); + Operand rcx = Gpr(X86Register.Rcx, OperandType.I64); + Operand rdx = Gpr(X86Register.Rdx, OperandType.I64); + + SplitOperand(node.GetSource(1), rax, rdx); + SplitOperand(node.GetSource(2), rbx, rcx); + + Operation operation = node; + + node = nodes.AddAfter(node, Operation(Instruction.VectorCreateScalar, dest, rax)); + nodes.AddAfter(node, Operation(Instruction.VectorInsert, dest, dest, rdx, Const(1))); + + operation.SetDestinations(new Operand[] { rdx, rax }); + operation.SetSources(new Operand[] { operation.GetSource(0), rdx, rax, rcx, rbx }); + } + else + { + // Handle the many restrictions of the compare and exchange (32/64) instruction: + // - The expected value should be in (E/R)AX. + // - The value at the memory location is loaded to (E/R)AX. + Operand expected = node.GetSource(1); + Operand newValue = node.GetSource(2); + + Operand rax = Gpr(X86Register.Rax, expected.Type); + + nodes.AddBefore(node, Operation(Instruction.Copy, rax, expected)); + + // We need to store the new value into a temp, since it may + // be a constant, and this instruction does not support immediate operands. + Operand temp = Local(newValue.Type); + + nodes.AddBefore(node, Operation(Instruction.Copy, temp, newValue)); + + node.SetSources(new Operand[] { node.GetSource(0), rax, temp }); + + nodes.AddAfter(node, Operation(Instruction.Copy, dest, rax)); + + node.Destination = rax; } - Operand rax = Gpr(X86Register.Rax, OperandType.I64); - Operand rbx = Gpr(X86Register.Rbx, OperandType.I64); - Operand rcx = Gpr(X86Register.Rcx, OperandType.I64); - Operand rdx = Gpr(X86Register.Rdx, OperandType.I64); - - SplitOperand(node.GetSource(1), rax, rdx); - SplitOperand(node.GetSource(2), rbx, rcx); - - Operation operation = node; - - node = nodes.AddAfter(node, Operation(Instruction.VectorCreateScalar, dest, rax)); - nodes.AddAfter(node, Operation(Instruction.VectorInsert, dest, dest, rdx, Const(1))); - - operation.SetDestinations(new Operand[] { rdx, rax }); - operation.SetSources(new Operand[] { operation.GetSource(0), rdx, rax, rcx, rbx }); + break; } - else - { - // Handle the many restrictions of the compare and exchange (32/64) instruction: - // - The expected value should be in (E/R)AX. - // - The value at the memory location is loaded to (E/R)AX. - Operand expected = node.GetSource(1); - Operand newValue = node.GetSource(2); - - Operand rax = Gpr(X86Register.Rax, expected.Type); - - nodes.AddBefore(node, Operation(Instruction.Copy, rax, expected)); - - // We need to store the new value into a temp, since it may - // be a constant, and this instruction does not support immediate operands. - Operand temp = Local(newValue.Type); - - nodes.AddBefore(node, Operation(Instruction.Copy, temp, newValue)); - - node.SetSources(new Operand[] { node.GetSource(0), rax, temp }); - - nodes.AddAfter(node, Operation(Instruction.Copy, dest, rax)); - - node.Destination = rax; - } - - break; - } case Instruction.Divide: case Instruction.DivideUI: - { - // Handle the many restrictions of the division instructions: - // - The dividend is always in RDX:RAX. - // - The result is always in RAX. - // - Additionally it also writes the remainder in RDX. - if (dest.Type.IsInteger()) { + // Handle the many restrictions of the division instructions: + // - The dividend is always in RDX:RAX. + // - The result is always in RAX. + // - Additionally it also writes the remainder in RDX. + if (dest.Type.IsInteger()) + { + Operand src1 = node.GetSource(0); + + Operand rax = Gpr(X86Register.Rax, src1.Type); + Operand rdx = Gpr(X86Register.Rdx, src1.Type); + + nodes.AddBefore(node, Operation(Instruction.Copy, rax, src1)); + nodes.AddBefore(node, Operation(Instruction.Clobber, rdx)); + + nodes.AddAfter(node, Operation(Instruction.Copy, dest, rax)); + + node.SetSources(new Operand[] { rdx, rax, node.GetSource(1) }); + node.Destination = rax; + } + + break; + } + + case Instruction.Extended: + { + bool isBlend = node.Intrinsic == Intrinsic.X86Blendvpd || + node.Intrinsic == Intrinsic.X86Blendvps || + node.Intrinsic == Intrinsic.X86Pblendvb; + + // BLENDVPD, BLENDVPS, PBLENDVB last operand is always implied to be XMM0 when VEX is not supported. + // SHA256RNDS2 always has an implied XMM0 as a last operand. + if ((isBlend && !HardwareCapabilities.SupportsVexEncoding) || node.Intrinsic == Intrinsic.X86Sha256Rnds2) + { + Operand xmm0 = Xmm(X86Register.Xmm0, OperandType.V128); + + nodes.AddBefore(node, Operation(Instruction.Copy, xmm0, node.GetSource(2))); + + node.SetSource(2, xmm0); + } + + break; + } + + case Instruction.Multiply64HighSI: + case Instruction.Multiply64HighUI: + { + // Handle the many restrictions of the i64 * i64 = i128 multiply instructions: + // - The multiplicand is always in RAX. + // - The lower 64-bits of the result is always in RAX. + // - The higher 64-bits of the result is always in RDX. Operand src1 = node.GetSource(0); Operand rax = Gpr(X86Register.Rax, src1.Type); Operand rdx = Gpr(X86Register.Rdx, src1.Type); - nodes.AddBefore(node, Operation(Instruction.Copy, rax, src1)); - nodes.AddBefore(node, Operation(Instruction.Clobber, rdx)); + nodes.AddBefore(node, Operation(Instruction.Copy, rax, src1)); - nodes.AddAfter(node, Operation(Instruction.Copy, dest, rax)); + node.SetSource(0, rax); - node.SetSources(new Operand[] { rdx, rax, node.GetSource(1) }); - node.Destination = rax; + nodes.AddAfter(node, Operation(Instruction.Copy, dest, rdx)); + + node.SetDestinations(new Operand[] { rdx, rax }); + + break; } - break; - } - - case Instruction.Extended: - { - bool isBlend = node.Intrinsic == Intrinsic.X86Blendvpd || - node.Intrinsic == Intrinsic.X86Blendvps || - node.Intrinsic == Intrinsic.X86Pblendvb; - - // BLENDVPD, BLENDVPS, PBLENDVB last operand is always implied to be XMM0 when VEX is not supported. - // SHA256RNDS2 always has an implied XMM0 as a last operand. - if ((isBlend && !HardwareCapabilities.SupportsVexEncoding) || node.Intrinsic == Intrinsic.X86Sha256Rnds2) - { - Operand xmm0 = Xmm(X86Register.Xmm0, OperandType.V128); - - nodes.AddBefore(node, Operation(Instruction.Copy, xmm0, node.GetSource(2))); - - node.SetSource(2, xmm0); - } - - break; - } - - case Instruction.Multiply64HighSI: - case Instruction.Multiply64HighUI: - { - // Handle the many restrictions of the i64 * i64 = i128 multiply instructions: - // - The multiplicand is always in RAX. - // - The lower 64-bits of the result is always in RAX. - // - The higher 64-bits of the result is always in RDX. - Operand src1 = node.GetSource(0); - - Operand rax = Gpr(X86Register.Rax, src1.Type); - Operand rdx = Gpr(X86Register.Rdx, src1.Type); - - nodes.AddBefore(node, Operation(Instruction.Copy, rax, src1)); - - node.SetSource(0, rax); - - nodes.AddAfter(node, Operation(Instruction.Copy, dest, rdx)); - - node.SetDestinations(new Operand[] { rdx, rax }); - - break; - } - case Instruction.RotateRight: case Instruction.ShiftLeft: case Instruction.ShiftRightSI: case Instruction.ShiftRightUI: - { - // The shift register is always implied to be CL (low 8-bits of RCX or ECX). - if (node.GetSource(1).Kind == OperandKind.LocalVariable) { - Operand rcx = Gpr(X86Register.Rcx, OperandType.I32); + // The shift register is always implied to be CL (low 8-bits of RCX or ECX). + if (node.GetSource(1).Kind == OperandKind.LocalVariable) + { + Operand rcx = Gpr(X86Register.Rcx, OperandType.I32); - nodes.AddBefore(node, Operation(Instruction.Copy, rcx, node.GetSource(1))); + nodes.AddBefore(node, Operation(Instruction.Copy, rcx, node.GetSource(1))); - node.SetSource(1, rcx); + node.SetSource(1, rcx); + } + + break; } - - break; - } } } @@ -459,7 +456,7 @@ namespace ARMeilleure.CodeGen.X86 // Unsigned integer to FP conversions are not supported on X86. // We need to turn them into signed integer to FP conversions, and // adjust the final result. - Operand dest = node.Destination; + Operand dest = node.Destination; Operand source = node.GetSource(0); Debug.Assert(source.Type.IsInteger(), $"Invalid source type \"{source.Type}\"."); @@ -472,8 +469,8 @@ namespace ARMeilleure.CodeGen.X86 // and then use the 64-bits signed conversion instructions. Operand zex = Local(OperandType.I64); - node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend32, zex, source)); - node = nodes.AddAfter(node, Operation(Instruction.ConvertToFP, dest, zex)); + node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend32, zex, source)); + nodes.AddAfter(node, Operation(Instruction.ConvertToFP, dest, zex)); } else /* if (source.Type == OperandType.I64) */ { @@ -487,15 +484,15 @@ namespace ARMeilleure.CodeGen.X86 // --- This can be done efficiently by adding the result to itself. // -- Then, we need to add the least significant bit that was shifted out. // --- We can convert the least significant bit to float, and add it to the result. - Operand lsb = Local(OperandType.I64); + Operand lsb = Local(OperandType.I64); Operand half = Local(OperandType.I64); Operand lsbF = Local(dest.Type); - node = nodes.AddAfter(node, Operation(Instruction.Copy, lsb, source)); + node = nodes.AddAfter(node, Operation(Instruction.Copy, lsb, source)); node = nodes.AddAfter(node, Operation(Instruction.Copy, half, source)); - node = nodes.AddAfter(node, Operation(Instruction.BitwiseAnd, lsb, lsb, Const(1L))); + node = nodes.AddAfter(node, Operation(Instruction.BitwiseAnd, lsb, lsb, Const(1L))); node = nodes.AddAfter(node, Operation(Instruction.ShiftRightUI, half, half, Const(1))); node = nodes.AddAfter(node, Operation(Instruction.ConvertToFP, lsbF, lsb)); @@ -513,7 +510,7 @@ namespace ARMeilleure.CodeGen.X86 // There's no SSE FP negate instruction, so we need to transform that into // a XOR of the value to be negated with a mask with the highest bit set. // This also produces -0 for a negation of the value 0. - Operand dest = node.Destination; + Operand dest = node.Destination; Operand source = node.GetSource(0); Debug.Assert(dest.Type == OperandType.FP32 || @@ -569,14 +566,14 @@ namespace ARMeilleure.CodeGen.X86 if ((index & 1) != 0) { node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend8, temp1, temp1)); - node = nodes.AddAfter(node, Operation(Instruction.ShiftLeft, temp2, temp2, Const(8))); - node = nodes.AddAfter(node, Operation(Instruction.BitwiseOr, temp1, temp1, temp2)); + node = nodes.AddAfter(node, Operation(Instruction.ShiftLeft, temp2, temp2, Const(8))); + node = nodes.AddAfter(node, Operation(Instruction.BitwiseOr, temp1, temp1, temp2)); } else { node = nodes.AddAfter(node, Operation(Instruction.ZeroExtend8, temp2, temp2)); - node = nodes.AddAfter(node, Operation(Instruction.BitwiseAnd, temp1, temp1, Const(0xff00))); - node = nodes.AddAfter(node, Operation(Instruction.BitwiseOr, temp1, temp1, temp2)); + node = nodes.AddAfter(node, Operation(Instruction.BitwiseAnd, temp1, temp1, Const(0xff00))); + node = nodes.AddAfter(node, Operation(Instruction.BitwiseOr, temp1, temp1, temp2)); } Operation vinsOp = Operation(Instruction.VectorInsert16, dest, src1, temp1, Const(index >> 1)); @@ -709,16 +706,11 @@ namespace ARMeilleure.CodeGen.X86 private static bool HasConstSrc1(Instruction inst) { - switch (inst) + return inst switch { - case Instruction.Copy: - case Instruction.LoadArgument: - case Instruction.Spill: - case Instruction.SpillArg: - return true; - } - - return false; + Instruction.Copy or Instruction.LoadArgument or Instruction.Spill or Instruction.SpillArg => true, + _ => false, + }; } private static bool HasConstSrc2(Instruction inst) @@ -762,15 +754,15 @@ namespace ARMeilleure.CodeGen.X86 case Instruction.BranchIf: case Instruction.Compare: - { - Operand comp = operation.GetSource(2); + { + Operand comp = operation.GetSource(2); - Debug.Assert(comp.Kind == OperandKind.Constant); + Debug.Assert(comp.Kind == OperandKind.Constant); - var compType = (Comparison)comp.AsInt32(); + var compType = (Comparison)comp.AsInt32(); - return compType == Comparison.Equal || compType == Comparison.NotEqual; - } + return compType == Comparison.Equal || compType == Comparison.NotEqual; + } } return false; @@ -793,4 +785,4 @@ namespace ARMeilleure.CodeGen.X86 return info.Type != IntrinsicType.Crc32; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/PreAllocatorSystemV.cs b/src/ARMeilleure/CodeGen/X86/PreAllocatorSystemV.cs index a84d5050d..e754cb09b 100644 --- a/src/ARMeilleure/CodeGen/X86/PreAllocatorSystemV.cs +++ b/src/ARMeilleure/CodeGen/X86/PreAllocatorSystemV.cs @@ -1,4 +1,3 @@ -using ARMeilleure.CodeGen.RegisterAllocators; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; @@ -15,9 +14,9 @@ namespace ARMeilleure.CodeGen.X86 { Operand dest = node.Destination; - List sources = new List + List sources = new() { - node.GetSource(0) + node.GetSource(0), }; int argsCount = node.SourcesCount - 1; @@ -52,10 +51,10 @@ namespace ARMeilleure.CodeGen.X86 if (source.Type == OperandType.V128 && passOnReg) { // V128 is a struct, we pass each half on a GPR if possible. - Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); + Operand argReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); Operand argReg2 = Gpr(CallingConvention.GetIntArgumentRegister(intCount++), OperandType.I64); - nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0))); + nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg, source, Const(0))); nodes.AddBefore(node, Operation(Instruction.VectorExtract, argReg2, source, Const(1))); continue; @@ -91,7 +90,7 @@ namespace ARMeilleure.CodeGen.X86 { if (dest.Type == OperandType.V128) { - Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); + Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); Operand retHReg = Gpr(CallingConvention.GetIntReturnRegisterHigh(), OperandType.I64); Operation operation = node; @@ -116,11 +115,11 @@ namespace ARMeilleure.CodeGen.X86 } } - public static void InsertTailcallCopies(IntrusiveList nodes, StackAllocator stackAlloc, Operation node) + public static void InsertTailcallCopies(IntrusiveList nodes, Operation node) { - List sources = new List + List sources = new() { - node.GetSource(0) + node.GetSource(0), }; int argsCount = node.SourcesCount - 1; @@ -251,11 +250,11 @@ namespace ARMeilleure.CodeGen.X86 // V128 is a struct, we pass each half on a GPR if possible. Operand pArg = Local(OperandType.V128); - Operand argLReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount), OperandType.I64); + Operand argLReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount), OperandType.I64); Operand argHReg = Gpr(CallingConvention.GetIntArgumentRegister(intCount + 1), OperandType.I64); Operation copyL = Operation(Instruction.VectorCreateScalar, pArg, argLReg); - Operation copyH = Operation(Instruction.VectorInsert, pArg, pArg, argHReg, Const(1)); + Operation copyH = Operation(Instruction.VectorInsert, pArg, pArg, argHReg, Const(1)); cctx.Cfg.Entry.Operations.AddFirst(copyH); cctx.Cfg.Entry.Operations.AddFirst(copyL); @@ -313,7 +312,7 @@ namespace ARMeilleure.CodeGen.X86 if (source.Type == OperandType.V128) { - Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); + Operand retLReg = Gpr(CallingConvention.GetIntReturnRegister(), OperandType.I64); Operand retHReg = Gpr(CallingConvention.GetIntReturnRegisterHigh(), OperandType.I64); nodes.AddBefore(node, Operation(Instruction.VectorExtract, retLReg, source, Const(0))); @@ -331,4 +330,4 @@ namespace ARMeilleure.CodeGen.X86 } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/PreAllocatorWindows.cs b/src/ARMeilleure/CodeGen/X86/PreAllocatorWindows.cs index 45319e6a5..10a2bd129 100644 --- a/src/ARMeilleure/CodeGen/X86/PreAllocatorWindows.cs +++ b/src/ARMeilleure/CodeGen/X86/PreAllocatorWindows.cs @@ -155,7 +155,7 @@ namespace ARMeilleure.CodeGen.X86 node.SetSources(sources); } - public static void InsertTailcallCopies(IntrusiveList nodes, StackAllocator stackAlloc, Operation node) + public static void InsertTailcallCopies(IntrusiveList nodes, Operation node) { int argsCount = node.SourcesCount - 1; int maxArgs = CallingConvention.GetArgumentsOnRegsCount(); @@ -324,4 +324,4 @@ namespace ARMeilleure.CodeGen.X86 node.SetSources(Array.Empty()); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/X86Condition.cs b/src/ARMeilleure/CodeGen/X86/X86Condition.cs index c82cbdec5..70699a207 100644 --- a/src/ARMeilleure/CodeGen/X86/X86Condition.cs +++ b/src/ARMeilleure/CodeGen/X86/X86Condition.cs @@ -5,22 +5,22 @@ namespace ARMeilleure.CodeGen.X86 { enum X86Condition { - Overflow = 0x0, - NotOverflow = 0x1, - Below = 0x2, - AboveOrEqual = 0x3, - Equal = 0x4, - NotEqual = 0x5, - BelowOrEqual = 0x6, - Above = 0x7, - Sign = 0x8, - NotSign = 0x9, - ParityEven = 0xa, - ParityOdd = 0xb, - Less = 0xc, + Overflow = 0x0, + NotOverflow = 0x1, + Below = 0x2, + AboveOrEqual = 0x3, + Equal = 0x4, + NotEqual = 0x5, + BelowOrEqual = 0x6, + Above = 0x7, + Sign = 0x8, + NotSign = 0x9, + ParityEven = 0xa, + ParityOdd = 0xb, + Less = 0xc, GreaterOrEqual = 0xd, - LessOrEqual = 0xe, - Greater = 0xf + LessOrEqual = 0xe, + Greater = 0xf, } static class ComparisonX86Extensions @@ -29,6 +29,7 @@ namespace ARMeilleure.CodeGen.X86 { return comp switch { +#pragma warning disable IDE0055 // Disable formatting Comparison.Equal => X86Condition.Equal, Comparison.NotEqual => X86Condition.NotEqual, Comparison.Greater => X86Condition.Greater, @@ -39,9 +40,10 @@ namespace ARMeilleure.CodeGen.X86 Comparison.Less => X86Condition.Less, Comparison.GreaterOrEqualUI => X86Condition.AboveOrEqual, Comparison.LessUI => X86Condition.Below, +#pragma warning restore IDE0055 - _ => throw new ArgumentException(null, nameof(comp)) + _ => throw new ArgumentException(null, nameof(comp)), }; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/X86Instruction.cs b/src/ARMeilleure/CodeGen/X86/X86Instruction.cs index 9a85c516f..e1979011d 100644 --- a/src/ARMeilleure/CodeGen/X86/X86Instruction.cs +++ b/src/ARMeilleure/CodeGen/X86/X86Instruction.cs @@ -226,6 +226,6 @@ namespace ARMeilleure.CodeGen.X86 Xorpd, Xorps, - Count + Count, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs b/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs index 98a19b9a2..9d23f9ada 100644 --- a/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs +++ b/src/ARMeilleure/CodeGen/X86/X86Optimizer.cs @@ -215,7 +215,7 @@ namespace ARMeilleure.CodeGen.X86 1 => Multiplier.x2, 2 => Multiplier.x4, 3 => Multiplier.x8, - _ => Multiplier.x1 + _ => Multiplier.x1, }; baseOp = indexOnSrc2 ? src1 : src2; diff --git a/src/ARMeilleure/CodeGen/X86/X86Register.cs b/src/ARMeilleure/CodeGen/X86/X86Register.cs index 01f63e311..0a6563663 100644 --- a/src/ARMeilleure/CodeGen/X86/X86Register.cs +++ b/src/ARMeilleure/CodeGen/X86/X86Register.cs @@ -1,5 +1,8 @@ +using System.Diagnostics.CodeAnalysis; + namespace ARMeilleure.CodeGen.X86 { + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] enum X86Register { Invalid = -1, @@ -12,8 +15,8 @@ namespace ARMeilleure.CodeGen.X86 Rbp = 5, Rsi = 6, Rdi = 7, - R8 = 8, - R9 = 9, + R8 = 8, + R9 = 9, R10 = 10, R11 = 11, R12 = 12, @@ -21,21 +24,21 @@ namespace ARMeilleure.CodeGen.X86 R14 = 14, R15 = 15, - Xmm0 = 0, - Xmm1 = 1, - Xmm2 = 2, - Xmm3 = 3, - Xmm4 = 4, - Xmm5 = 5, - Xmm6 = 6, - Xmm7 = 7, - Xmm8 = 8, - Xmm9 = 9, + Xmm0 = 0, + Xmm1 = 1, + Xmm2 = 2, + Xmm3 = 3, + Xmm4 = 4, + Xmm5 = 5, + Xmm6 = 6, + Xmm7 = 7, + Xmm8 = 8, + Xmm9 = 9, Xmm10 = 10, Xmm11 = 11, Xmm12 = 12, Xmm13 = 13, Xmm14 = 14, - Xmm15 = 15 + Xmm15 = 15, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Common/ArenaAllocator.cs b/src/ARMeilleure/Common/ArenaAllocator.cs index bce6794ad..f810c2abd 100644 --- a/src/ARMeilleure/Common/ArenaAllocator.cs +++ b/src/ARMeilleure/Common/ArenaAllocator.cs @@ -82,8 +82,10 @@ namespace ARMeilleure.Common } else { - _page = new PageInfo(); - _page.Pointer = (byte*)NativeAllocator.Instance.Allocate(_pageSize); + _page = new PageInfo + { + Pointer = (byte*)NativeAllocator.Instance.Allocate(_pageSize), + }; _pages.Add(_page); } @@ -106,7 +108,7 @@ namespace ARMeilleure.Common // Free excess pages that was allocated. while (_pages.Count > _pageCount) { - NativeAllocator.Instance.Free(_pages[_pages.Count - 1].Pointer); + NativeAllocator.Instance.Free(_pages[^1].Pointer); _pages.RemoveAt(_pages.Count - 1); } @@ -125,12 +127,13 @@ namespace ARMeilleure.Common // If arena is used frequently, keep pages for longer. Otherwise keep pages for a shorter amount of time. int now = Environment.TickCount; - int count = (now - _lastReset) switch { + int count = (now - _lastReset) switch + { >= 5000 => 0, >= 2500 => 50, >= 1000 => 100, - >= 10 => 1500, - _ => 5000 + >= 10 => 1500, + _ => 5000, }; for (int i = _pages.Count - 1; i >= 0; i--) diff --git a/src/ARMeilleure/Common/BitMap.cs b/src/ARMeilleure/Common/BitMap.cs index 27ef031f3..94d47ea59 100644 --- a/src/ARMeilleure/Common/BitMap.cs +++ b/src/ARMeilleure/Common/BitMap.cs @@ -138,7 +138,7 @@ namespace ARMeilleure.Common var newSpan = new Span(_masks, _count); oldSpan.CopyTo(newSpan); - newSpan.Slice(oldSpan.Length).Clear(); + newSpan[oldSpan.Length..].Clear(); _allocator.Free(oldMask); } @@ -176,8 +176,8 @@ namespace ARMeilleure.Common private int _bit; private readonly BitMap _map; - public int Current => (int)_index * IntSize + _bit; - object IEnumerator.Current => Current; + public readonly int Current => (int)_index * IntSize + _bit; + readonly object IEnumerator.Current => Current; public Enumerator(BitMap map) { @@ -214,9 +214,9 @@ namespace ARMeilleure.Common return true; } - public void Reset() { } + public readonly void Reset() { } - public void Dispose() { } + public readonly void Dispose() { } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/Block.cs b/src/ARMeilleure/Decoders/Block.cs index f296d299d..bb88170da 100644 --- a/src/ARMeilleure/Decoders/Block.cs +++ b/src/ARMeilleure/Decoders/Block.cs @@ -5,10 +5,10 @@ namespace ARMeilleure.Decoders { class Block { - public ulong Address { get; set; } + public ulong Address { get; set; } public ulong EndAddress { get; set; } - public Block Next { get; set; } + public Block Next { get; set; } public Block Branch { get; set; } public bool Exit { get; set; } @@ -43,14 +43,14 @@ namespace ARMeilleure.Decoders rightBlock.EndAddress = EndAddress; - rightBlock.Next = Next; + rightBlock.Next = Next; rightBlock.Branch = Branch; rightBlock.OpCodes.AddRange(OpCodes.GetRange(splitIndex, splitCount)); EndAddress = rightBlock.Address; - Next = rightBlock; + Next = rightBlock; Branch = null; OpCodes.RemoveRange(splitIndex, splitCount); @@ -58,9 +58,9 @@ namespace ARMeilleure.Decoders private static int BinarySearch(List opCodes, ulong address) { - int left = 0; + int left = 0; int middle = 0; - int right = opCodes.Count - 1; + int right = opCodes.Count - 1; while (left <= right) { @@ -92,10 +92,10 @@ namespace ARMeilleure.Decoders { if (OpCodes.Count > 0) { - return OpCodes[OpCodes.Count - 1]; + return OpCodes[^1]; } return null; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/Condition.cs b/src/ARMeilleure/Decoders/Condition.cs index 727f897da..961825a10 100644 --- a/src/ARMeilleure/Decoders/Condition.cs +++ b/src/ARMeilleure/Decoders/Condition.cs @@ -2,22 +2,22 @@ namespace ARMeilleure.Decoders { enum Condition { - Eq = 0, - Ne = 1, + Eq = 0, + Ne = 1, GeUn = 2, LtUn = 3, - Mi = 4, - Pl = 5, - Vs = 6, - Vc = 7, + Mi = 4, + Pl = 5, + Vs = 6, + Vc = 7, GtUn = 8, LeUn = 9, - Ge = 10, - Lt = 11, - Gt = 12, - Le = 13, - Al = 14, - Nv = 15 + Ge = 10, + Lt = 11, + Gt = 12, + Le = 13, + Al = 14, + Nv = 15, } static class ConditionExtensions @@ -29,4 +29,4 @@ namespace ARMeilleure.Decoders return (Condition)((int)cond ^ 1); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/DataOp.cs b/src/ARMeilleure/Decoders/DataOp.cs index 464d00898..f99fd5e70 100644 --- a/src/ARMeilleure/Decoders/DataOp.cs +++ b/src/ARMeilleure/Decoders/DataOp.cs @@ -2,9 +2,9 @@ namespace ARMeilleure.Decoders { enum DataOp { - Adr = 0, + Adr = 0, Arithmetic = 1, - Logical = 2, - BitField = 3 + Logical = 2, + BitField = 3, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/Decoder.cs b/src/ARMeilleure/Decoders/Decoder.cs index 426465aaa..6d07827a2 100644 --- a/src/ARMeilleure/Decoders/Decoder.cs +++ b/src/ARMeilleure/Decoders/Decoder.cs @@ -20,11 +20,11 @@ namespace ARMeilleure.Decoders public static Block[] Decode(IMemoryManager memory, ulong address, ExecutionMode mode, bool highCq, DecoderMode dMode) { - List blocks = new List(); + List blocks = new(); - Queue workQueue = new Queue(); + Queue workQueue = new(); - Dictionary visited = new Dictionary(); + Dictionary visited = new(); Debug.Assert(MaxInstsPerFunctionLowCq <= MaxInstsPerFunction); @@ -163,7 +163,7 @@ namespace ARMeilleure.Decoders { index = 0; - int left = 0; + int left = 0; int right = blocks.Count - 1; while (left <= right) @@ -196,9 +196,9 @@ namespace ARMeilleure.Decoders private static void FillBlock( IMemoryManager memory, - ExecutionMode mode, - Block block, - ulong limitAddress) + ExecutionMode mode, + Block block, + ulong limitAddress) { ulong address = block.Address; int itBlockSize = 0; @@ -241,12 +241,12 @@ namespace ARMeilleure.Decoders private static bool IsUnconditionalBranch(OpCode opCode) { return opCode is OpCodeBImmAl || - opCode is OpCodeBReg || IsAarch32UnconditionalBranch(opCode); + opCode is OpCodeBReg || IsAarch32UnconditionalBranch(opCode); } private static bool IsAarch32UnconditionalBranch(OpCode opCode) { - if (!(opCode is OpCode32 op)) + if (opCode is not OpCode32 op) { return false; } @@ -290,9 +290,9 @@ namespace ARMeilleure.Decoders if (opCode is IOpCode32Mem opMem) { - rt = opMem.Rt; - rn = opMem.Rn; - wBack = opMem.WBack; + rt = opMem.Rt; + rn = opMem.Rn; + wBack = opMem.WBack; isLoad = opMem.IsLoad; // For the dual load, we also need to take into account the @@ -304,12 +304,12 @@ namespace ARMeilleure.Decoders } else if (opCode is IOpCode32MemMult opMemMult) { - const int pcMask = 1 << RegisterAlias.Aarch32Pc; + const int PCMask = 1 << RegisterAlias.Aarch32Pc; - rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0; - rn = opMemMult.Rn; - wBack = opMemMult.PostOffset != 0; - isLoad = opMemMult.IsLoad; + rt = (opMemMult.RegisterMask & PCMask) != 0 ? RegisterAlias.Aarch32Pc : 0; + rn = opMemMult.Rn; + wBack = opMemMult.PostOffset != 0; + isLoad = opMemMult.IsLoad; } else { @@ -388,4 +388,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/DecoderHelper.cs b/src/ARMeilleure/Decoders/DecoderHelper.cs index 5227e6a19..35e573955 100644 --- a/src/ARMeilleure/Decoders/DecoderHelper.cs +++ b/src/ARMeilleure/Decoders/DecoderHelper.cs @@ -10,7 +10,7 @@ namespace ARMeilleure.Decoders Imm8ToFP64Table = BuildImm8ToFP64Table(); } - public static readonly uint[] Imm8ToFP32Table; + public static readonly uint[] Imm8ToFP32Table; public static readonly ulong[] Imm8ToFP64Table; private static uint[] BuildImm8ToFP32Table() @@ -40,47 +40,47 @@ namespace ARMeilleure.Decoders // abcdefgh -> aBbbbbbc defgh000 00000000 00000000 (B = ~b) private static uint ExpandImm8ToFP32(uint imm) { - uint MoveBit(uint bits, int from, int to) + static uint MoveBit(uint bits, int from, int to) { return ((bits >> from) & 1U) << to; } return MoveBit(imm, 7, 31) | MoveBit(~imm, 6, 30) | - MoveBit(imm, 6, 29) | MoveBit( imm, 6, 28) | - MoveBit(imm, 6, 27) | MoveBit( imm, 6, 26) | - MoveBit(imm, 6, 25) | MoveBit( imm, 5, 24) | - MoveBit(imm, 4, 23) | MoveBit( imm, 3, 22) | - MoveBit(imm, 2, 21) | MoveBit( imm, 1, 20) | + MoveBit(imm, 6, 29) | MoveBit(imm, 6, 28) | + MoveBit(imm, 6, 27) | MoveBit(imm, 6, 26) | + MoveBit(imm, 6, 25) | MoveBit(imm, 5, 24) | + MoveBit(imm, 4, 23) | MoveBit(imm, 3, 22) | + MoveBit(imm, 2, 21) | MoveBit(imm, 1, 20) | MoveBit(imm, 0, 19); } // abcdefgh -> aBbbbbbb bbcdefgh 00000000 00000000 00000000 00000000 00000000 00000000 (B = ~b) private static ulong ExpandImm8ToFP64(ulong imm) { - ulong MoveBit(ulong bits, int from, int to) + static ulong MoveBit(ulong bits, int from, int to) { return ((bits >> from) & 1UL) << to; } return MoveBit(imm, 7, 63) | MoveBit(~imm, 6, 62) | - MoveBit(imm, 6, 61) | MoveBit( imm, 6, 60) | - MoveBit(imm, 6, 59) | MoveBit( imm, 6, 58) | - MoveBit(imm, 6, 57) | MoveBit( imm, 6, 56) | - MoveBit(imm, 6, 55) | MoveBit( imm, 6, 54) | - MoveBit(imm, 5, 53) | MoveBit( imm, 4, 52) | - MoveBit(imm, 3, 51) | MoveBit( imm, 2, 50) | - MoveBit(imm, 1, 49) | MoveBit( imm, 0, 48); + MoveBit(imm, 6, 61) | MoveBit(imm, 6, 60) | + MoveBit(imm, 6, 59) | MoveBit(imm, 6, 58) | + MoveBit(imm, 6, 57) | MoveBit(imm, 6, 56) | + MoveBit(imm, 6, 55) | MoveBit(imm, 6, 54) | + MoveBit(imm, 5, 53) | MoveBit(imm, 4, 52) | + MoveBit(imm, 3, 51) | MoveBit(imm, 2, 50) | + MoveBit(imm, 1, 49) | MoveBit(imm, 0, 48); } public struct BitMask { public long WMask; public long TMask; - public int Pos; - public int Shift; + public int Pos; + public int Shift; public bool IsUndefined; - public static BitMask Invalid => new BitMask { IsUndefined = true }; + public static BitMask Invalid => new() { IsUndefined = true }; } public static BitMask DecodeBitMask(int opCode, bool immediate) @@ -88,7 +88,7 @@ namespace ARMeilleure.Decoders int immS = (opCode >> 10) & 0x3f; int immR = (opCode >> 16) & 0x3f; - int n = (opCode >> 22) & 1; + int n = (opCode >> 22) & 1; int sf = (opCode >> 31) & 1; int length = BitUtils.HighestBitSet((~immS & 0x3f) | (n << 6)); @@ -115,7 +115,7 @@ namespace ARMeilleure.Decoders if (r > 0) { - wMask = BitUtils.RotateRight(wMask, r, size); + wMask = BitUtils.RotateRight(wMask, r, size); wMask &= BitUtils.FillWithOnes(size); } @@ -124,8 +124,8 @@ namespace ARMeilleure.Decoders WMask = BitUtils.Replicate(wMask, size), TMask = BitUtils.Replicate(tMask, size), - Pos = immS, - Shift = immR + Pos = immS, + Shift = immR, }; } @@ -164,4 +164,4 @@ namespace ARMeilleure.Decoders return false; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/DecoderMode.cs b/src/ARMeilleure/Decoders/DecoderMode.cs index 553620847..280ebb649 100644 --- a/src/ARMeilleure/Decoders/DecoderMode.cs +++ b/src/ARMeilleure/Decoders/DecoderMode.cs @@ -6,4 +6,4 @@ SingleBlock, SingleInstruction, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode.cs b/src/ARMeilleure/Decoders/IOpCode.cs index 37ba7a4c6..9d5e3bf7a 100644 --- a/src/ARMeilleure/Decoders/IOpCode.cs +++ b/src/ARMeilleure/Decoders/IOpCode.cs @@ -14,4 +14,4 @@ namespace ARMeilleure.Decoders OperandType GetOperandType(); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32.cs b/src/ARMeilleure/Decoders/IOpCode32.cs index 126c10690..578925dee 100644 --- a/src/ARMeilleure/Decoders/IOpCode32.cs +++ b/src/ARMeilleure/Decoders/IOpCode32.cs @@ -6,4 +6,4 @@ namespace ARMeilleure.Decoders uint GetPc(); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32Alu.cs b/src/ARMeilleure/Decoders/IOpCode32Alu.cs index 69fee164c..a85ef44ad 100644 --- a/src/ARMeilleure/Decoders/IOpCode32Alu.cs +++ b/src/ARMeilleure/Decoders/IOpCode32Alu.cs @@ -5,4 +5,4 @@ namespace ARMeilleure.Decoders int Rd { get; } int Rn { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32AluImm.cs b/src/ARMeilleure/Decoders/IOpCode32AluImm.cs index 342fb8f6c..9d49a440d 100644 --- a/src/ARMeilleure/Decoders/IOpCode32AluImm.cs +++ b/src/ARMeilleure/Decoders/IOpCode32AluImm.cs @@ -6,4 +6,4 @@ bool IsRotated { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32AluImm16.cs b/src/ARMeilleure/Decoders/IOpCode32AluImm16.cs index cd128f657..dd42a70b1 100644 --- a/src/ARMeilleure/Decoders/IOpCode32AluImm16.cs +++ b/src/ARMeilleure/Decoders/IOpCode32AluImm16.cs @@ -4,4 +4,4 @@ namespace ARMeilleure.Decoders { int Immediate { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32AluRsImm.cs b/src/ARMeilleure/Decoders/IOpCode32AluRsImm.cs index e899a6592..8b976b58f 100644 --- a/src/ARMeilleure/Decoders/IOpCode32AluRsImm.cs +++ b/src/ARMeilleure/Decoders/IOpCode32AluRsImm.cs @@ -7,4 +7,4 @@ ShiftType ShiftType { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32AluRsReg.cs b/src/ARMeilleure/Decoders/IOpCode32AluRsReg.cs index 879db0593..e8c33c2b1 100644 --- a/src/ARMeilleure/Decoders/IOpCode32AluRsReg.cs +++ b/src/ARMeilleure/Decoders/IOpCode32AluRsReg.cs @@ -7,4 +7,4 @@ ShiftType ShiftType { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32BImm.cs b/src/ARMeilleure/Decoders/IOpCode32BImm.cs index ec7db2c26..8d22d5c40 100644 --- a/src/ARMeilleure/Decoders/IOpCode32BImm.cs +++ b/src/ARMeilleure/Decoders/IOpCode32BImm.cs @@ -1,4 +1,4 @@ namespace ARMeilleure.Decoders { interface IOpCode32BImm : IOpCode32, IOpCodeBImm { } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32BReg.cs b/src/ARMeilleure/Decoders/IOpCode32BReg.cs index 097ab4275..9badc9858 100644 --- a/src/ARMeilleure/Decoders/IOpCode32BReg.cs +++ b/src/ARMeilleure/Decoders/IOpCode32BReg.cs @@ -4,4 +4,4 @@ namespace ARMeilleure.Decoders { int Rm { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32Exception.cs b/src/ARMeilleure/Decoders/IOpCode32Exception.cs index 8f0fb81a0..4c1fc231c 100644 --- a/src/ARMeilleure/Decoders/IOpCode32Exception.cs +++ b/src/ARMeilleure/Decoders/IOpCode32Exception.cs @@ -4,4 +4,4 @@ { int Id { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32HasSetFlags.cs b/src/ARMeilleure/Decoders/IOpCode32HasSetFlags.cs index 71ca6d19c..772e1080f 100644 --- a/src/ARMeilleure/Decoders/IOpCode32HasSetFlags.cs +++ b/src/ARMeilleure/Decoders/IOpCode32HasSetFlags.cs @@ -4,4 +4,4 @@ { bool? SetFlags { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32Mem.cs b/src/ARMeilleure/Decoders/IOpCode32Mem.cs index 6664ddffd..a34bc0e2a 100644 --- a/src/ARMeilleure/Decoders/IOpCode32Mem.cs +++ b/src/ARMeilleure/Decoders/IOpCode32Mem.cs @@ -13,4 +13,4 @@ namespace ARMeilleure.Decoders int Immediate { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32MemMult.cs b/src/ARMeilleure/Decoders/IOpCode32MemMult.cs index 4b891bc1b..0c5e48f22 100644 --- a/src/ARMeilleure/Decoders/IOpCode32MemMult.cs +++ b/src/ARMeilleure/Decoders/IOpCode32MemMult.cs @@ -12,4 +12,4 @@ namespace ARMeilleure.Decoders int Offset { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32MemReg.cs b/src/ARMeilleure/Decoders/IOpCode32MemReg.cs index 7fe1b0229..f356e4d7c 100644 --- a/src/ARMeilleure/Decoders/IOpCode32MemReg.cs +++ b/src/ARMeilleure/Decoders/IOpCode32MemReg.cs @@ -4,4 +4,4 @@ { int Rm { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCode32MemRsImm.cs b/src/ARMeilleure/Decoders/IOpCode32MemRsImm.cs index 65b7ee0b4..3407e98ac 100644 --- a/src/ARMeilleure/Decoders/IOpCode32MemRsImm.cs +++ b/src/ARMeilleure/Decoders/IOpCode32MemRsImm.cs @@ -5,4 +5,4 @@ namespace ARMeilleure.Decoders int Rm { get; } ShiftType ShiftType { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeAlu.cs b/src/ARMeilleure/Decoders/IOpCodeAlu.cs index b8c28513d..059769ba9 100644 --- a/src/ARMeilleure/Decoders/IOpCodeAlu.cs +++ b/src/ARMeilleure/Decoders/IOpCodeAlu.cs @@ -7,4 +7,4 @@ namespace ARMeilleure.Decoders DataOp DataOp { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeAluImm.cs b/src/ARMeilleure/Decoders/IOpCodeAluImm.cs index 02f4c997b..40a69cc90 100644 --- a/src/ARMeilleure/Decoders/IOpCodeAluImm.cs +++ b/src/ARMeilleure/Decoders/IOpCodeAluImm.cs @@ -4,4 +4,4 @@ namespace ARMeilleure.Decoders { long Immediate { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeAluRs.cs b/src/ARMeilleure/Decoders/IOpCodeAluRs.cs index 22540b11a..eec956982 100644 --- a/src/ARMeilleure/Decoders/IOpCodeAluRs.cs +++ b/src/ARMeilleure/Decoders/IOpCodeAluRs.cs @@ -3,8 +3,8 @@ namespace ARMeilleure.Decoders interface IOpCodeAluRs : IOpCodeAlu { int Shift { get; } - int Rm { get; } + int Rm { get; } ShiftType ShiftType { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeAluRx.cs b/src/ARMeilleure/Decoders/IOpCodeAluRx.cs index 9d16be787..e5a8559d8 100644 --- a/src/ARMeilleure/Decoders/IOpCodeAluRx.cs +++ b/src/ARMeilleure/Decoders/IOpCodeAluRx.cs @@ -3,8 +3,8 @@ namespace ARMeilleure.Decoders interface IOpCodeAluRx : IOpCodeAlu { int Shift { get; } - int Rm { get; } + int Rm { get; } IntType IntType { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeBImm.cs b/src/ARMeilleure/Decoders/IOpCodeBImm.cs index 958bff28d..9ce7512a1 100644 --- a/src/ARMeilleure/Decoders/IOpCodeBImm.cs +++ b/src/ARMeilleure/Decoders/IOpCodeBImm.cs @@ -4,4 +4,4 @@ namespace ARMeilleure.Decoders { long Immediate { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeCond.cs b/src/ARMeilleure/Decoders/IOpCodeCond.cs index 9808f7c08..6604f19a2 100644 --- a/src/ARMeilleure/Decoders/IOpCodeCond.cs +++ b/src/ARMeilleure/Decoders/IOpCodeCond.cs @@ -4,4 +4,4 @@ namespace ARMeilleure.Decoders { Condition Cond { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeLit.cs b/src/ARMeilleure/Decoders/IOpCodeLit.cs index 74084a457..434e4da88 100644 --- a/src/ARMeilleure/Decoders/IOpCodeLit.cs +++ b/src/ARMeilleure/Decoders/IOpCodeLit.cs @@ -2,10 +2,10 @@ namespace ARMeilleure.Decoders { interface IOpCodeLit : IOpCode { - int Rt { get; } + int Rt { get; } long Immediate { get; } - int Size { get; } - bool Signed { get; } - bool Prefetch { get; } + int Size { get; } + bool Signed { get; } + bool Prefetch { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IOpCodeSimd.cs b/src/ARMeilleure/Decoders/IOpCodeSimd.cs index 056ef045c..598d9d7f8 100644 --- a/src/ARMeilleure/Decoders/IOpCodeSimd.cs +++ b/src/ARMeilleure/Decoders/IOpCodeSimd.cs @@ -4,4 +4,4 @@ namespace ARMeilleure.Decoders { int Size { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/InstDescriptor.cs b/src/ARMeilleure/Decoders/InstDescriptor.cs index 577ff3946..c35c754a9 100644 --- a/src/ARMeilleure/Decoders/InstDescriptor.cs +++ b/src/ARMeilleure/Decoders/InstDescriptor.cs @@ -4,15 +4,15 @@ namespace ARMeilleure.Decoders { readonly struct InstDescriptor { - public static InstDescriptor Undefined => new InstDescriptor(InstName.Und, InstEmit.Und); + public static InstDescriptor Undefined => new(InstName.Und, InstEmit.Und); - public InstName Name { get; } + public InstName Name { get; } public InstEmitter Emitter { get; } public InstDescriptor(InstName name, InstEmitter emitter) { - Name = name; + Name = name; Emitter = emitter; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/InstEmitter.cs b/src/ARMeilleure/Decoders/InstEmitter.cs index a8b526569..43bfcdca3 100644 --- a/src/ARMeilleure/Decoders/InstEmitter.cs +++ b/src/ARMeilleure/Decoders/InstEmitter.cs @@ -3,4 +3,4 @@ using ARMeilleure.Translation; namespace ARMeilleure.Decoders { delegate void InstEmitter(ArmEmitterContext context); -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/IntType.cs b/src/ARMeilleure/Decoders/IntType.cs index 244e96805..937a569aa 100644 --- a/src/ARMeilleure/Decoders/IntType.cs +++ b/src/ARMeilleure/Decoders/IntType.cs @@ -2,13 +2,13 @@ namespace ARMeilleure.Decoders { enum IntType { - UInt8 = 0, + UInt8 = 0, UInt16 = 1, UInt32 = 2, UInt64 = 3, - Int8 = 4, - Int16 = 5, - Int32 = 6, - Int64 = 7 + Int8 = 4, + Int16 = 5, + Int32 = 6, + Int64 = 7, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode.cs b/src/ARMeilleure/Decoders/OpCode.cs index f9aed7924..c8123308b 100644 --- a/src/ARMeilleure/Decoders/OpCode.cs +++ b/src/ARMeilleure/Decoders/OpCode.cs @@ -5,8 +5,8 @@ namespace ARMeilleure.Decoders { class OpCode : IOpCode { - public ulong Address { get; } - public int RawOpCode { get; } + public ulong Address { get; } + public int RawOpCode { get; } public int OpCodeSizeInBytes { get; protected set; } = 4; @@ -14,13 +14,13 @@ namespace ARMeilleure.Decoders public RegisterSize RegisterSize { get; protected set; } - public static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCode(inst, address, opCode); + public static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new(inst, address, opCode); public OpCode(InstDescriptor inst, ulong address, int opCode) { Instruction = inst; - Address = address; - RawOpCode = opCode; + Address = address; + RawOpCode = opCode; RegisterSize = RegisterSize.Int64; } @@ -30,15 +30,14 @@ namespace ARMeilleure.Decoders public int GetBitsCount() { - switch (RegisterSize) + return RegisterSize switch { - case RegisterSize.Int32: return 32; - case RegisterSize.Int64: return 64; - case RegisterSize.Simd64: return 64; - case RegisterSize.Simd128: return 128; - } - - throw new InvalidOperationException(); + RegisterSize.Int32 => 32, + RegisterSize.Int64 => 64, + RegisterSize.Simd64 => 64, + RegisterSize.Simd128 => 128, + _ => throw new InvalidOperationException(), + }; } public OperandType GetOperandType() @@ -46,4 +45,4 @@ namespace ARMeilleure.Decoders return RegisterSize == RegisterSize.Int32 ? OperandType.I32 : OperandType.I64; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32.cs b/src/ARMeilleure/Decoders/OpCode32.cs index c2f14145b..a2be01e9a 100644 --- a/src/ARMeilleure/Decoders/OpCode32.cs +++ b/src/ARMeilleure/Decoders/OpCode32.cs @@ -31,4 +31,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32Alu.cs b/src/ARMeilleure/Decoders/OpCode32Alu.cs index 1625aee0a..8634f5ce9 100644 --- a/src/ARMeilleure/Decoders/OpCode32Alu.cs +++ b/src/ARMeilleure/Decoders/OpCode32Alu.cs @@ -17,4 +17,4 @@ namespace ARMeilleure.Decoders SetFlags = ((opCode >> 20) & 1) != 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32AluImm.cs b/src/ARMeilleure/Decoders/OpCode32AluImm.cs index b5435aaf1..c8b05e6bc 100644 --- a/src/ARMeilleure/Decoders/OpCode32AluImm.cs +++ b/src/ARMeilleure/Decoders/OpCode32AluImm.cs @@ -20,4 +20,4 @@ namespace ARMeilleure.Decoders IsRotated = shift != 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32AluRsImm.cs b/src/ARMeilleure/Decoders/OpCode32AluRsImm.cs index c2dee6c9a..4b2c5897a 100644 --- a/src/ARMeilleure/Decoders/OpCode32AluRsImm.cs +++ b/src/ARMeilleure/Decoders/OpCode32AluRsImm.cs @@ -2,7 +2,7 @@ namespace ARMeilleure.Decoders { class OpCode32AluRsImm : OpCode32Alu, IOpCode32AluRsImm { - public int Rm { get; } + public int Rm { get; } public int Immediate { get; } public ShiftType ShiftType { get; } @@ -11,10 +11,10 @@ namespace ARMeilleure.Decoders public OpCode32AluRsImm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rm = (opCode >> 0) & 0xf; + Rm = (opCode >> 0) & 0xf; Immediate = (opCode >> 7) & 0x1f; ShiftType = (ShiftType)((opCode >> 5) & 3); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32BImm.cs b/src/ARMeilleure/Decoders/OpCode32BImm.cs index f2959b331..e7f5d6db1 100644 --- a/src/ARMeilleure/Decoders/OpCode32BImm.cs +++ b/src/ARMeilleure/Decoders/OpCode32BImm.cs @@ -26,4 +26,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32BReg.cs b/src/ARMeilleure/Decoders/OpCode32BReg.cs index d4f5f7601..8939c0de3 100644 --- a/src/ARMeilleure/Decoders/OpCode32BReg.cs +++ b/src/ARMeilleure/Decoders/OpCode32BReg.cs @@ -11,4 +11,4 @@ namespace ARMeilleure.Decoders Rm = opCode & 0xf; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32Mem.cs b/src/ARMeilleure/Decoders/OpCode32Mem.cs index ceb1e49f5..8a2421996 100644 --- a/src/ARMeilleure/Decoders/OpCode32Mem.cs +++ b/src/ARMeilleure/Decoders/OpCode32Mem.cs @@ -9,9 +9,9 @@ namespace ARMeilleure.Decoders public int Immediate { get; protected set; } - public bool Index { get; } - public bool Add { get; } - public bool WBack { get; } + public bool Index { get; } + public bool Add { get; } + public bool WBack { get; } public bool Unprivileged { get; } public bool IsLoad { get; } @@ -24,16 +24,16 @@ namespace ARMeilleure.Decoders Rn = (opCode >> 16) & 0xf; bool isLoad = (opCode & (1 << 20)) != 0; - bool w = (opCode & (1 << 21)) != 0; - bool u = (opCode & (1 << 23)) != 0; - bool p = (opCode & (1 << 24)) != 0; + bool w = (opCode & (1 << 21)) != 0; + bool u = (opCode & (1 << 23)) != 0; + bool p = (opCode & (1 << 24)) != 0; - Index = p; - Add = u; - WBack = !p || w; + Index = p; + Add = u; + WBack = !p || w; Unprivileged = !p && w; IsLoad = isLoad || inst.Name == InstName.Ldrd; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32MemImm.cs b/src/ARMeilleure/Decoders/OpCode32MemImm.cs index 3af4b6f7c..fa10e04ee 100644 --- a/src/ARMeilleure/Decoders/OpCode32MemImm.cs +++ b/src/ARMeilleure/Decoders/OpCode32MemImm.cs @@ -9,4 +9,4 @@ namespace ARMeilleure.Decoders Immediate = opCode & 0xfff; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32MemImm8.cs b/src/ARMeilleure/Decoders/OpCode32MemImm8.cs index 1b8a57de4..248ee8e65 100644 --- a/src/ARMeilleure/Decoders/OpCode32MemImm8.cs +++ b/src/ARMeilleure/Decoders/OpCode32MemImm8.cs @@ -12,4 +12,4 @@ namespace ARMeilleure.Decoders Immediate = imm4L | (imm4H << 4); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32MemMult.cs b/src/ARMeilleure/Decoders/OpCode32MemMult.cs index 522b96bb9..6e39e3479 100644 --- a/src/ARMeilleure/Decoders/OpCode32MemMult.cs +++ b/src/ARMeilleure/Decoders/OpCode32MemMult.cs @@ -7,8 +7,8 @@ namespace ARMeilleure.Decoders public int Rn { get; } public int RegisterMask { get; } - public int Offset { get; } - public int PostOffset { get; } + public int Offset { get; } + public int PostOffset { get; } public bool IsLoad { get; } @@ -19,9 +19,9 @@ namespace ARMeilleure.Decoders Rn = (opCode >> 16) & 0xf; bool isLoad = (opCode & (1 << 20)) != 0; - bool w = (opCode & (1 << 21)) != 0; - bool u = (opCode & (1 << 23)) != 0; - bool p = (opCode & (1 << 24)) != 0; + bool w = (opCode & (1 << 21)) != 0; + bool u = (opCode & (1 << 23)) != 0; + bool p = (opCode & (1 << 24)) != 0; RegisterMask = opCode & 0xffff; @@ -49,4 +49,4 @@ namespace ARMeilleure.Decoders IsLoad = isLoad; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32Mrs.cs b/src/ARMeilleure/Decoders/OpCode32Mrs.cs index c34a8b997..b681b54c0 100644 --- a/src/ARMeilleure/Decoders/OpCode32Mrs.cs +++ b/src/ARMeilleure/Decoders/OpCode32Mrs.cs @@ -2,8 +2,8 @@ namespace ARMeilleure.Decoders { class OpCode32Mrs : OpCode32 { - public bool R { get; } - public int Rd { get; } + public bool R { get; } + public int Rd { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCode32Mrs(inst, address, opCode); diff --git a/src/ARMeilleure/Decoders/OpCode32MsrReg.cs b/src/ARMeilleure/Decoders/OpCode32MsrReg.cs index d897ffd80..7186ebf74 100644 --- a/src/ARMeilleure/Decoders/OpCode32MsrReg.cs +++ b/src/ARMeilleure/Decoders/OpCode32MsrReg.cs @@ -4,11 +4,11 @@ namespace ARMeilleure.Decoders { class OpCode32MsrReg : OpCode32 { - public bool R { get; } - public int Mask { get; } - public int Rd { get; } + public bool R { get; } + public int Mask { get; } + public int Rd { get; } public bool Banked { get; } - public int Rn { get; } + public int Rn { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCode32MsrReg(inst, address, opCode); diff --git a/src/ARMeilleure/Decoders/OpCode32Sat.cs b/src/ARMeilleure/Decoders/OpCode32Sat.cs index 621def27c..35c5cf47a 100644 --- a/src/ARMeilleure/Decoders/OpCode32Sat.cs +++ b/src/ARMeilleure/Decoders/OpCode32Sat.cs @@ -21,4 +21,4 @@ namespace ARMeilleure.Decoders ShiftType = (ShiftType)((opCode >> 5) & 2); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32Sat16.cs b/src/ARMeilleure/Decoders/OpCode32Sat16.cs index 51061b079..01f4d3b23 100644 --- a/src/ARMeilleure/Decoders/OpCode32Sat16.cs +++ b/src/ARMeilleure/Decoders/OpCode32Sat16.cs @@ -15,4 +15,4 @@ namespace ARMeilleure.Decoders SatImm = (opCode >> 16) & 0xf; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32SimdBase.cs b/src/ARMeilleure/Decoders/OpCode32SimdBase.cs index 4382fc2aa..2361ac1eb 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdBase.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdBase.cs @@ -24,27 +24,21 @@ namespace ARMeilleure.Decoders protected int GetQuadwordIndex(int index) { - switch (RegisterSize) + return RegisterSize switch { - case RegisterSize.Simd128: - case RegisterSize.Simd64: - return index >> 1; - } - - throw new InvalidOperationException(); + RegisterSize.Simd128 or RegisterSize.Simd64 => index >> 1, + _ => throw new InvalidOperationException(), + }; } protected int GetQuadwordSubindex(int index) { - switch (RegisterSize) + return RegisterSize switch { - case RegisterSize.Simd128: - return 0; - case RegisterSize.Simd64: - return index & 1; - } - - throw new InvalidOperationException(); + RegisterSize.Simd128 => 0, + RegisterSize.Simd64 => index & 1, + _ => throw new InvalidOperationException(), + }; } protected OpCode32SimdBase(InstDescriptor inst, ulong address, int opCode, bool isThumb) : base(inst, address, opCode) diff --git a/src/ARMeilleure/Decoders/OpCode32SimdCvtFFixed.cs b/src/ARMeilleure/Decoders/OpCode32SimdCvtFFixed.cs new file mode 100644 index 000000000..32faad1ec --- /dev/null +++ b/src/ARMeilleure/Decoders/OpCode32SimdCvtFFixed.cs @@ -0,0 +1,23 @@ +namespace ARMeilleure.Decoders +{ + class OpCode32SimdCvtFFixed : OpCode32Simd + { + public int Fbits { get; protected set; } + + public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCode32SimdCvtFFixed(inst, address, opCode, false); + public new static OpCode CreateT32(InstDescriptor inst, ulong address, int opCode) => new OpCode32SimdCvtFFixed(inst, address, opCode, true); + + public OpCode32SimdCvtFFixed(InstDescriptor inst, ulong address, int opCode, bool isThumb) : base(inst, address, opCode, isThumb) + { + Opc = (opCode >> 8) & 0x1; + + Size = Opc == 1 ? 0 : 2; + Fbits = 64 - ((opCode >> 16) & 0x3f); + + if (DecoderHelper.VectorArgumentsInvalid(Q, Vd, Vm)) + { + Instruction = InstDescriptor.Undefined; + } + } + } +} diff --git a/src/ARMeilleure/Decoders/OpCode32SimdCvtTB.cs b/src/ARMeilleure/Decoders/OpCode32SimdCvtTB.cs index a95b32ab0..d3beb4bfd 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdCvtTB.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdCvtTB.cs @@ -15,8 +15,8 @@ namespace ARMeilleure.Decoders { IsThumb = isThumb; - Op = ((opCode >> 16) & 0x1) != 0; - T = ((opCode >> 7) & 0x1) != 0; + Op = ((opCode >> 16) & 0x1) != 0; + T = ((opCode >> 7) & 0x1) != 0; Size = ((opCode >> 8) & 0x1); RegisterSize = Size == 1 ? RegisterSize.Int64 : RegisterSize.Int32; @@ -41,4 +41,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCode32SimdLong.cs b/src/ARMeilleure/Decoders/OpCode32SimdLong.cs index 8d64d673a..558771a38 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdLong.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdLong.cs @@ -14,9 +14,15 @@ // The value must be a power of 2, otherwise it is the encoding of another instruction. switch (imm3h) { - case 1: Size = 0; break; - case 2: Size = 1; break; - case 4: Size = 2; break; + case 1: + Size = 0; + break; + case 2: + Size = 1; + break; + case 4: + Size = 2; + break; } U = ((opCode >> (isThumb ? 28 : 24)) & 0x1) != 0; diff --git a/src/ARMeilleure/Decoders/OpCode32SimdMemPair.cs b/src/ARMeilleure/Decoders/OpCode32SimdMemPair.cs index da88eed27..325be4ece 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdMemPair.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdMemPair.cs @@ -4,12 +4,12 @@ namespace ARMeilleure.Decoders { class OpCode32SimdMemPair : OpCode32, IOpCode32Simd { - private static int[] _regsMap = + private static readonly int[] _regsMap = { 1, 1, 4, 2, 1, 1, 3, 1, 1, 1, 2, 1, - 1, 1, 1, 1 + 1, 1, 1, 1, }; public int Vd { get; } diff --git a/src/ARMeilleure/Decoders/OpCode32SimdSel.cs b/src/ARMeilleure/Decoders/OpCode32SimdSel.cs index 37fd714a4..cb28418c3 100644 --- a/src/ARMeilleure/Decoders/OpCode32SimdSel.cs +++ b/src/ARMeilleure/Decoders/OpCode32SimdSel.cs @@ -13,11 +13,11 @@ } } - enum OpCode32SimdSelMode : int + enum OpCode32SimdSelMode { Eq = 0, Vs, Ge, - Gt + Gt, } } diff --git a/src/ARMeilleure/Decoders/OpCodeAdr.cs b/src/ARMeilleure/Decoders/OpCodeAdr.cs index 9655c766c..080280404 100644 --- a/src/ARMeilleure/Decoders/OpCodeAdr.cs +++ b/src/ARMeilleure/Decoders/OpCodeAdr.cs @@ -6,14 +6,14 @@ namespace ARMeilleure.Decoders public long Immediate { get; } - public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeAdr(inst, address, opCode); + public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeAdr(inst, address, opCode); public OpCodeAdr(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { Rd = opCode & 0x1f; - Immediate = DecoderHelper.DecodeImmS19_2(opCode); + Immediate = DecoderHelper.DecodeImmS19_2(opCode); Immediate |= ((long)opCode >> 29) & 3; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeAlu.cs b/src/ARMeilleure/Decoders/OpCodeAlu.cs index 4d7f03a71..1619ecd8e 100644 --- a/src/ARMeilleure/Decoders/OpCodeAlu.cs +++ b/src/ARMeilleure/Decoders/OpCodeAlu.cs @@ -11,8 +11,8 @@ namespace ARMeilleure.Decoders public OpCodeAlu(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rd = (opCode >> 0) & 0x1f; - Rn = (opCode >> 5) & 0x1f; + Rd = (opCode >> 0) & 0x1f; + Rn = (opCode >> 5) & 0x1f; DataOp = (DataOp)((opCode >> 24) & 0x3); RegisterSize = (opCode >> 31) != 0 @@ -20,4 +20,4 @@ namespace ARMeilleure.Decoders : RegisterSize.Int32; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeAluBinary.cs b/src/ARMeilleure/Decoders/OpCodeAluBinary.cs index e8b10656a..4413581ca 100644 --- a/src/ARMeilleure/Decoders/OpCodeAluBinary.cs +++ b/src/ARMeilleure/Decoders/OpCodeAluBinary.cs @@ -11,4 +11,4 @@ namespace ARMeilleure.Decoders Rm = (opCode >> 16) & 0x1f; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeAluImm.cs b/src/ARMeilleure/Decoders/OpCodeAluImm.cs index 91aa95531..0d2f7202f 100644 --- a/src/ARMeilleure/Decoders/OpCodeAluImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeAluImm.cs @@ -33,8 +33,8 @@ namespace ARMeilleure.Decoders } else { - throw new ArgumentException(nameof(opCode)); + throw new ArgumentException($"Invalid data operation: {DataOp}", nameof(opCode)); } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeAluRs.cs b/src/ARMeilleure/Decoders/OpCodeAluRs.cs index 949833363..47a47e7d0 100644 --- a/src/ARMeilleure/Decoders/OpCodeAluRs.cs +++ b/src/ARMeilleure/Decoders/OpCodeAluRs.cs @@ -3,7 +3,7 @@ namespace ARMeilleure.Decoders class OpCodeAluRs : OpCodeAlu, IOpCodeAluRs { public int Shift { get; } - public int Rm { get; } + public int Rm { get; } public ShiftType ShiftType { get; } @@ -22,8 +22,8 @@ namespace ARMeilleure.Decoders Shift = shift; - Rm = (opCode >> 16) & 0x1f; + Rm = (opCode >> 16) & 0x1f; ShiftType = (ShiftType)((opCode >> 22) & 0x3); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeAluRx.cs b/src/ARMeilleure/Decoders/OpCodeAluRx.cs index d39da9e74..c21486788 100644 --- a/src/ARMeilleure/Decoders/OpCodeAluRx.cs +++ b/src/ARMeilleure/Decoders/OpCodeAluRx.cs @@ -3,7 +3,7 @@ namespace ARMeilleure.Decoders class OpCodeAluRx : OpCodeAlu, IOpCodeAluRx { public int Shift { get; } - public int Rm { get; } + public int Rm { get; } public IntType IntType { get; } @@ -11,9 +11,9 @@ namespace ARMeilleure.Decoders public OpCodeAluRx(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Shift = (opCode >> 10) & 0x7; + Shift = (opCode >> 10) & 0x7; IntType = (IntType)((opCode >> 13) & 0x7); - Rm = (opCode >> 16) & 0x1f; + Rm = (opCode >> 16) & 0x1f; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBImm.cs b/src/ARMeilleure/Decoders/OpCodeBImm.cs index e302516e2..2848c1409 100644 --- a/src/ARMeilleure/Decoders/OpCodeBImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeBImm.cs @@ -8,4 +8,4 @@ namespace ARMeilleure.Decoders public OpCodeBImm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBImmAl.cs b/src/ARMeilleure/Decoders/OpCodeBImmAl.cs index 47ae5f562..6c4b28c6c 100644 --- a/src/ARMeilleure/Decoders/OpCodeBImmAl.cs +++ b/src/ARMeilleure/Decoders/OpCodeBImmAl.cs @@ -9,4 +9,4 @@ namespace ARMeilleure.Decoders Immediate = (long)address + DecoderHelper.DecodeImm26_2(opCode); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBImmCmp.cs b/src/ARMeilleure/Decoders/OpCodeBImmCmp.cs index a52465699..c477ddecf 100644 --- a/src/ARMeilleure/Decoders/OpCodeBImmCmp.cs +++ b/src/ARMeilleure/Decoders/OpCodeBImmCmp.cs @@ -17,4 +17,4 @@ namespace ARMeilleure.Decoders : RegisterSize.Int32; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBImmCond.cs b/src/ARMeilleure/Decoders/OpCodeBImmCond.cs index b57a7ea85..7a51a0720 100644 --- a/src/ARMeilleure/Decoders/OpCodeBImmCond.cs +++ b/src/ARMeilleure/Decoders/OpCodeBImmCond.cs @@ -22,4 +22,4 @@ namespace ARMeilleure.Decoders Immediate = (long)address + DecoderHelper.DecodeImmS19_2(opCode); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBImmTest.cs b/src/ARMeilleure/Decoders/OpCodeBImmTest.cs index bad984055..f989e59e4 100644 --- a/src/ARMeilleure/Decoders/OpCodeBImmTest.cs +++ b/src/ARMeilleure/Decoders/OpCodeBImmTest.cs @@ -2,7 +2,7 @@ namespace ARMeilleure.Decoders { class OpCodeBImmTest : OpCodeBImm { - public int Rt { get; } + public int Rt { get; } public int Bit { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeBImmTest(inst, address, opCode); @@ -13,8 +13,8 @@ namespace ARMeilleure.Decoders Immediate = (long)address + DecoderHelper.DecodeImmS14_2(opCode); - Bit = (opCode >> 19) & 0x1f; + Bit = (opCode >> 19) & 0x1f; Bit |= (opCode >> 26) & 0x20; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBReg.cs b/src/ARMeilleure/Decoders/OpCodeBReg.cs index b5dcbfd8e..3b84cf5c0 100644 --- a/src/ARMeilleure/Decoders/OpCodeBReg.cs +++ b/src/ARMeilleure/Decoders/OpCodeBReg.cs @@ -8,7 +8,7 @@ namespace ARMeilleure.Decoders public OpCodeBReg(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - int op4 = (opCode >> 0) & 0x1f; + int op4 = (opCode >> 0) & 0x1f; int op2 = (opCode >> 16) & 0x1f; if (op2 != 0b11111 || op4 != 0b00000) @@ -21,4 +21,4 @@ namespace ARMeilleure.Decoders Rn = (opCode >> 5) & 0x1f; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeBfm.cs b/src/ARMeilleure/Decoders/OpCodeBfm.cs index 8e1c78361..d51efade2 100644 --- a/src/ARMeilleure/Decoders/OpCodeBfm.cs +++ b/src/ARMeilleure/Decoders/OpCodeBfm.cs @@ -4,8 +4,8 @@ namespace ARMeilleure.Decoders { public long WMask { get; } public long TMask { get; } - public int Pos { get; } - public int Shift { get; } + public int Pos { get; } + public int Shift { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeBfm(inst, address, opCode); @@ -22,8 +22,8 @@ namespace ARMeilleure.Decoders WMask = bm.WMask; TMask = bm.TMask; - Pos = bm.Pos; + Pos = bm.Pos; Shift = bm.Shift; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeCcmp.cs b/src/ARMeilleure/Decoders/OpCodeCcmp.cs index aa47146f8..d40353486 100644 --- a/src/ARMeilleure/Decoders/OpCodeCcmp.cs +++ b/src/ARMeilleure/Decoders/OpCodeCcmp.cs @@ -4,7 +4,7 @@ namespace ARMeilleure.Decoders { class OpCodeCcmp : OpCodeAlu, IOpCodeCond { - public int Nzcv { get; } + public int Nzcv { get; } protected int RmImm; public Condition Cond { get; } @@ -22,11 +22,11 @@ namespace ARMeilleure.Decoders return; } - Nzcv = (opCode >> 0) & 0xf; - Cond = (Condition)((opCode >> 12) & 0xf); - RmImm = (opCode >> 16) & 0x1f; + Nzcv = (opCode >> 0) & 0xf; + Cond = (Condition)((opCode >> 12) & 0xf); + RmImm = (opCode >> 16) & 0x1f; Rd = RegisterAlias.Zr; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeCcmpImm.cs b/src/ARMeilleure/Decoders/OpCodeCcmpImm.cs index 3548f2da8..9d6acf196 100644 --- a/src/ARMeilleure/Decoders/OpCodeCcmpImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeCcmpImm.cs @@ -8,4 +8,4 @@ namespace ARMeilleure.Decoders public OpCodeCcmpImm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeCcmpReg.cs b/src/ARMeilleure/Decoders/OpCodeCcmpReg.cs index d5df3b102..349afa120 100644 --- a/src/ARMeilleure/Decoders/OpCodeCcmpReg.cs +++ b/src/ARMeilleure/Decoders/OpCodeCcmpReg.cs @@ -12,4 +12,4 @@ namespace ARMeilleure.Decoders public OpCodeCcmpReg(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeCsel.cs b/src/ARMeilleure/Decoders/OpCodeCsel.cs index 4b8dc7fdd..418962e08 100644 --- a/src/ARMeilleure/Decoders/OpCodeCsel.cs +++ b/src/ARMeilleure/Decoders/OpCodeCsel.cs @@ -10,8 +10,8 @@ namespace ARMeilleure.Decoders public OpCodeCsel(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rm = (opCode >> 16) & 0x1f; + Rm = (opCode >> 16) & 0x1f; Cond = (Condition)((opCode >> 12) & 0xf); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeException.cs b/src/ARMeilleure/Decoders/OpCodeException.cs index 6b72138ee..eee636405 100644 --- a/src/ARMeilleure/Decoders/OpCodeException.cs +++ b/src/ARMeilleure/Decoders/OpCodeException.cs @@ -11,4 +11,4 @@ namespace ARMeilleure.Decoders Id = (opCode >> 5) & 0xffff; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMem.cs b/src/ARMeilleure/Decoders/OpCodeMem.cs index 0ba2bcd18..9b4e5ff3e 100644 --- a/src/ARMeilleure/Decoders/OpCodeMem.cs +++ b/src/ARMeilleure/Decoders/OpCodeMem.cs @@ -2,18 +2,18 @@ namespace ARMeilleure.Decoders { class OpCodeMem : OpCode { - public int Rt { get; protected set; } - public int Rn { get; protected set; } - public int Size { get; protected set; } + public int Rt { get; protected set; } + public int Rn { get; protected set; } + public int Size { get; protected set; } public bool Extend64 { get; protected set; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeMem(inst, address, opCode); public OpCodeMem(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rt = (opCode >> 0) & 0x1f; - Rn = (opCode >> 5) & 0x1f; + Rt = (opCode >> 0) & 0x1f; + Rn = (opCode >> 5) & 0x1f; Size = (opCode >> 30) & 0x3; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMemEx.cs b/src/ARMeilleure/Decoders/OpCodeMemEx.cs index 899024853..1dc73140f 100644 --- a/src/ARMeilleure/Decoders/OpCodeMemEx.cs +++ b/src/ARMeilleure/Decoders/OpCodeMemEx.cs @@ -3,14 +3,14 @@ namespace ARMeilleure.Decoders class OpCodeMemEx : OpCodeMem { public int Rt2 { get; } - public int Rs { get; } + public int Rs { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeMemEx(inst, address, opCode); public OpCodeMemEx(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { Rt2 = (opCode >> 10) & 0x1f; - Rs = (opCode >> 16) & 0x1f; + Rs = (opCode >> 16) & 0x1f; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMemImm.cs b/src/ARMeilleure/Decoders/OpCodeMemImm.cs index d6ed2282f..4d5eeb1ed 100644 --- a/src/ARMeilleure/Decoders/OpCodeMemImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeMemImm.cs @@ -2,18 +2,18 @@ namespace ARMeilleure.Decoders { class OpCodeMemImm : OpCodeMem { - public long Immediate { get; protected set; } - public bool WBack { get; protected set; } - public bool PostIdx { get; protected set; } - protected bool Unscaled { get; } + public long Immediate { get; protected set; } + public bool WBack { get; protected set; } + public bool PostIdx { get; protected set; } + protected bool Unscaled { get; } private enum MemOp { - Unscaled = 0, - PostIndexed = 1, + Unscaled = 0, + PostIndexed = 1, Unprivileged = 2, - PreIndexed = 3, - Unsigned + PreIndexed = 3, + Unsigned, } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeMemImm(inst, address, opCode); @@ -21,13 +21,13 @@ namespace ARMeilleure.Decoders public OpCodeMemImm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { Extend64 = ((opCode >> 22) & 3) == 2; - WBack = ((opCode >> 24) & 1) == 0; + WBack = ((opCode >> 24) & 1) == 0; // The type is not valid for the Unsigned Immediate 12-bits encoding, // because the bits 11:10 are used for the larger Immediate offset. MemOp type = WBack ? (MemOp)((opCode >> 10) & 3) : MemOp.Unsigned; - PostIdx = type == MemOp.PostIndexed; + PostIdx = type == MemOp.PostIndexed; Unscaled = type == MemOp.Unscaled || type == MemOp.Unprivileged; @@ -50,4 +50,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMemLit.cs b/src/ARMeilleure/Decoders/OpCodeMemLit.cs index 986d66340..8712a78e3 100644 --- a/src/ARMeilleure/Decoders/OpCodeMemLit.cs +++ b/src/ARMeilleure/Decoders/OpCodeMemLit.cs @@ -2,11 +2,11 @@ namespace ARMeilleure.Decoders { class OpCodeMemLit : OpCode, IOpCodeLit { - public int Rt { get; } + public int Rt { get; } public long Immediate { get; } - public int Size { get; } - public bool Signed { get; } - public bool Prefetch { get; } + public int Size { get; } + public bool Signed { get; } + public bool Prefetch { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeMemLit(inst, address, opCode); @@ -18,11 +18,27 @@ namespace ARMeilleure.Decoders switch ((opCode >> 30) & 3) { - case 0: Size = 2; Signed = false; Prefetch = false; break; - case 1: Size = 3; Signed = false; Prefetch = false; break; - case 2: Size = 2; Signed = true; Prefetch = false; break; - case 3: Size = 0; Signed = false; Prefetch = true; break; + case 0: + Size = 2; + Signed = false; + Prefetch = false; + break; + case 1: + Size = 3; + Signed = false; + Prefetch = false; + break; + case 2: + Size = 2; + Signed = true; + Prefetch = false; + break; + case 3: + Size = 0; + Signed = false; + Prefetch = true; + break; } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMemPair.cs b/src/ARMeilleure/Decoders/OpCodeMemPair.cs index 21018033d..eb696cfeb 100644 --- a/src/ARMeilleure/Decoders/OpCodeMemPair.cs +++ b/src/ARMeilleure/Decoders/OpCodeMemPair.cs @@ -8,11 +8,11 @@ namespace ARMeilleure.Decoders public OpCodeMemPair(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rt2 = (opCode >> 10) & 0x1f; - WBack = ((opCode >> 23) & 0x1) != 0; - PostIdx = ((opCode >> 23) & 0x3) == 1; + Rt2 = (opCode >> 10) & 0x1f; + WBack = ((opCode >> 23) & 0x1) != 0; + PostIdx = ((opCode >> 23) & 0x3) == 1; Extend64 = ((opCode >> 30) & 0x3) == 1; - Size = ((opCode >> 31) & 0x1) | 2; + Size = ((opCode >> 31) & 0x1) | 2; DecodeImm(opCode); } @@ -22,4 +22,4 @@ namespace ARMeilleure.Decoders Immediate = ((long)(opCode >> 15) << 57) >> (57 - Size); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMemReg.cs b/src/ARMeilleure/Decoders/OpCodeMemReg.cs index 73d6c5d2c..9b0d15959 100644 --- a/src/ARMeilleure/Decoders/OpCodeMemReg.cs +++ b/src/ARMeilleure/Decoders/OpCodeMemReg.cs @@ -3,7 +3,7 @@ namespace ARMeilleure.Decoders class OpCodeMemReg : OpCodeMem { public bool Shift { get; } - public int Rm { get; } + public int Rm { get; } public IntType IntType { get; } @@ -11,10 +11,10 @@ namespace ARMeilleure.Decoders public OpCodeMemReg(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Shift = ((opCode >> 12) & 0x1) != 0; - IntType = (IntType)((opCode >> 13) & 0x7); - Rm = (opCode >> 16) & 0x1f; - Extend64 = ((opCode >> 22) & 0x3) == 2; + Shift = ((opCode >> 12) & 0x1) != 0; + IntType = (IntType)((opCode >> 13) & 0x7); + Rm = (opCode >> 16) & 0x1f; + Extend64 = ((opCode >> 22) & 0x3) == 2; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMov.cs b/src/ARMeilleure/Decoders/OpCodeMov.cs index 50af88cb9..a2914b71c 100644 --- a/src/ARMeilleure/Decoders/OpCodeMov.cs +++ b/src/ARMeilleure/Decoders/OpCodeMov.cs @@ -22,9 +22,9 @@ namespace ARMeilleure.Decoders return; } - Rd = (opCode >> 0) & 0x1f; - Immediate = (opCode >> 5) & 0xffff; - Bit = (opCode >> 21) & 0x3; + Rd = (opCode >> 0) & 0x1f; + Immediate = (opCode >> 5) & 0xffff; + Bit = (opCode >> 21) & 0x3; Bit <<= 4; @@ -35,4 +35,4 @@ namespace ARMeilleure.Decoders : RegisterSize.Int32; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeMul.cs b/src/ARMeilleure/Decoders/OpCodeMul.cs index 31d140a65..9b1dd37b8 100644 --- a/src/ARMeilleure/Decoders/OpCodeMul.cs +++ b/src/ARMeilleure/Decoders/OpCodeMul.cs @@ -13,4 +13,4 @@ namespace ARMeilleure.Decoders Rm = (opCode >> 16) & 0x1f; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimd.cs b/src/ARMeilleure/Decoders/OpCodeSimd.cs index 85713690a..bd34d74d9 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimd.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimd.cs @@ -2,18 +2,18 @@ namespace ARMeilleure.Decoders { class OpCodeSimd : OpCode, IOpCodeSimd { - public int Rd { get; } - public int Rn { get; } - public int Opc { get; } + public int Rd { get; } + public int Rn { get; } + public int Opc { get; } public int Size { get; protected set; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimd(inst, address, opCode); public OpCodeSimd(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rd = (opCode >> 0) & 0x1f; - Rn = (opCode >> 5) & 0x1f; - Opc = (opCode >> 15) & 0x3; + Rd = (opCode >> 0) & 0x1f; + Rn = (opCode >> 5) & 0x1f; + Opc = (opCode >> 15) & 0x3; Size = (opCode >> 22) & 0x3; RegisterSize = ((opCode >> 30) & 1) != 0 @@ -21,4 +21,4 @@ namespace ARMeilleure.Decoders : RegisterSize.Simd64; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdCvt.cs b/src/ARMeilleure/Decoders/OpCodeSimdCvt.cs index 05b32941a..e50cf12e6 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdCvt.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdCvt.cs @@ -9,7 +9,7 @@ namespace ARMeilleure.Decoders public OpCodeSimdCvt(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { int scale = (opCode >> 10) & 0x3f; - int sf = (opCode >> 31) & 0x1; + int sf = (opCode >> 31) & 0x1; FBits = 64 - scale; @@ -18,4 +18,4 @@ namespace ARMeilleure.Decoders : RegisterSize.Int32; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdExt.cs b/src/ARMeilleure/Decoders/OpCodeSimdExt.cs index a0e264d9d..0a3359e13 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdExt.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdExt.cs @@ -11,4 +11,4 @@ namespace ARMeilleure.Decoders Imm4 = (opCode >> 11) & 0xf; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdFcond.cs b/src/ARMeilleure/Decoders/OpCodeSimdFcond.cs index aa16e0c19..510cd3101 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdFcond.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdFcond.cs @@ -10,7 +10,7 @@ namespace ARMeilleure.Decoders public OpCodeSimdFcond(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Nzcv = (opCode >> 0) & 0xf; + Nzcv = (opCode >> 0) & 0xf; Cond = (Condition)((opCode >> 12) & 0xf); } } diff --git a/src/ARMeilleure/Decoders/OpCodeSimdFmov.cs b/src/ARMeilleure/Decoders/OpCodeSimdFmov.cs index 9f9062b8d..662abe284 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdFmov.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdFmov.cs @@ -2,9 +2,9 @@ namespace ARMeilleure.Decoders { class OpCodeSimdFmov : OpCode, IOpCodeSimd { - public int Rd { get; } + public int Rd { get; } public long Immediate { get; } - public int Size { get; } + public int Size { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimdFmov(inst, address, opCode); @@ -16,7 +16,7 @@ namespace ARMeilleure.Decoders long imm; - Rd = (opCode >> 0) & 0x1f; + Rd = (opCode >> 0) & 0x1f; imm = (opCode >> 13) & 0xff; if (type == 0) @@ -29,4 +29,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdHelper.cs b/src/ARMeilleure/Decoders/OpCodeSimdHelper.cs index 02f74d030..d900ed9ba 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdHelper.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdHelper.cs @@ -52,17 +52,20 @@ else if ((modeHigh & 0b110) == 0b100) { // 16-bits shifted Immediate. - size = 1; imm <<= (modeHigh & 1) << 3; + size = 1; + imm <<= (modeHigh & 1) << 3; } else if ((modeHigh & 0b100) == 0b000) { // 32-bits shifted Immediate. - size = 2; imm <<= modeHigh << 3; + size = 2; + imm <<= modeHigh << 3; } else if ((modeHigh & 0b111) == 0b110) { // 32-bits shifted Immediate (fill with ones). - size = 2; imm = ShlOnes(imm, 8 << modeLow); + size = 2; + imm = ShlOnes(imm, 8 << modeLow); } else { diff --git a/src/ARMeilleure/Decoders/OpCodeSimdImm.cs b/src/ARMeilleure/Decoders/OpCodeSimdImm.cs index eeca77096..3f4bad7f7 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdImm.cs @@ -2,9 +2,9 @@ namespace ARMeilleure.Decoders { class OpCodeSimdImm : OpCode, IOpCodeSimd { - public int Rd { get; } + public int Rd { get; } public long Immediate { get; } - public int Size { get; } + public int Size { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimdImm(inst, address, opCode); @@ -13,14 +13,14 @@ namespace ARMeilleure.Decoders Rd = opCode & 0x1f; int cMode = (opCode >> 12) & 0xf; - int op = (opCode >> 29) & 0x1; + int op = (opCode >> 29) & 0x1; - int modeLow = cMode & 1; + int modeLow = cMode & 1; int modeHigh = cMode >> 1; long imm; - imm = ((uint)opCode >> 5) & 0x1f; + imm = ((uint)opCode >> 5) & 0x1f; imm |= ((uint)opCode >> 11) & 0xe0; if (modeHigh == 0b111) @@ -67,17 +67,20 @@ namespace ARMeilleure.Decoders else if ((modeHigh & 0b110) == 0b100) { // 16-bits shifted Immediate. - Size = 1; imm <<= (modeHigh & 1) << 3; + Size = 1; + imm <<= (modeHigh & 1) << 3; } else if ((modeHigh & 0b100) == 0b000) { // 32-bits shifted Immediate. - Size = 2; imm <<= modeHigh << 3; + Size = 2; + imm <<= modeHigh << 3; } else if ((modeHigh & 0b111) == 0b110) { // 32-bits shifted Immediate (fill with ones). - Size = 2; imm = ShlOnes(imm, 8 << modeLow); + Size = 2; + imm = ShlOnes(imm, 8 << modeLow); } else { @@ -104,4 +107,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdIns.cs b/src/ARMeilleure/Decoders/OpCodeSimdIns.cs index f6f9249d1..95436879c 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdIns.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdIns.cs @@ -23,14 +23,22 @@ namespace ARMeilleure.Decoders switch (Size) { - case 1: Size = 0; break; - case 2: Size = 1; break; - case 4: Size = 2; break; - case 8: Size = 3; break; + case 1: + Size = 0; + break; + case 2: + Size = 1; + break; + case 4: + Size = 2; + break; + case 8: + Size = 3; + break; } - SrcIndex = imm4 >> Size; + SrcIndex = imm4 >> Size; DstIndex = imm5 >> (Size + 1); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdMemImm.cs b/src/ARMeilleure/Decoders/OpCodeSimdMemImm.cs index c11594cb0..14a9d7c9c 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdMemImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdMemImm.cs @@ -25,4 +25,4 @@ namespace ARMeilleure.Decoders Extend64 = false; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdMemLit.cs b/src/ARMeilleure/Decoders/OpCodeSimdMemLit.cs index 8e2129661..efa558bf9 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdMemLit.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdMemLit.cs @@ -2,10 +2,10 @@ namespace ARMeilleure.Decoders { class OpCodeSimdMemLit : OpCode, IOpCodeSimd, IOpCodeLit { - public int Rt { get; } + public int Rt { get; } public long Immediate { get; } - public int Size { get; } - public bool Signed => false; + public int Size { get; } + public bool Signed => false; public bool Prefetch => false; public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimdMemLit(inst, address, opCode); @@ -28,4 +28,4 @@ namespace ARMeilleure.Decoders Size = opc + 2; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdMemMs.cs b/src/ARMeilleure/Decoders/OpCodeSimdMemMs.cs index 8922c18f6..c05b52494 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdMemMs.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdMemMs.cs @@ -2,10 +2,10 @@ namespace ARMeilleure.Decoders { class OpCodeSimdMemMs : OpCodeMemReg, IOpCodeSimd { - public int Reps { get; } - public int SElems { get; } - public int Elems { get; } - public bool WBack { get; } + public int Reps { get; } + public int SElems { get; } + public int Elems { get; } + public bool WBack { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimdMemMs(inst, address, opCode); @@ -13,18 +13,41 @@ namespace ARMeilleure.Decoders { switch ((opCode >> 12) & 0xf) { - case 0b0000: Reps = 1; SElems = 4; break; - case 0b0010: Reps = 4; SElems = 1; break; - case 0b0100: Reps = 1; SElems = 3; break; - case 0b0110: Reps = 3; SElems = 1; break; - case 0b0111: Reps = 1; SElems = 1; break; - case 0b1000: Reps = 1; SElems = 2; break; - case 0b1010: Reps = 2; SElems = 1; break; + case 0b0000: + Reps = 1; + SElems = 4; + break; + case 0b0010: + Reps = 4; + SElems = 1; + break; + case 0b0100: + Reps = 1; + SElems = 3; + break; + case 0b0110: + Reps = 3; + SElems = 1; + break; + case 0b0111: + Reps = 1; + SElems = 1; + break; + case 0b1000: + Reps = 1; + SElems = 2; + break; + case 0b1010: + Reps = 2; + SElems = 1; + break; - default: Instruction = InstDescriptor.Undefined; return; + default: + Instruction = InstDescriptor.Undefined; + return; } - Size = (opCode >> 10) & 3; + Size = (opCode >> 10) & 3; WBack = ((opCode >> 23) & 1) != 0; bool q = ((opCode >> 30) & 1) != 0; @@ -45,4 +68,4 @@ namespace ARMeilleure.Decoders Elems = (GetBitsCount() >> 3) >> Size; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdMemPair.cs b/src/ARMeilleure/Decoders/OpCodeSimdMemPair.cs index 1ab953679..697163896 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdMemPair.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdMemPair.cs @@ -13,4 +13,4 @@ namespace ARMeilleure.Decoders DecodeImm(opCode); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdMemReg.cs b/src/ARMeilleure/Decoders/OpCodeSimdMemReg.cs index 9ea6dda37..be7b25b9d 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdMemReg.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdMemReg.cs @@ -18,4 +18,4 @@ namespace ARMeilleure.Decoders Extend64 = false; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdMemSs.cs b/src/ARMeilleure/Decoders/OpCodeSimdMemSs.cs index 44abdd389..5bc614e19 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdMemSs.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdMemSs.cs @@ -2,21 +2,21 @@ namespace ARMeilleure.Decoders { class OpCodeSimdMemSs : OpCodeMemReg, IOpCodeSimd { - public int SElems { get; } - public int Index { get; } + public int SElems { get; } + public int Index { get; } public bool Replicate { get; } - public bool WBack { get; } + public bool WBack { get; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimdMemSs(inst, address, opCode); public OpCodeSimdMemSs(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - int size = (opCode >> 10) & 3; - int s = (opCode >> 12) & 1; + int size = (opCode >> 10) & 3; + int s = (opCode >> 12) & 1; int sElems = (opCode >> 12) & 2; - int scale = (opCode >> 14) & 3; - int l = (opCode >> 22) & 1; - int q = (opCode >> 30) & 1; + int scale = (opCode >> 14) & 3; + int l = (opCode >> 22) & 1; + int q = (opCode >> 30) & 1; sElems |= (opCode >> 21) & 1; @@ -27,63 +27,63 @@ namespace ARMeilleure.Decoders switch (scale) { case 1: - { - if ((size & 1) != 0) { - Instruction = InstDescriptor.Undefined; + if ((size & 1) != 0) + { + Instruction = InstDescriptor.Undefined; - return; + return; + } + + index >>= 1; + + break; } - index >>= 1; - - break; - } - case 2: - { - if ((size & 2) != 0 || - ((size & 1) != 0 && s != 0)) { - Instruction = InstDescriptor.Undefined; + if ((size & 2) != 0 || + ((size & 1) != 0 && s != 0)) + { + Instruction = InstDescriptor.Undefined; - return; + return; + } + + if ((size & 1) != 0) + { + index >>= 3; + + scale = 3; + } + else + { + index >>= 2; + } + + break; } - if ((size & 1) != 0) - { - index >>= 3; - - scale = 3; - } - else - { - index >>= 2; - } - - break; - } - case 3: - { - if (l == 0 || s != 0) { - Instruction = InstDescriptor.Undefined; + if (l == 0 || s != 0) + { + Instruction = InstDescriptor.Undefined; - return; + return; + } + + scale = size; + + Replicate = true; + + break; } - - scale = size; - - Replicate = true; - - break; - } } - Index = index; + Index = index; SElems = sElems; - Size = scale; + Size = scale; Extend64 = false; @@ -94,4 +94,4 @@ namespace ARMeilleure.Decoders : RegisterSize.Simd64; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdReg.cs b/src/ARMeilleure/Decoders/OpCodeSimdReg.cs index ac4f71dae..40f9b1c53 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdReg.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdReg.cs @@ -3,16 +3,16 @@ namespace ARMeilleure.Decoders class OpCodeSimdReg : OpCodeSimd { public bool Bit3 { get; } - public int Ra { get; } - public int Rm { get; protected set; } + public int Ra { get; } + public int Rm { get; protected set; } public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeSimdReg(inst, address, opCode); public OpCodeSimdReg(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Bit3 = ((opCode >> 3) & 0x1) != 0; - Ra = (opCode >> 10) & 0x1f; - Rm = (opCode >> 16) & 0x1f; + Bit3 = ((opCode >> 3) & 0x1) != 0; + Ra = (opCode >> 10) & 0x1f; + Rm = (opCode >> 16) & 0x1f; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdRegElem.cs b/src/ARMeilleure/Decoders/OpCodeSimdRegElem.cs index 92368deea..bb248ab6b 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdRegElem.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdRegElem.cs @@ -12,7 +12,7 @@ namespace ARMeilleure.Decoders { case 1: Index = (opCode >> 20) & 3 | - (opCode >> 9) & 4; + (opCode >> 9) & 4; Rm &= 0xf; @@ -24,8 +24,10 @@ namespace ARMeilleure.Decoders break; - default: Instruction = InstDescriptor.Undefined; break; + default: + Instruction = InstDescriptor.Undefined; + break; } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSimdRegElemF.cs b/src/ARMeilleure/Decoders/OpCodeSimdRegElemF.cs index d46dd57ed..c97bd787e 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdRegElemF.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdRegElemF.cs @@ -26,7 +26,9 @@ namespace ARMeilleure.Decoders break; - default: Instruction = InstDescriptor.Undefined; break; + default: + Instruction = InstDescriptor.Undefined; + break; } } } diff --git a/src/ARMeilleure/Decoders/OpCodeSimdTbl.cs b/src/ARMeilleure/Decoders/OpCodeSimdTbl.cs index 9c631e485..3a7ef6aba 100644 --- a/src/ARMeilleure/Decoders/OpCodeSimdTbl.cs +++ b/src/ARMeilleure/Decoders/OpCodeSimdTbl.cs @@ -9,4 +9,4 @@ namespace ARMeilleure.Decoders Size = ((opCode >> 13) & 3) + 1; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeSystem.cs b/src/ARMeilleure/Decoders/OpCodeSystem.cs index 4d79421a8..215134153 100644 --- a/src/ARMeilleure/Decoders/OpCodeSystem.cs +++ b/src/ARMeilleure/Decoders/OpCodeSystem.cs @@ -2,7 +2,7 @@ namespace ARMeilleure.Decoders { class OpCodeSystem : OpCode { - public int Rt { get; } + public int Rt { get; } public int Op2 { get; } public int CRm { get; } public int CRn { get; } @@ -13,12 +13,12 @@ namespace ARMeilleure.Decoders public OpCodeSystem(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rt = (opCode >> 0) & 0x1f; - Op2 = (opCode >> 5) & 0x7; - CRm = (opCode >> 8) & 0xf; - CRn = (opCode >> 12) & 0xf; - Op1 = (opCode >> 16) & 0x7; + Rt = (opCode >> 0) & 0x1f; + Op2 = (opCode >> 5) & 0x7; + CRm = (opCode >> 8) & 0xf; + CRn = (opCode >> 12) & 0xf; + Op1 = (opCode >> 16) & 0x7; Op0 = ((opCode >> 19) & 0x1) | 2; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT16.cs b/src/ARMeilleure/Decoders/OpCodeT16.cs index 9c3d6b006..de946b961 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16.cs @@ -12,4 +12,4 @@ namespace ARMeilleure.Decoders OpCodeSizeInBytes = 2; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT16AddSubImm3.cs b/src/ARMeilleure/Decoders/OpCodeT16AddSubImm3.cs index 95f180548..cefb50e4a 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16AddSubImm3.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16AddSubImm3.cs @@ -1,6 +1,6 @@ namespace ARMeilleure.Decoders { - class OpCodeT16AddSubImm3: OpCodeT16, IOpCode32AluImm + class OpCodeT16AddSubImm3 : OpCodeT16, IOpCode32AluImm { public int Rd { get; } public int Rn { get; } @@ -15,8 +15,8 @@ public OpCodeT16AddSubImm3(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rd = (opCode >> 0) & 0x7; - Rn = (opCode >> 3) & 0x7; + Rd = (opCode >> 0) & 0x7; + Rn = (opCode >> 3) & 0x7; Immediate = (opCode >> 6) & 0x7; IsRotated = false; } diff --git a/src/ARMeilleure/Decoders/OpCodeT16BImm11.cs b/src/ARMeilleure/Decoders/OpCodeT16BImm11.cs index f230b20e2..fab098a8f 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16BImm11.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16BImm11.cs @@ -8,7 +8,7 @@ public OpCodeT16BImm11(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - int imm = (opCode << 21) >> 20; + int imm = (opCode << 21) >> 20; Immediate = GetPc() + imm; } } diff --git a/src/ARMeilleure/Decoders/OpCodeT16BImm8.cs b/src/ARMeilleure/Decoders/OpCodeT16BImm8.cs index 5f6842983..edfa86ba5 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16BImm8.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16BImm8.cs @@ -10,7 +10,7 @@ { Cond = (Condition)((opCode >> 8) & 0xf); - int imm = (opCode << 24) >> 23; + int imm = (opCode << 24) >> 23; Immediate = GetPc() + imm; } } diff --git a/src/ARMeilleure/Decoders/OpCodeT16MemImm5.cs b/src/ARMeilleure/Decoders/OpCodeT16MemImm5.cs index 20ef31e27..873c63b93 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16MemImm5.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16MemImm5.cs @@ -36,23 +36,13 @@ namespace ARMeilleure.Decoders break; } - switch (inst.Name) + Immediate = inst.Name switch { - case InstName.Str: - case InstName.Ldr: - Immediate = ((opCode >> 6) & 0x1f) << 2; - break; - case InstName.Strb: - case InstName.Ldrb: - Immediate = ((opCode >> 6) & 0x1f); - break; - case InstName.Strh: - case InstName.Ldrh: - Immediate = ((opCode >> 6) & 0x1f) << 1; - break; - default: - throw new InvalidOperationException(); - } + InstName.Str or InstName.Ldr => ((opCode >> 6) & 0x1f) << 2, + InstName.Strb or InstName.Ldrb => ((opCode >> 6) & 0x1f), + InstName.Strh or InstName.Ldrh => ((opCode >> 6) & 0x1f) << 1, + _ => throw new InvalidOperationException(), + }; } } } diff --git a/src/ARMeilleure/Decoders/OpCodeT16MemMult.cs b/src/ARMeilleure/Decoders/OpCodeT16MemMult.cs index f4185cfcb..3f3057acd 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16MemMult.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16MemMult.cs @@ -27,7 +27,7 @@ namespace ARMeilleure.Decoders { InstName.Ldm => true, InstName.Stm => false, - _ => throw new InvalidOperationException() + _ => throw new InvalidOperationException(), }; } } diff --git a/src/ARMeilleure/Decoders/OpCodeT16ShiftImm.cs b/src/ARMeilleure/Decoders/OpCodeT16ShiftImm.cs index a540026ec..8f35e4391 100644 --- a/src/ARMeilleure/Decoders/OpCodeT16ShiftImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeT16ShiftImm.cs @@ -15,8 +15,8 @@ public OpCodeT16ShiftImm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rd = (opCode >> 0) & 0x7; - Rm = (opCode >> 3) & 0x7; + Rd = (opCode >> 0) & 0x7; + Rm = (opCode >> 3) & 0x7; Immediate = (opCode >> 6) & 0x1F; ShiftType = (ShiftType)((opCode >> 11) & 3); } diff --git a/src/ARMeilleure/Decoders/OpCodeT32.cs b/src/ARMeilleure/Decoders/OpCodeT32.cs index cf43d4298..5ccbd6a27 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32.cs @@ -12,4 +12,4 @@ OpCodeSizeInBytes = 4; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32Alu.cs b/src/ARMeilleure/Decoders/OpCodeT32Alu.cs index a81b3b3dc..1f92f7558 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32Alu.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32Alu.cs @@ -17,4 +17,4 @@ SetFlags = ((opCode >> 20) & 1) != 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32AluImm.cs b/src/ARMeilleure/Decoders/OpCodeT32AluImm.cs index 0895c29b4..863d14bda 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32AluImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32AluImm.cs @@ -35,4 +35,4 @@ namespace ARMeilleure.Decoders } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32AluImm12.cs b/src/ARMeilleure/Decoders/OpCodeT32AluImm12.cs index 31de63dd3..12b65a100 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32AluImm12.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32AluImm12.cs @@ -13,4 +13,4 @@ namespace ARMeilleure.Decoders Immediate = (opCode & 0xff) | ((opCode >> 4) & 0x700) | ((opCode >> 15) & 0x800); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32AluReg.cs b/src/ARMeilleure/Decoders/OpCodeT32AluReg.cs index a487f55a6..4ac983470 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32AluReg.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32AluReg.cs @@ -11,4 +11,4 @@ namespace ARMeilleure.Decoders Rm = (opCode >> 0) & 0xf; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32AluRsImm.cs b/src/ARMeilleure/Decoders/OpCodeT32AluRsImm.cs index 1c9ba7a2c..edf0298df 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32AluRsImm.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32AluRsImm.cs @@ -2,7 +2,7 @@ { class OpCodeT32AluRsImm : OpCodeT32Alu, IOpCode32AluRsImm { - public int Rm { get; } + public int Rm { get; } public int Immediate { get; } public ShiftType ShiftType { get; } @@ -11,10 +11,10 @@ public OpCodeT32AluRsImm(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { - Rm = (opCode >> 0) & 0xf; + Rm = (opCode >> 0) & 0xf; Immediate = ((opCode >> 6) & 3) | ((opCode >> 10) & 0x1c); ShiftType = (ShiftType)((opCode >> 4) & 3); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32BImm20.cs b/src/ARMeilleure/Decoders/OpCodeT32BImm20.cs index b6da8abdb..13256ee54 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32BImm20.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32BImm20.cs @@ -24,4 +24,4 @@ Cond = (Condition)((opCode >> 22) & 0xf); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32BImm24.cs b/src/ARMeilleure/Decoders/OpCodeT32BImm24.cs index 774ec3a64..d7c606619 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32BImm24.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32BImm24.cs @@ -32,4 +32,4 @@ namespace ARMeilleure.Decoders Immediate = pc + imm32; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32MemImm12.cs b/src/ARMeilleure/Decoders/OpCodeT32MemImm12.cs index 7838604b2..4977cdf50 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32MemImm12.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32MemImm12.cs @@ -22,4 +22,4 @@ IsLoad = ((opCode >> 20) & 1) != 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32MemImm8.cs b/src/ARMeilleure/Decoders/OpCodeT32MemImm8.cs index d8b7763cb..f84e41400 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32MemImm8.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32MemImm8.cs @@ -18,7 +18,7 @@ Rn = (opCode >> 16) & 0xf; Index = ((opCode >> 10) & 1) != 0; - Add = ((opCode >> 9) & 1) != 0; + Add = ((opCode >> 9) & 1) != 0; WBack = ((opCode >> 8) & 1) != 0; Immediate = opCode & 0xff; @@ -26,4 +26,4 @@ IsLoad = ((opCode >> 20) & 1) != 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32MemImm8D.cs b/src/ARMeilleure/Decoders/OpCodeT32MemImm8D.cs index 7a078c489..51f5042f2 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32MemImm8D.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32MemImm8D.cs @@ -20,7 +20,7 @@ namespace ARMeilleure.Decoders Rn = (opCode >> 16) & 0xf; Index = ((opCode >> 24) & 1) != 0; - Add = ((opCode >> 23) & 1) != 0; + Add = ((opCode >> 23) & 1) != 0; WBack = ((opCode >> 21) & 1) != 0; Immediate = (opCode & 0xff) << 2; @@ -28,4 +28,4 @@ namespace ARMeilleure.Decoders IsLoad = ((opCode >> 20) & 1) != 0; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32MemMult.cs b/src/ARMeilleure/Decoders/OpCodeT32MemMult.cs index a9ba306dc..d155842a6 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32MemMult.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32MemMult.cs @@ -7,8 +7,8 @@ namespace ARMeilleure.Decoders public int Rn { get; } public int RegisterMask { get; } - public int Offset { get; } - public int PostOffset { get; } + public int Offset { get; } + public int PostOffset { get; } public bool IsLoad { get; } @@ -19,9 +19,9 @@ namespace ARMeilleure.Decoders Rn = (opCode >> 16) & 0xf; bool isLoad = (opCode & (1 << 20)) != 0; - bool w = (opCode & (1 << 21)) != 0; - bool u = (opCode & (1 << 23)) != 0; - bool p = (opCode & (1 << 24)) != 0; + bool w = (opCode & (1 << 21)) != 0; + bool u = (opCode & (1 << 23)) != 0; + bool p = (opCode & (1 << 24)) != 0; RegisterMask = opCode & 0xffff; @@ -49,4 +49,4 @@ namespace ARMeilleure.Decoders IsLoad = isLoad; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32MovImm16.cs b/src/ARMeilleure/Decoders/OpCodeT32MovImm16.cs index 5161892bb..2f871c740 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32MovImm16.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32MovImm16.cs @@ -4,8 +4,6 @@ namespace ARMeilleure.Decoders { public int Immediate { get; } - public bool IsRotated => false; - public new static OpCode Create(InstDescriptor inst, ulong address, int opCode) => new OpCodeT32MovImm16(inst, address, opCode); public OpCodeT32MovImm16(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) @@ -13,4 +11,4 @@ namespace ARMeilleure.Decoders Immediate = (opCode & 0xff) | ((opCode >> 4) & 0x700) | ((opCode >> 15) & 0x800) | ((opCode >> 4) & 0xf000); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeT32Tb.cs b/src/ARMeilleure/Decoders/OpCodeT32Tb.cs index 527754b1f..0a4d2a6c4 100644 --- a/src/ARMeilleure/Decoders/OpCodeT32Tb.cs +++ b/src/ARMeilleure/Decoders/OpCodeT32Tb.cs @@ -13,4 +13,4 @@ namespace ARMeilleure.Decoders Rn = (opCode >> 16) & 0xf; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/OpCodeTable.cs b/src/ARMeilleure/Decoders/OpCodeTable.cs index 4f3599583..9e13bd9b5 100644 --- a/src/ARMeilleure/Decoders/OpCodeTable.cs +++ b/src/ARMeilleure/Decoders/OpCodeTable.cs @@ -13,7 +13,7 @@ namespace ARMeilleure.Decoders private readonly struct InstInfo { - public int Mask { get; } + public int Mask { get; } public int Value { get; } public InstDescriptor Inst { get; } @@ -22,24 +22,25 @@ namespace ARMeilleure.Decoders public InstInfo(int mask, int value, InstDescriptor inst, MakeOp makeOp) { - Mask = mask; - Value = value; - Inst = inst; + Mask = mask; + Value = value; + Inst = inst; MakeOp = makeOp; } } - private static List AllInstA32 = new(); - private static List AllInstT32 = new(); - private static List AllInstA64 = new(); + private static readonly List _allInstA32 = new(); + private static readonly List _allInstT32 = new(); + private static readonly List _allInstA64 = new(); - private static InstInfo[][] InstA32FastLookup = new InstInfo[FastLookupSize][]; - private static InstInfo[][] InstT32FastLookup = new InstInfo[FastLookupSize][]; - private static InstInfo[][] InstA64FastLookup = new InstInfo[FastLookupSize][]; + private static readonly InstInfo[][] _instA32FastLookup = new InstInfo[FastLookupSize][]; + private static readonly InstInfo[][] _instT32FastLookup = new InstInfo[FastLookupSize][]; + private static readonly InstInfo[][] _instA64FastLookup = new InstInfo[FastLookupSize][]; static OpCodeTable() { -#region "OpCode Table (AArch64)" +#pragma warning disable IDE0055 // Disable formatting + #region "OpCode Table (AArch64)" // Base SetA64("x0011010000xxxxx000000xxxxxxxxxx", InstName.Adc, InstEmit.Adc, OpCodeAluRs.Create); SetA64("x0111010000xxxxx000000xxxxxxxxxx", InstName.Adcs, InstEmit.Adcs, OpCodeAluRs.Create); @@ -329,6 +330,7 @@ namespace ARMeilleure.Decoders SetA64("011111100x110000110010xxxxxxxxxx", InstName.Fmaxnmp_S, InstEmit.Fmaxnmp_S, OpCodeSimd.Create); SetA64("0>1011100<1xxxxx110001xxxxxxxxxx", InstName.Fmaxnmp_V, InstEmit.Fmaxnmp_V, OpCodeSimdReg.Create); SetA64("0110111000110000110010xxxxxxxxxx", InstName.Fmaxnmv_V, InstEmit.Fmaxnmv_V, OpCodeSimd.Create); + SetA64("011111100x110000111110xxxxxxxxxx", InstName.Fmaxp_S, InstEmit.Fmaxp_S, OpCodeSimd.Create); SetA64("0>1011100<1xxxxx111101xxxxxxxxxx", InstName.Fmaxp_V, InstEmit.Fmaxp_V, OpCodeSimdReg.Create); SetA64("0110111000110000111110xxxxxxxxxx", InstName.Fmaxv_V, InstEmit.Fmaxv_V, OpCodeSimd.Create); SetA64("000111100x1xxxxx010110xxxxxxxxxx", InstName.Fmin_S, InstEmit.Fmin_S, OpCodeSimdReg.Create); @@ -338,6 +340,7 @@ namespace ARMeilleure.Decoders SetA64("011111101x110000110010xxxxxxxxxx", InstName.Fminnmp_S, InstEmit.Fminnmp_S, OpCodeSimd.Create); SetA64("0>1011101<1xxxxx110001xxxxxxxxxx", InstName.Fminnmp_V, InstEmit.Fminnmp_V, OpCodeSimdReg.Create); SetA64("0110111010110000110010xxxxxxxxxx", InstName.Fminnmv_V, InstEmit.Fminnmv_V, OpCodeSimd.Create); + SetA64("011111101x110000111110xxxxxxxxxx", InstName.Fminp_S, InstEmit.Fminp_S, OpCodeSimd.Create); SetA64("0>1011101<1xxxxx111101xxxxxxxxxx", InstName.Fminp_V, InstEmit.Fminp_V, OpCodeSimdReg.Create); SetA64("0110111010110000111110xxxxxxxxxx", InstName.Fminv_V, InstEmit.Fminv_V, OpCodeSimd.Create); SetA64("010111111xxxxxxx0001x0xxxxxxxxxx", InstName.Fmla_Se, InstEmit.Fmla_Se, OpCodeSimdRegElemF.Create); @@ -638,9 +641,9 @@ namespace ARMeilleure.Decoders SetA64("0x001110<<100001001010xxxxxxxxxx", InstName.Xtn_V, InstEmit.Xtn_V, OpCodeSimd.Create); SetA64("0>001110<<0xxxxx001110xxxxxxxxxx", InstName.Zip1_V, InstEmit.Zip1_V, OpCodeSimdReg.Create); SetA64("0>001110<<0xxxxx011110xxxxxxxxxx", InstName.Zip2_V, InstEmit.Zip2_V, OpCodeSimdReg.Create); -#endregion + #endregion -#region "OpCode Table (AArch32, A32)" + #region "OpCode Table (AArch32, A32)" // Base SetA32("<<<<0010101xxxxxxxxxxxxxxxxxxxxx", InstName.Adc, InstEmit32.Adc, OpCode32AluImm.Create); SetA32("<<<<0000101xxxxxxxxxxxxxxxx0xxxx", InstName.Adc, InstEmit32.Adc, OpCode32AluRsImm.Create); @@ -882,177 +885,178 @@ namespace ARMeilleure.Decoders SetVfp("<<<<11100x11xxxxxxxx101xx1x0xxxx", InstName.Vsub, InstEmit32.Vsub_S, OpCode32SimdRegS.Create, OpCode32SimdRegS.CreateT32); // ASIMD - SetAsimd("111100111x110000xxx0001101x0xxx0", InstName.Aesd_V, InstEmit32.Aesd_V, OpCode32Simd.Create, OpCode32Simd.CreateT32); - SetAsimd("111100111x110000xxx0001100x0xxx0", InstName.Aese_V, InstEmit32.Aese_V, OpCode32Simd.Create, OpCode32Simd.CreateT32); - SetAsimd("111100111x110000xxx0001111x0xxx0", InstName.Aesimc_V, InstEmit32.Aesimc_V, OpCode32Simd.Create, OpCode32Simd.CreateT32); - SetAsimd("111100111x110000xxx0001110x0xxx0", InstName.Aesmc_V, InstEmit32.Aesmc_V, OpCode32Simd.Create, OpCode32Simd.CreateT32); - SetAsimd("111100110x00xxx0xxx01100x1x0xxx0", InstName.Sha256h_V, InstEmit32.Sha256h_V, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("111100110x01xxx0xxx01100x1x0xxx0", InstName.Sha256h2_V, InstEmit32.Sha256h2_V, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("111100111x111010xxx0001111x0xxx0", InstName.Sha256su0_V, InstEmit32.Sha256su0_V, OpCode32Simd.Create, OpCode32Simd.CreateT32); - SetAsimd("111100110x10xxx0xxx01100x1x0xxx0", InstName.Sha256su1_V, InstEmit32.Sha256su1_V, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("1111001x0x<xxxx", InstName.Vld4, InstEmit32.Vld4, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); - SetAsimd("111101000x10xxxxxxxx000x<>>xxxxxxx100101x1xxx0", InstName.Vqrshrn, InstEmit32.Vqrshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); - SetAsimd("111100111x>>>xxxxxxx100001x1xxx0", InstName.Vqrshrun, InstEmit32.Vqrshrun, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); - SetAsimd("1111001x1x>>>xxxxxxx100100x1xxx0", InstName.Vqshrn, InstEmit32.Vqshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); - SetAsimd("111100111x>>>xxxxxxx100000x1xxx0", InstName.Vqshrun, InstEmit32.Vqshrun, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); - SetAsimd("1111001x0xxxxxxxxxxx0010xxx1xxxx", InstName.Vqsub, InstEmit32.Vqsub, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("111100111x111011xxxx010x0xx0xxxx", InstName.Vrecpe, InstEmit32.Vrecpe, OpCode32SimdSqrte.Create, OpCode32SimdSqrte.CreateT32); - SetAsimd("111100100x00xxxxxxxx1111xxx1xxxx", InstName.Vrecps, InstEmit32.Vrecps, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("111100111x11xx00xxxx000<>>xxxxxxx0010>xx1xxxx", InstName.Vrshr, InstEmit32.Vrshr, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); - SetAsimd("111100101x>>>xxxxxxx100001x1xxx0", InstName.Vrshrn, InstEmit32.Vrshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); - SetAsimd("111100111x111011xxxx010x1xx0xxxx", InstName.Vrsqrte, InstEmit32.Vrsqrte, OpCode32SimdSqrte.Create, OpCode32SimdSqrte.CreateT32); - SetAsimd("111100100x10xxxxxxxx1111xxx1xxxx", InstName.Vrsqrts, InstEmit32.Vrsqrts, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("1111001x1x>>>xxxxxxx0011>xx1xxxx", InstName.Vrsra, InstEmit32.Vrsra, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); - SetAsimd("111100101x>>>xxxxxxx0101>xx1xxxx", InstName.Vshl, InstEmit32.Vshl, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); - SetAsimd("1111001x0xxxxxxxxxxx0100xxx0xxxx", InstName.Vshl, InstEmit32.Vshl_I, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); - SetAsimd("1111001x1x>>>xxxxxxx101000x1xxxx", InstName.Vshll, InstEmit32.Vshll, OpCode32SimdShImmLong.Create, OpCode32SimdShImmLong.CreateT32); // A1 encoding. - SetAsimd("1111001x1x>>>xxxxxxx0000>xx1xxxx", InstName.Vshr, InstEmit32.Vshr, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); - SetAsimd("111100101x>>>xxxxxxx100000x1xxx0", InstName.Vshrn, InstEmit32.Vshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); - SetAsimd("1111001x1x>>>xxxxxxx0001>xx1xxxx", InstName.Vsra, InstEmit32.Vsra, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); - SetAsimd("111101001x00xxxxxxxx0000xxx0xxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); - SetAsimd("111101001x00xxxxxxxx0100xx0xxxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); - SetAsimd("111101001x00xxxxxxxx1000x000xxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); - SetAsimd("111101001x00xxxxxxxx1000x011xxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); - SetAsimd("111101000x00xxxxxxxx0111xx0xxxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemPair.Create, OpCode32SimdMemPair.CreateT32); // Regs = 1. - SetAsimd("111101000x00xxxxxxxx1010xx<xxxx", InstName.Vld4, InstEmit32.Vld4, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); + SetAsimd("111101000x10xxxxxxxx000x<>>xxxxxxx100101x1xxx0", InstName.Vqrshrn, InstEmit32.Vqrshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); + SetAsimd("111100111x>>>xxxxxxx100001x1xxx0", InstName.Vqrshrun, InstEmit32.Vqrshrun, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); + SetAsimd("1111001x1x>>>xxxxxxx100100x1xxx0", InstName.Vqshrn, InstEmit32.Vqshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); + SetAsimd("111100111x>>>xxxxxxx100000x1xxx0", InstName.Vqshrun, InstEmit32.Vqshrun, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); + SetAsimd("1111001x0xxxxxxxxxxx0010xxx1xxxx", InstName.Vqsub, InstEmit32.Vqsub, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); + SetAsimd("111100111x111011xxxx010x0xx0xxxx", InstName.Vrecpe, InstEmit32.Vrecpe, OpCode32SimdSqrte.Create, OpCode32SimdSqrte.CreateT32); + SetAsimd("111100100x00xxxxxxxx1111xxx1xxxx", InstName.Vrecps, InstEmit32.Vrecps, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); + SetAsimd("111100111x11xx00xxxx000<>>xxxxxxx0010>xx1xxxx", InstName.Vrshr, InstEmit32.Vrshr, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); + SetAsimd("111100101x>>>xxxxxxx100001x1xxx0", InstName.Vrshrn, InstEmit32.Vrshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); + SetAsimd("111100111x111011xxxx010x1xx0xxxx", InstName.Vrsqrte, InstEmit32.Vrsqrte, OpCode32SimdSqrte.Create, OpCode32SimdSqrte.CreateT32); + SetAsimd("111100100x10xxxxxxxx1111xxx1xxxx", InstName.Vrsqrts, InstEmit32.Vrsqrts, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); + SetAsimd("1111001x1x>>>xxxxxxx0011>xx1xxxx", InstName.Vrsra, InstEmit32.Vrsra, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); + SetAsimd("111100101x>>>xxxxxxx0101>xx1xxxx", InstName.Vshl, InstEmit32.Vshl, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); + SetAsimd("1111001x0xxxxxxxxxxx0100xxx0xxxx", InstName.Vshl, InstEmit32.Vshl_I, OpCode32SimdReg.Create, OpCode32SimdReg.CreateT32); + SetAsimd("1111001x1x>>>xxxxxxx101000x1xxxx", InstName.Vshll, InstEmit32.Vshll, OpCode32SimdShImmLong.Create, OpCode32SimdShImmLong.CreateT32); // A1 encoding. + SetAsimd("1111001x1x>>>xxxxxxx0000>xx1xxxx", InstName.Vshr, InstEmit32.Vshr, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); + SetAsimd("111100101x>>>xxxxxxx100000x1xxx0", InstName.Vshrn, InstEmit32.Vshrn, OpCode32SimdShImmNarrow.Create, OpCode32SimdShImmNarrow.CreateT32); + SetAsimd("1111001x1x>>>xxxxxxx0001>xx1xxxx", InstName.Vsra, InstEmit32.Vsra, OpCode32SimdShImm.Create, OpCode32SimdShImm.CreateT32); + SetAsimd("111101001x00xxxxxxxx0000xxx0xxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); + SetAsimd("111101001x00xxxxxxxx0100xx0xxxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); + SetAsimd("111101001x00xxxxxxxx1000x000xxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); + SetAsimd("111101001x00xxxxxxxx1000x011xxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemSingle.Create, OpCode32SimdMemSingle.CreateT32); + SetAsimd("111101000x00xxxxxxxx0111xx0xxxxx", InstName.Vst1, InstEmit32.Vst1, OpCode32SimdMemPair.Create, OpCode32SimdMemPair.CreateT32); // Regs = 1. + SetAsimd("111101000x00xxxxxxxx1010xx< allInsts, Func ToFastLookupIndex) + private static void FillFastLookupTable(InstInfo[][] table, List allInsts, Func toFastLookupIndex) { List[] temp = new List[FastLookupSize]; @@ -1315,8 +1320,8 @@ namespace ARMeilleure.Decoders foreach (InstInfo inst in allInsts) { - int mask = ToFastLookupIndex(inst.Mask); - int value = ToFastLookupIndex(inst.Value); + int mask = toFastLookupIndex(inst.Mask); + int value = toFastLookupIndex(inst.Value); for (int index = 0; index < temp.Length; index++) { @@ -1335,22 +1340,21 @@ namespace ARMeilleure.Decoders private static void SetA32(string encoding, InstName name, InstEmitter emitter, MakeOp makeOp) { - Set(encoding, AllInstA32, new InstDescriptor(name, emitter), makeOp); + Set(encoding, _allInstA32, new InstDescriptor(name, emitter), makeOp); } private static void SetT16(string encoding, InstName name, InstEmitter emitter, MakeOp makeOp) { encoding = "xxxxxxxxxxxxxxxx" + encoding; - Set(encoding, AllInstT32, new InstDescriptor(name, emitter), makeOp); + Set(encoding, _allInstT32, new InstDescriptor(name, emitter), makeOp); } private static void SetT32(string encoding, InstName name, InstEmitter emitter, MakeOp makeOp) { string reversedEncoding = $"{encoding.AsSpan(16)}{encoding.AsSpan(0, 16)}"; - MakeOp reversedMakeOp = - (inst, address, opCode) + OpCode ReversedMakeOp(InstDescriptor inst, ulong address, int opCode) => makeOp(inst, address, (int)BitOperations.RotateRight((uint)opCode, 16)); - Set(reversedEncoding, AllInstT32, new InstDescriptor(name, emitter), reversedMakeOp); + Set(reversedEncoding, _allInstT32, new InstDescriptor(name, emitter), ReversedMakeOp); } private static void SetVfp(string encoding, InstName name, InstEmitter emitter, MakeOp makeOpA32, MakeOp makeOpT32) @@ -1395,12 +1399,12 @@ namespace ARMeilleure.Decoders private static void SetA64(string encoding, InstName name, InstEmitter emitter, MakeOp makeOp) { - Set(encoding, AllInstA64, new InstDescriptor(name, emitter), makeOp); + Set(encoding, _allInstA64, new InstDescriptor(name, emitter), makeOp); } private static void Set(string encoding, List list, InstDescriptor inst, MakeOp makeOp) { - int bit = encoding.Length - 1; + int bit = encoding.Length - 1; int value = 0; int xMask = 0; int xBits = 0; @@ -1439,7 +1443,7 @@ namespace ARMeilleure.Decoders } else if (chr != '0') { - throw new ArgumentException(nameof(encoding)); + throw new ArgumentException($"Invalid encoding: {encoding}", nameof(encoding)); } } @@ -1470,17 +1474,17 @@ namespace ARMeilleure.Decoders public static (InstDescriptor inst, MakeOp makeOp) GetInstA32(int opCode) { - return GetInstFromList(InstA32FastLookup[ToFastLookupIndexA(opCode)], opCode); + return GetInstFromList(_instA32FastLookup[ToFastLookupIndexA(opCode)], opCode); } public static (InstDescriptor inst, MakeOp makeOp) GetInstT32(int opCode) { - return GetInstFromList(InstT32FastLookup[ToFastLookupIndexT(opCode)], opCode); + return GetInstFromList(_instT32FastLookup[ToFastLookupIndexT(opCode)], opCode); } public static (InstDescriptor inst, MakeOp makeOp) GetInstA64(int opCode) { - return GetInstFromList(InstA64FastLookup[ToFastLookupIndexA(opCode)], opCode); + return GetInstFromList(_instA64FastLookup[ToFastLookupIndexA(opCode)], opCode); } private static (InstDescriptor inst, MakeOp makeOp) GetInstFromList(InstInfo[] insts, int opCode) diff --git a/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs b/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs index 17c17812d..20759f356 100644 --- a/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs +++ b/src/ARMeilleure/Decoders/Optimizations/TailCallRemover.cs @@ -17,26 +17,26 @@ namespace ARMeilleure.Decoders.Optimizations throw new InvalidOperationException("Function entry point is not contained in a block."); } - const ulong allowance = 4; + const ulong Allowance = 4; Block entryBlock = blocks[entryBlockId]; Block startBlock = entryBlock; - Block endBlock = entryBlock; + Block endBlock = entryBlock; int startBlockIndex = entryBlockId; - int endBlockIndex = entryBlockId; + int endBlockIndex = entryBlockId; for (int i = entryBlockId + 1; i < blocks.Count; i++) // Search forwards. { Block block = blocks[i]; - if (endBlock.EndAddress < block.Address - allowance) + if (endBlock.EndAddress < block.Address - Allowance) { break; // End of contiguous function. } - endBlock = block; + endBlock = block; endBlockIndex = i; } @@ -44,12 +44,12 @@ namespace ARMeilleure.Decoders.Optimizations { Block block = blocks[i]; - if (startBlock.Address > block.EndAddress + allowance) + if (startBlock.Address > block.EndAddress + Allowance) { break; // End of contiguous function. } - startBlock = block; + startBlock = block; startBlockIndex = i; } @@ -57,7 +57,7 @@ namespace ARMeilleure.Decoders.Optimizations { return blocks.ToArray(); // Nothing to do here. } - + // Mark branches whose target is outside of the contiguous region as an exit block. for (int i = startBlockIndex; i <= endBlockIndex; i++) { @@ -69,7 +69,7 @@ namespace ARMeilleure.Decoders.Optimizations } } - var newBlocks = new List(blocks.Count); + var newBlocks = new List(blocks.Count); // Finally, rebuild decoded block list, ignoring blocks outside the contiguous range. for (int i = 0; i < blocks.Count; i++) diff --git a/src/ARMeilleure/Decoders/RegisterSize.cs b/src/ARMeilleure/Decoders/RegisterSize.cs index c9cea03ed..7c00984e8 100644 --- a/src/ARMeilleure/Decoders/RegisterSize.cs +++ b/src/ARMeilleure/Decoders/RegisterSize.cs @@ -5,6 +5,6 @@ namespace ARMeilleure.Decoders Int32, Int64, Simd64, - Simd128 + Simd128, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Decoders/ShiftType.cs b/src/ARMeilleure/Decoders/ShiftType.cs index 8583f16ad..43b738f3f 100644 --- a/src/ARMeilleure/Decoders/ShiftType.cs +++ b/src/ARMeilleure/Decoders/ShiftType.cs @@ -5,6 +5,6 @@ namespace ARMeilleure.Decoders Lsl = 0, Lsr = 1, Asr = 2, - Ror = 3 + Ror = 3, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Diagnostics/IRDumper.cs b/src/ARMeilleure/Diagnostics/IRDumper.cs index 3d1a60e58..16833d085 100644 --- a/src/ARMeilleure/Diagnostics/IRDumper.cs +++ b/src/ARMeilleure/Diagnostics/IRDumper.cs @@ -34,7 +34,9 @@ namespace ARMeilleure.Diagnostics for (int index = 0; index < _indentLevel; index++) { +#pragma warning disable CA1834 // Use StringBuilder.Append(char) for single character strings _builder.Append(Indentation); +#pragma warning restore CA1834 } } @@ -110,10 +112,18 @@ namespace ARMeilleure.Diagnostics switch (reg.Type) { - case RegisterType.Flag: _builder.Append('b'); break; - case RegisterType.FpFlag: _builder.Append('f'); break; - case RegisterType.Integer: _builder.Append('r'); break; - case RegisterType.Vector: _builder.Append('v'); break; + case RegisterType.Flag: + _builder.Append('b'); + break; + case RegisterType.FpFlag: + _builder.Append('f'); + break; + case RegisterType.Integer: + _builder.Append('r'); + break; + case RegisterType.Vector: + _builder.Append('v'); + break; } _builder.Append(reg.Index); @@ -145,9 +155,15 @@ namespace ARMeilleure.Diagnostics switch (memOp.Scale) { - case Multiplier.x2: _builder.Append("*2"); break; - case Multiplier.x4: _builder.Append("*4"); break; - case Multiplier.x8: _builder.Append("*8"); break; + case Multiplier.x2: + _builder.Append("*2"); + break; + case Multiplier.x4: + _builder.Append("*4"); + break; + case Multiplier.x8: + _builder.Append("*8"); + break; } } @@ -308,4 +324,4 @@ namespace ARMeilleure.Diagnostics }; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Diagnostics/Logger.cs b/src/ARMeilleure/Diagnostics/Logger.cs index 07a60667e..d7f61230c 100644 --- a/src/ARMeilleure/Diagnostics/Logger.cs +++ b/src/ARMeilleure/Diagnostics/Logger.cs @@ -8,7 +8,7 @@ namespace ARMeilleure.Diagnostics { private static long _startTime; - private static long[] _accumulatedTime; + private static readonly long[] _accumulatedTime; static Logger() { @@ -53,4 +53,4 @@ namespace ARMeilleure.Diagnostics Console.WriteLine(text); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Diagnostics/PassName.cs b/src/ARMeilleure/Diagnostics/PassName.cs index e34bf0d2f..2d87659f0 100644 --- a/src/ARMeilleure/Diagnostics/PassName.cs +++ b/src/ARMeilleure/Diagnostics/PassName.cs @@ -14,6 +14,6 @@ namespace ARMeilleure.Diagnostics RegisterAllocation, CodeGeneration, - Count + Count, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Diagnostics/Symbols.cs b/src/ARMeilleure/Diagnostics/Symbols.cs index 6bde62f56..86469d8bb 100644 --- a/src/ARMeilleure/Diagnostics/Symbols.cs +++ b/src/ARMeilleure/Diagnostics/Symbols.cs @@ -33,9 +33,8 @@ namespace ARMeilleure.Diagnostics public static string Get(ulong address) { - string result; - if (_symbols.TryGetValue(address, out result)) + if (_symbols.TryGetValue(address, out string result)) { return result; } diff --git a/src/ARMeilleure/Diagnostics/TranslatorEventSource.cs b/src/ARMeilleure/Diagnostics/TranslatorEventSource.cs index a4f17844d..6452bf0af 100644 --- a/src/ARMeilleure/Diagnostics/TranslatorEventSource.cs +++ b/src/ARMeilleure/Diagnostics/TranslatorEventSource.cs @@ -19,19 +19,19 @@ namespace ARMeilleure.Diagnostics { _rejitQueueCounter = new PollingCounter("rejit-queue-length", this, () => _rejitQueue) { - DisplayName = "Rejit Queue Length" + DisplayName = "Rejit Queue Length", }; _funcTabSizeCounter = new PollingCounter("addr-tab-alloc", this, () => _funcTabSize / 1024d / 1024d) { DisplayName = "AddressTable Total Bytes Allocated", - DisplayUnits = "MiB" + DisplayUnits = "MiB", }; _funcTabLeafSizeCounter = new PollingCounter("addr-tab-leaf-alloc", this, () => _funcTabLeafSize / 1024d / 1024d) { DisplayName = "AddressTable Total Leaf Bytes Allocated", - DisplayUnits = "MiB" + DisplayUnits = "MiB", }; } diff --git a/src/ARMeilleure/Instructions/CryptoHelper.cs b/src/ARMeilleure/Instructions/CryptoHelper.cs index e517c75d2..ba68cebb3 100644 --- a/src/ARMeilleure/Instructions/CryptoHelper.cs +++ b/src/ARMeilleure/Instructions/CryptoHelper.cs @@ -7,7 +7,8 @@ namespace ARMeilleure.Instructions { static class CryptoHelper { -#region "LookUp Tables" + #region "LookUp Tables" +#pragma warning disable IDE1006 // Naming rule violation private static ReadOnlySpan _sBox => new byte[] { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, @@ -25,7 +26,7 @@ namespace ARMeilleure.Instructions 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, }; private static ReadOnlySpan _invSBox => new byte[] @@ -45,7 +46,7 @@ namespace ARMeilleure.Instructions 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, - 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d, }; private static ReadOnlySpan _gfMul02 => new byte[] @@ -65,7 +66,7 @@ namespace ARMeilleure.Instructions 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, - 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5 + 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5, }; private static ReadOnlySpan _gfMul03 => new byte[] @@ -85,7 +86,7 @@ namespace ARMeilleure.Instructions 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, - 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a + 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a, }; private static ReadOnlySpan _gfMul09 => new byte[] @@ -105,7 +106,7 @@ namespace ARMeilleure.Instructions 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, - 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46 + 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46, }; private static ReadOnlySpan _gfMul0B => new byte[] @@ -125,7 +126,7 @@ namespace ARMeilleure.Instructions 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, - 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3 + 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3, }; private static ReadOnlySpan _gfMul0D => new byte[] @@ -145,7 +146,7 @@ namespace ARMeilleure.Instructions 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, - 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97 + 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97, }; private static ReadOnlySpan _gfMul0E => new byte[] @@ -165,23 +166,24 @@ namespace ARMeilleure.Instructions 0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, - 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d + 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d, }; private static ReadOnlySpan _srPerm => new byte[] { - 0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3 + 0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3, }; private static ReadOnlySpan _isrPerm => new byte[] { - 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11 + 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11, }; -#endregion +#pragma warning restore IDE1006 + #endregion public static V128 AesInvMixColumns(V128 op) { - byte[] inState = op.ToArray(); + byte[] inState = op.ToArray(); byte[] outState = new byte[16]; for (int columns = 0; columns <= 3; columns++) @@ -204,7 +206,7 @@ namespace ARMeilleure.Instructions public static V128 AesInvShiftRows(V128 op) { - byte[] inState = op.ToArray(); + byte[] inState = op.ToArray(); byte[] outState = new byte[16]; for (int idx = 0; idx <= 15; idx++) @@ -217,7 +219,7 @@ namespace ARMeilleure.Instructions public static V128 AesInvSubBytes(V128 op) { - byte[] inState = op.ToArray(); + byte[] inState = op.ToArray(); byte[] outState = new byte[16]; for (int idx = 0; idx <= 15; idx++) @@ -230,7 +232,7 @@ namespace ARMeilleure.Instructions public static V128 AesMixColumns(V128 op) { - byte[] inState = op.ToArray(); + byte[] inState = op.ToArray(); byte[] outState = new byte[16]; for (int columns = 0; columns <= 3; columns++) @@ -253,7 +255,7 @@ namespace ARMeilleure.Instructions public static V128 AesShiftRows(V128 op) { - byte[] inState = op.ToArray(); + byte[] inState = op.ToArray(); byte[] outState = new byte[16]; for (int idx = 0; idx <= 15; idx++) @@ -266,7 +268,7 @@ namespace ARMeilleure.Instructions public static V128 AesSubBytes(V128 op) { - byte[] inState = op.ToArray(); + byte[] inState = op.ToArray(); byte[] outState = new byte[16]; for (int idx = 0; idx <= 15; idx++) diff --git a/src/ARMeilleure/Instructions/InstEmitAlu.cs b/src/ARMeilleure/Instructions/InstEmitAlu.cs index e0d10e77d..ac17c32a7 100644 --- a/src/ARMeilleure/Instructions/InstEmitAlu.cs +++ b/src/ARMeilleure/Instructions/InstEmitAlu.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System.Diagnostics; - using static ARMeilleure.Instructions.InstEmitAluHelper; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -12,7 +11,7 @@ namespace ARMeilleure.Instructions { static partial class InstEmit { - public static void Adc(ArmEmitterContext context) => EmitAdc(context, setFlags: false); + public static void Adc(ArmEmitterContext context) => EmitAdc(context, setFlags: false); public static void Adcs(ArmEmitterContext context) => EmitAdc(context, setFlags: true); private static void EmitAdc(ArmEmitterContext context, bool setFlags) @@ -87,7 +86,7 @@ namespace ARMeilleure.Instructions SetAluDOrZR(context, context.ShiftRightSI(GetAluN(context), GetAluMShift(context))); } - public static void Bic(ArmEmitterContext context) => EmitBic(context, setFlags: false); + public static void Bic(ArmEmitterContext context) => EmitBic(context, setFlags: false); public static void Bics(ArmEmitterContext context) => EmitBic(context, setFlags: true); private static void EmitBic(ArmEmitterContext context, bool setFlags) @@ -190,7 +189,7 @@ namespace ARMeilleure.Instructions SetAluDOrZR(context, context.ShiftRightUI(GetAluN(context), GetAluMShift(context))); } - public static void Sbc(ArmEmitterContext context) => EmitSbc(context, setFlags: false); + public static void Sbc(ArmEmitterContext context) => EmitSbc(context, setFlags: false); public static void Sbcs(ArmEmitterContext context) => EmitSbc(context, setFlags: true); private static void EmitSbc(ArmEmitterContext context, bool setFlags) @@ -281,16 +280,16 @@ namespace ARMeilleure.Instructions Debug.Assert(op.Type == OperandType.I64); Operand val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(op, Const(0xaaaaaaaaaaaaaaaaul)), Const(1)), - context.ShiftLeft (context.BitwiseAnd(op, Const(0x5555555555555555ul)), Const(1))); + context.ShiftLeft(context.BitwiseAnd(op, Const(0x5555555555555555ul)), Const(1))); val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(val, Const(0xccccccccccccccccul)), Const(2)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x3333333333333333ul)), Const(2))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x3333333333333333ul)), Const(2))); val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(val, Const(0xf0f0f0f0f0f0f0f0ul)), Const(4)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x0f0f0f0f0f0f0f0ful)), Const(4))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x0f0f0f0f0f0f0f0ful)), Const(4))); val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(val, Const(0xff00ff00ff00ff00ul)), Const(8)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x00ff00ff00ff00fful)), Const(8))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x00ff00ff00ff00fful)), Const(8))); val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(val, Const(0xffff0000ffff0000ul)), Const(16)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x0000ffff0000fffful)), Const(16))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x0000ffff0000fffful)), Const(16))); return context.BitwiseOr(context.ShiftRightUI(val, Const(32)), context.ShiftLeft(val, Const(32))); } @@ -340,7 +339,7 @@ namespace ARMeilleure.Instructions Operand val = EmitReverseBytes16_64Op(context, op); return context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(val, Const(0xffff0000ffff0000ul)), Const(16)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x0000ffff0000fffful)), Const(16))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x0000ffff0000fffful)), Const(16))); } public static void Rev64(ArmEmitterContext context) diff --git a/src/ARMeilleure/Instructions/InstEmitAlu32.cs b/src/ARMeilleure/Instructions/InstEmitAlu32.cs index 584ada7e0..3a5e71bcc 100644 --- a/src/ARMeilleure/Instructions/InstEmitAlu32.cs +++ b/src/ARMeilleure/Instructions/InstEmitAlu32.cs @@ -2,13 +2,14 @@ using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; - +using System.Diagnostics.CodeAnalysis; using static ARMeilleure.Instructions.InstEmitAluHelper; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; namespace ARMeilleure.Instructions { + [SuppressMessage("Style", "IDE0059: Remove unnecessary value assignment")] static partial class InstEmit32 { public static void Add(ArmEmitterContext context) diff --git a/src/ARMeilleure/Instructions/InstEmitAluHelper.cs b/src/ARMeilleure/Instructions/InstEmitAluHelper.cs index 994878ad7..4d4a31f7b 100644 --- a/src/ARMeilleure/Instructions/InstEmitAluHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitAluHelper.cs @@ -26,7 +26,7 @@ namespace ARMeilleure.Instructions public static void EmitNZFlagsCheck(ArmEmitterContext context, Operand d) { - SetFlag(context, PState.NFlag, context.ICompareLess (d, Const(d.Type, 0))); + SetFlag(context, PState.NFlag, context.ICompareLess(d, Const(d.Type, 0))); SetFlag(context, PState.ZFlag, context.ICompareEqual(d, Const(d.Type, 0))); } @@ -196,60 +196,73 @@ namespace ARMeilleure.Instructions { // ARM32. case IOpCode32AluImm op: - { - if (ShouldSetFlags(context) && op.IsRotated && setCarry) { - SetFlag(context, PState.CFlag, Const((uint)op.Immediate >> 31)); + if (ShouldSetFlags(context) && op.IsRotated && setCarry) + { + SetFlag(context, PState.CFlag, Const((uint)op.Immediate >> 31)); + } + + return Const(op.Immediate); } + case IOpCode32AluImm16 op: return Const(op.Immediate); - } - case IOpCode32AluImm16 op: return Const(op.Immediate); + case IOpCode32AluRsImm op: + return GetMShiftedByImmediate(context, op, setCarry); + case IOpCode32AluRsReg op: + return GetMShiftedByReg(context, op, setCarry); - case IOpCode32AluRsImm op: return GetMShiftedByImmediate(context, op, setCarry); - case IOpCode32AluRsReg op: return GetMShiftedByReg(context, op, setCarry); - - case IOpCode32AluReg op: return GetIntA32(context, op.Rm); + case IOpCode32AluReg op: + return GetIntA32(context, op.Rm); // ARM64. case IOpCodeAluImm op: - { - if (op.GetOperandType() == OperandType.I32) { - return Const((int)op.Immediate); + if (op.GetOperandType() == OperandType.I32) + { + return Const((int)op.Immediate); + } + else + { + return Const(op.Immediate); + } } - else - { - return Const(op.Immediate); - } - } case IOpCodeAluRs op: - { - Operand value = GetIntOrZR(context, op.Rm); - - switch (op.ShiftType) { - case ShiftType.Lsl: value = context.ShiftLeft (value, Const(op.Shift)); break; - case ShiftType.Lsr: value = context.ShiftRightUI(value, Const(op.Shift)); break; - case ShiftType.Asr: value = context.ShiftRightSI(value, Const(op.Shift)); break; - case ShiftType.Ror: value = context.RotateRight (value, Const(op.Shift)); break; + Operand value = GetIntOrZR(context, op.Rm); + + switch (op.ShiftType) + { + case ShiftType.Lsl: + value = context.ShiftLeft(value, Const(op.Shift)); + break; + case ShiftType.Lsr: + value = context.ShiftRightUI(value, Const(op.Shift)); + break; + case ShiftType.Asr: + value = context.ShiftRightSI(value, Const(op.Shift)); + break; + case ShiftType.Ror: + value = context.RotateRight(value, Const(op.Shift)); + break; + } + + return value; } - return value; - } - case IOpCodeAluRx op: - { - Operand value = GetExtendedM(context, op.Rm, op.IntType); + { + Operand value = GetExtendedM(context, op.Rm, op.IntType); - value = context.ShiftLeft(value, Const(op.Shift)); + value = context.ShiftLeft(value, Const(op.Shift)); - return value; - } + return value; + } - default: throw InvalidOpCodeType(context.CurrOp); + default: + throw InvalidOpCodeType(context.CurrOp); } } @@ -269,9 +282,15 @@ namespace ARMeilleure.Instructions { switch (op.ShiftType) { - case ShiftType.Lsr: shift = 32; break; - case ShiftType.Asr: shift = 32; break; - case ShiftType.Ror: shift = 1; break; + case ShiftType.Lsr: + shift = 32; + break; + case ShiftType.Asr: + shift = 32; + break; + case ShiftType.Ror: + shift = 1; + break; } } @@ -281,9 +300,15 @@ namespace ARMeilleure.Instructions switch (op.ShiftType) { - case ShiftType.Lsl: m = GetLslC(context, m, setCarry, shift); break; - case ShiftType.Lsr: m = GetLsrC(context, m, setCarry, shift); break; - case ShiftType.Asr: m = GetAsrC(context, m, setCarry, shift); break; + case ShiftType.Lsl: + m = GetLslC(context, m, setCarry, shift); + break; + case ShiftType.Lsr: + m = GetLsrC(context, m, setCarry, shift); + break; + case ShiftType.Asr: + m = GetAsrC(context, m, setCarry, shift); + break; case ShiftType.Ror: if (op.Immediate != 0) { @@ -306,9 +331,15 @@ namespace ARMeilleure.Instructions { switch (shiftType) { - case ShiftType.Lsr: shift = 32; break; - case ShiftType.Asr: shift = 32; break; - case ShiftType.Ror: shift = 1; break; + case ShiftType.Lsr: + shift = 32; + break; + case ShiftType.Asr: + shift = 32; + break; + case ShiftType.Ror: + shift = 1; + break; } } @@ -328,10 +359,18 @@ namespace ARMeilleure.Instructions switch (op.ShiftType) { - case ShiftType.Lsl: shiftResult = EmitLslC(context, m, setCarry, s, shiftIsZero); break; - case ShiftType.Lsr: shiftResult = EmitLsrC(context, m, setCarry, s, shiftIsZero); break; - case ShiftType.Asr: shiftResult = EmitAsrC(context, m, setCarry, s, shiftIsZero); break; - case ShiftType.Ror: shiftResult = EmitRorC(context, m, setCarry, s, shiftIsZero); break; + case ShiftType.Lsl: + shiftResult = EmitLslC(context, m, setCarry, s, shiftIsZero); + break; + case ShiftType.Lsr: + shiftResult = EmitLsrC(context, m, setCarry, s, shiftIsZero); + break; + case ShiftType.Asr: + shiftResult = EmitAsrC(context, m, setCarry, s, shiftIsZero); + break; + case ShiftType.Ror: + shiftResult = EmitRorC(context, m, setCarry, s, shiftIsZero); + break; } return context.ConditionalSelect(shiftIsZero, zeroResult, shiftResult); diff --git a/src/ARMeilleure/Instructions/InstEmitBfm.cs b/src/ARMeilleure/Instructions/InstEmitBfm.cs index 46a7ddddd..aaf228756 100644 --- a/src/ARMeilleure/Instructions/InstEmitBfm.cs +++ b/src/ARMeilleure/Instructions/InstEmitBfm.cs @@ -84,9 +84,9 @@ namespace ARMeilleure.Instructions { Operand res = GetIntOrZR(context, op.Rn); - res = context.ShiftLeft (res, Const(bitsCount - 1 - op.Pos)); + res = context.ShiftLeft(res, Const(bitsCount - 1 - op.Pos)); res = context.ShiftRightSI(res, Const(bitsCount - 1)); - res = context.BitwiseAnd (res, Const(res.Type, ~op.TMask)); + res = context.BitwiseAnd(res, Const(res.Type, ~op.TMask)); Operand n2 = GetBfmN(context); @@ -193,4 +193,4 @@ namespace ARMeilleure.Instructions return context.BitwiseAnd(context.RotateRight(res, Const(op.Shift)), Const(res.Type, mask)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitCcmp.cs b/src/ARMeilleure/Instructions/InstEmitCcmp.cs index 7f0beb6cb..a71fc2689 100644 --- a/src/ARMeilleure/Instructions/InstEmitCcmp.cs +++ b/src/ARMeilleure/Instructions/InstEmitCcmp.cs @@ -2,7 +2,6 @@ using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; - using static ARMeilleure.Instructions.InstEmitAluHelper; using static ARMeilleure.Instructions.InstEmitFlowHelper; using static ARMeilleure.Instructions.InstEmitHelper; @@ -20,7 +19,7 @@ namespace ARMeilleure.Instructions OpCodeCcmp op = (OpCodeCcmp)context.CurrOp; Operand lblTrue = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); EmitCondBranch(context, lblTrue, op.Cond); @@ -58,4 +57,4 @@ namespace ARMeilleure.Instructions context.MarkLabel(lblEnd); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitCsel.cs b/src/ARMeilleure/Instructions/InstEmitCsel.cs index 926b9a9ed..1cd936b31 100644 --- a/src/ARMeilleure/Instructions/InstEmitCsel.cs +++ b/src/ARMeilleure/Instructions/InstEmitCsel.cs @@ -1,7 +1,6 @@ using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; - using static ARMeilleure.Instructions.InstEmitFlowHelper; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -15,10 +14,10 @@ namespace ARMeilleure.Instructions None, Increment, Invert, - Negate + Negate, } - public static void Csel(ArmEmitterContext context) => EmitCsel(context, CselOperation.None); + public static void Csel(ArmEmitterContext context) => EmitCsel(context, CselOperation.None); public static void Csinc(ArmEmitterContext context) => EmitCsel(context, CselOperation.Increment); public static void Csinv(ArmEmitterContext context) => EmitCsel(context, CselOperation.Invert); public static void Csneg(ArmEmitterContext context) => EmitCsel(context, CselOperation.Negate); @@ -50,4 +49,4 @@ namespace ARMeilleure.Instructions SetIntOrZR(context, op.Rd, d); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitDiv.cs b/src/ARMeilleure/Instructions/InstEmitDiv.cs index 39a5c32e6..728462ed4 100644 --- a/src/ARMeilleure/Instructions/InstEmitDiv.cs +++ b/src/ARMeilleure/Instructions/InstEmitDiv.cs @@ -1,7 +1,6 @@ using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -23,7 +22,7 @@ namespace ARMeilleure.Instructions Operand divisorIsZero = context.ICompareEqual(m, Const(m.Type, 0)); Operand lblBadDiv = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); context.BranchIfTrue(lblBadDiv, divisorIsZero); @@ -33,7 +32,7 @@ namespace ARMeilleure.Instructions bool is32Bits = op.RegisterSize == RegisterSize.Int32; Operand intMin = is32Bits ? Const(int.MinValue) : Const(long.MinValue); - Operand minus1 = is32Bits ? Const(-1) : Const(-1L); + Operand minus1 = is32Bits ? Const(-1) : Const(-1L); Operand nIsIntMin = context.ICompareEqual(n, intMin); Operand mIsMinus1 = context.ICompareEqual(m, minus1); @@ -51,7 +50,7 @@ namespace ARMeilleure.Instructions Operand d = unsigned ? context.DivideUI(n, m) - : context.Divide (n, m); + : context.Divide(n, m); SetAluDOrZR(context, d); diff --git a/src/ARMeilleure/Instructions/InstEmitException.cs b/src/ARMeilleure/Instructions/InstEmitException.cs index 0baaa87d7..d30fb2fbd 100644 --- a/src/ARMeilleure/Instructions/InstEmitException.cs +++ b/src/ARMeilleure/Instructions/InstEmitException.cs @@ -52,4 +52,4 @@ namespace ARMeilleure.Instructions context.Return(Const(op.Address)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitFlow.cs b/src/ARMeilleure/Instructions/InstEmitFlow.cs index c40eb55cf..a986bf66f 100644 --- a/src/ARMeilleure/Instructions/InstEmitFlow.cs +++ b/src/ARMeilleure/Instructions/InstEmitFlow.cs @@ -53,7 +53,7 @@ namespace ARMeilleure.Instructions } public static void Cbnz(ArmEmitterContext context) => EmitCb(context, onNotZero: true); - public static void Cbz(ArmEmitterContext context) => EmitCb(context, onNotZero: false); + public static void Cbz(ArmEmitterContext context) => EmitCb(context, onNotZero: false); private static void EmitCb(ArmEmitterContext context, bool onNotZero) { @@ -70,7 +70,7 @@ namespace ARMeilleure.Instructions } public static void Tbnz(ArmEmitterContext context) => EmitTb(context, onNotZero: true); - public static void Tbz(ArmEmitterContext context) => EmitTb(context, onNotZero: false); + public static void Tbz(ArmEmitterContext context) => EmitTb(context, onNotZero: false); private static void EmitTb(ArmEmitterContext context, bool onNotZero) { @@ -104,4 +104,4 @@ namespace ARMeilleure.Instructions } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitFlow32.cs b/src/ARMeilleure/Instructions/InstEmitFlow32.cs index 3a7707ee9..289d3f483 100644 --- a/src/ARMeilleure/Instructions/InstEmitFlow32.cs +++ b/src/ARMeilleure/Instructions/InstEmitFlow32.cs @@ -82,7 +82,7 @@ namespace ARMeilleure.Instructions } public static void Cbnz(ArmEmitterContext context) => EmitCb(context, onNotZero: true); - public static void Cbz(ArmEmitterContext context) => EmitCb(context, onNotZero: false); + public static void Cbz(ArmEmitterContext context) => EmitCb(context, onNotZero: false); private static void EmitCb(ArmEmitterContext context, bool onNotZero) { @@ -109,7 +109,7 @@ namespace ARMeilleure.Instructions } public static void Tbb(ArmEmitterContext context) => EmitTb(context, halfword: false); - public static void Tbh(ArmEmitterContext context) => EmitTb(context, halfword: true); + public static void Tbh(ArmEmitterContext context) => EmitTb(context, halfword: true); private static void EmitTb(ArmEmitterContext context, bool halfword) { @@ -133,4 +133,4 @@ namespace ARMeilleure.Instructions EmitVirtualJump(context, targetAddress, isReturn: false); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs b/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs index 6ac329085..2009bafda 100644 --- a/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitFlowHelper.cs @@ -75,66 +75,66 @@ namespace ARMeilleure.Instructions break; case Condition.GtUn: - { - Operand c = GetFlag(PState.CFlag); - Operand z = GetFlag(PState.ZFlag); + { + Operand c = GetFlag(PState.CFlag); + Operand z = GetFlag(PState.ZFlag); - value = context.BitwiseAnd(c, Inverse(z)); + value = context.BitwiseAnd(c, Inverse(z)); - break; - } + break; + } case Condition.LeUn: - { - Operand c = GetFlag(PState.CFlag); - Operand z = GetFlag(PState.ZFlag); + { + Operand c = GetFlag(PState.CFlag); + Operand z = GetFlag(PState.ZFlag); - value = context.BitwiseOr(Inverse(c), z); + value = context.BitwiseOr(Inverse(c), z); - break; - } + break; + } case Condition.Ge: - { - Operand n = GetFlag(PState.NFlag); - Operand v = GetFlag(PState.VFlag); + { + Operand n = GetFlag(PState.NFlag); + Operand v = GetFlag(PState.VFlag); - value = context.ICompareEqual(n, v); + value = context.ICompareEqual(n, v); - break; - } + break; + } case Condition.Lt: - { - Operand n = GetFlag(PState.NFlag); - Operand v = GetFlag(PState.VFlag); + { + Operand n = GetFlag(PState.NFlag); + Operand v = GetFlag(PState.VFlag); - value = context.ICompareNotEqual(n, v); + value = context.ICompareNotEqual(n, v); - break; - } + break; + } case Condition.Gt: - { - Operand n = GetFlag(PState.NFlag); - Operand z = GetFlag(PState.ZFlag); - Operand v = GetFlag(PState.VFlag); + { + Operand n = GetFlag(PState.NFlag); + Operand z = GetFlag(PState.ZFlag); + Operand v = GetFlag(PState.VFlag); - value = context.BitwiseAnd(Inverse(z), context.ICompareEqual(n, v)); + value = context.BitwiseAnd(Inverse(z), context.ICompareEqual(n, v)); - break; - } + break; + } case Condition.Le: - { - Operand n = GetFlag(PState.NFlag); - Operand z = GetFlag(PState.ZFlag); - Operand v = GetFlag(PState.VFlag); + { + Operand n = GetFlag(PState.NFlag); + Operand z = GetFlag(PState.ZFlag); + Operand v = GetFlag(PState.VFlag); - value = context.BitwiseOr(z, context.ICompareNotEqual(n, v)); + value = context.BitwiseOr(z, context.ICompareNotEqual(n, v)); - break; - } + break; + } } return value; diff --git a/src/ARMeilleure/Instructions/InstEmitHashHelper.cs b/src/ARMeilleure/Instructions/InstEmitHashHelper.cs index 55a03a4f6..9218e1ae0 100644 --- a/src/ARMeilleure/Instructions/InstEmitHashHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitHashHelper.cs @@ -45,7 +45,7 @@ namespace ARMeilleure.Instructions } else { - string name = (size, castagnoli) switch + string name = (size, castagnoli) switch { (0, false) => nameof(SoftFallback.Crc32b), (1, false) => nameof(SoftFallback.Crc32h), @@ -55,7 +55,7 @@ namespace ARMeilleure.Instructions (1, true) => nameof(SoftFallback.Crc32ch), (2, true) => nameof(SoftFallback.Crc32cw), (3, true) => nameof(SoftFallback.Crc32cx), - _ => throw new ArgumentOutOfRangeException(nameof(size)) + _ => throw new ArgumentOutOfRangeException(nameof(size)), }; return context.Call(typeof(SoftFallback).GetMethod(name), crc, value); @@ -71,9 +71,15 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: data = context.VectorInsert8(context.VectorZero(), data, 0); break; - case 1: data = context.VectorInsert16(context.VectorZero(), data, 0); break; - case 2: data = context.VectorInsert(context.VectorZero(), data, 0); break; + case 0: + data = context.VectorInsert8(context.VectorZero(), data, 0); + break; + case 1: + data = context.VectorInsert16(context.VectorZero(), data, 0); + break; + case 2: + data = context.VectorInsert(context.VectorZero(), data, 0); + break; } int bitsize = 8 << size; diff --git a/src/ARMeilleure/Instructions/InstEmitHelper.cs b/src/ARMeilleure/Instructions/InstEmitHelper.cs index a22bb3fb7..7a515f94f 100644 --- a/src/ARMeilleure/Instructions/InstEmitHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitHelper.cs @@ -16,13 +16,25 @@ namespace ARMeilleure.Instructions switch (type) { - case IntType.UInt8: value = context.ZeroExtend8 (value.Type, value); break; - case IntType.UInt16: value = context.ZeroExtend16(value.Type, value); break; - case IntType.UInt32: value = context.ZeroExtend32(value.Type, value); break; + case IntType.UInt8: + value = context.ZeroExtend8(value.Type, value); + break; + case IntType.UInt16: + value = context.ZeroExtend16(value.Type, value); + break; + case IntType.UInt32: + value = context.ZeroExtend32(value.Type, value); + break; - case IntType.Int8: value = context.SignExtend8 (value.Type, value); break; - case IntType.Int16: value = context.SignExtend16(value.Type, value); break; - case IntType.Int32: value = context.SignExtend32(value.Type, value); break; + case IntType.Int8: + value = context.SignExtend8(value.Type, value); + break; + case IntType.Int16: + value = context.SignExtend16(value.Type, value); + break; + case IntType.Int32: + value = context.SignExtend32(value.Type, value); + break; } return value; @@ -100,78 +112,51 @@ namespace ARMeilleure.Instructions public static int GetBankedRegisterAlias(Aarch32Mode mode, int regIndex) { - switch (regIndex) + return regIndex switch { - case 8: return mode == Aarch32Mode.Fiq - ? RegisterAlias.R8Fiq - : RegisterAlias.R8Usr; - - case 9: return mode == Aarch32Mode.Fiq - ? RegisterAlias.R9Fiq - : RegisterAlias.R9Usr; - - case 10: return mode == Aarch32Mode.Fiq - ? RegisterAlias.R10Fiq - : RegisterAlias.R10Usr; - - case 11: return mode == Aarch32Mode.Fiq - ? RegisterAlias.R11Fiq - : RegisterAlias.R11Usr; - - case 12: return mode == Aarch32Mode.Fiq - ? RegisterAlias.R12Fiq - : RegisterAlias.R12Usr; - - case 13: - switch (mode) - { - case Aarch32Mode.User: - case Aarch32Mode.System: return RegisterAlias.SpUsr; - case Aarch32Mode.Fiq: return RegisterAlias.SpFiq; - case Aarch32Mode.Irq: return RegisterAlias.SpIrq; - case Aarch32Mode.Supervisor: return RegisterAlias.SpSvc; - case Aarch32Mode.Abort: return RegisterAlias.SpAbt; - case Aarch32Mode.Hypervisor: return RegisterAlias.SpHyp; - case Aarch32Mode.Undefined: return RegisterAlias.SpUnd; - - default: throw new ArgumentException(nameof(mode)); - } - - case 14: - switch (mode) - { - case Aarch32Mode.User: - case Aarch32Mode.Hypervisor: - case Aarch32Mode.System: return RegisterAlias.LrUsr; - case Aarch32Mode.Fiq: return RegisterAlias.LrFiq; - case Aarch32Mode.Irq: return RegisterAlias.LrIrq; - case Aarch32Mode.Supervisor: return RegisterAlias.LrSvc; - case Aarch32Mode.Abort: return RegisterAlias.LrAbt; - case Aarch32Mode.Undefined: return RegisterAlias.LrUnd; - - default: throw new ArgumentException(nameof(mode)); - } - - default: throw new ArgumentOutOfRangeException(nameof(regIndex)); - } +#pragma warning disable IDE0055 // Disable formatting + 8 => mode == Aarch32Mode.Fiq ? RegisterAlias.R8Fiq : RegisterAlias.R8Usr, + 9 => mode == Aarch32Mode.Fiq ? RegisterAlias.R9Fiq : RegisterAlias.R9Usr, + 10 => mode == Aarch32Mode.Fiq ? RegisterAlias.R10Fiq : RegisterAlias.R10Usr, + 11 => mode == Aarch32Mode.Fiq ? RegisterAlias.R11Fiq : RegisterAlias.R11Usr, + 12 => mode == Aarch32Mode.Fiq ? RegisterAlias.R12Fiq : RegisterAlias.R12Usr, + 13 => mode switch + { + Aarch32Mode.User or Aarch32Mode.System => RegisterAlias.SpUsr, + Aarch32Mode.Fiq => RegisterAlias.SpFiq, + Aarch32Mode.Irq => RegisterAlias.SpIrq, + Aarch32Mode.Supervisor => RegisterAlias.SpSvc, + Aarch32Mode.Abort => RegisterAlias.SpAbt, + Aarch32Mode.Hypervisor => RegisterAlias.SpHyp, + Aarch32Mode.Undefined => RegisterAlias.SpUnd, + _ => throw new ArgumentException($"No such AArch32Mode: {mode}", nameof(mode)), + }, + 14 => mode switch + { + Aarch32Mode.User or Aarch32Mode.Hypervisor or Aarch32Mode.System => RegisterAlias.LrUsr, + Aarch32Mode.Fiq => RegisterAlias.LrFiq, + Aarch32Mode.Irq => RegisterAlias.LrIrq, + Aarch32Mode.Supervisor => RegisterAlias.LrSvc, + Aarch32Mode.Abort => RegisterAlias.LrAbt, + Aarch32Mode.Undefined => RegisterAlias.LrUnd, + _ => throw new ArgumentException($"No such AArch32Mode: {mode}", nameof(mode)), + }, + _ => throw new ArgumentOutOfRangeException(nameof(regIndex), regIndex, null), +#pragma warning restore IDE0055 + }; } public static bool IsA32Return(ArmEmitterContext context) { - switch (context.CurrOp) + return context.CurrOp switch { - case IOpCode32MemMult op: - return true; // Setting PC using LDM is nearly always a return. - case OpCode32AluRsImm op: - return op.Rm == RegisterAlias.Aarch32Lr; - case OpCode32AluRsReg op: - return op.Rm == RegisterAlias.Aarch32Lr; - case OpCode32AluReg op: - return op.Rm == RegisterAlias.Aarch32Lr; - case OpCode32Mem op: - return op.Rn == RegisterAlias.Aarch32Sp && op.WBack && !op.Index; // Setting PC to an address stored on the stack is nearly always a return. - } - return false; + IOpCode32MemMult => true, // Setting PC using LDM is nearly always a return. + OpCode32AluRsImm op => op.Rm == RegisterAlias.Aarch32Lr, + OpCode32AluRsReg op => op.Rm == RegisterAlias.Aarch32Lr, + OpCode32AluReg op => op.Rm == RegisterAlias.Aarch32Lr, + OpCode32Mem op => op.Rn == RegisterAlias.Aarch32Sp && op.WBack && !op.Index, // Setting PC to an address stored on the stack is nearly always a return. + _ => false, + }; } public static void EmitBxWritePc(ArmEmitterContext context, Operand pc, int sourceRegister = 0) diff --git a/src/ARMeilleure/Instructions/InstEmitMemory.cs b/src/ARMeilleure/Instructions/InstEmitMemory.cs index 7baed14c8..840099f9c 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemory.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemory.cs @@ -26,7 +26,7 @@ namespace ARMeilleure.Instructions SetIntOrZR(context, op.Rd, Const(address)); } - public static void Ldr(ArmEmitterContext context) => EmitLdr(context, signed: false); + public static void Ldr(ArmEmitterContext context) => EmitLdr(context, signed: false); public static void Ldrs(ArmEmitterContext context) => EmitLdr(context, signed: true); private static void EmitLdr(ArmEmitterContext context, bool signed) @@ -89,7 +89,7 @@ namespace ARMeilleure.Instructions Operand address = GetAddress(context); Operand address2 = GetAddress(context, 1L << op.Size); - EmitLoad(op.Rt, address); + EmitLoad(op.Rt, address); EmitLoad(op.Rt2, address2); EmitWBackIfNeeded(context, address); @@ -113,7 +113,7 @@ namespace ARMeilleure.Instructions Operand address = GetAddress(context); Operand address2 = GetAddress(context, 1L << op.Size); - EmitStore(context, address, op.Rt, op.Size); + EmitStore(context, address, op.Rt, op.Size); EmitStore(context, address2, op.Rt2, op.Size); EmitWBackIfNeeded(context, address); @@ -126,42 +126,42 @@ namespace ARMeilleure.Instructions switch (context.CurrOp) { case OpCodeMemImm op: - { - address = context.Copy(GetIntOrSP(context, op.Rn)); - - // Pre-indexing. - if (!op.PostIdx) { - address = context.Add(address, Const(op.Immediate + addend)); - } - else if (addend != 0) - { - address = context.Add(address, Const(addend)); - } + address = context.Copy(GetIntOrSP(context, op.Rn)); - break; - } + // Pre-indexing. + if (!op.PostIdx) + { + address = context.Add(address, Const(op.Immediate + addend)); + } + else if (addend != 0) + { + address = context.Add(address, Const(addend)); + } + + break; + } case OpCodeMemReg op: - { - Operand n = GetIntOrSP(context, op.Rn); - - Operand m = GetExtendedM(context, op.Rm, op.IntType); - - if (op.Shift) { - m = context.ShiftLeft(m, Const(op.Size)); + Operand n = GetIntOrSP(context, op.Rn); + + Operand m = GetExtendedM(context, op.Rm, op.IntType); + + if (op.Shift) + { + m = context.ShiftLeft(m, Const(op.Size)); + } + + address = context.Add(n, m); + + if (addend != 0) + { + address = context.Add(address, Const(addend)); + } + + break; } - - address = context.Add(n, m); - - if (addend != 0) - { - address = context.Add(address, Const(addend)); - } - - break; - } } return address; @@ -181,4 +181,4 @@ namespace ARMeilleure.Instructions } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitMemory32.cs b/src/ARMeilleure/Instructions/InstEmitMemory32.cs index 17ec97aa6..cee06700d 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemory32.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemory32.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitMemoryHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -12,18 +11,18 @@ namespace ARMeilleure.Instructions { static partial class InstEmit32 { - private const int ByteSizeLog2 = 0; + private const int ByteSizeLog2 = 0; private const int HWordSizeLog2 = 1; - private const int WordSizeLog2 = 2; + private const int WordSizeLog2 = 2; private const int DWordSizeLog2 = 3; [Flags] enum AccessType { - Store = 0, - Signed = 1, - Load = 2, - Ordered = 4, + Store = 0, + Signed = 1, + Load = 2, + Ordered = 4, Exclusive = 8, LoadZx = Load, @@ -47,7 +46,7 @@ namespace ARMeilleure.Instructions SetIntA32(context, op.Rn, context.Add(n, Const(op.PostOffset))); } - int mask = op.RegisterMask; + int mask = op.RegisterMask; int offset = 0; for (int register = 0; mask != 0; mask >>= 1, register++) @@ -101,7 +100,7 @@ namespace ARMeilleure.Instructions Operand baseAddress = context.Add(n, Const(op.Offset)); - int mask = op.RegisterMask; + int mask = op.RegisterMask; int offset = 0; for (int register = 0; mask != 0; mask >>= 1, register++) @@ -161,7 +160,7 @@ namespace ARMeilleure.Instructions if (op.Index || op.WBack) { temp = op.Add - ? context.Add (n, m) + ? context.Add(n, m) : context.Subtract(n, m); } @@ -200,7 +199,7 @@ namespace ARMeilleure.Instructions if (size == DWordSizeLog2) { Operand lblBigEndian = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); context.BranchIfTrue(lblBigEndian, GetFlag(PState.EFlag)); @@ -233,7 +232,7 @@ namespace ARMeilleure.Instructions if (size == DWordSizeLog2) { Operand lblBigEndian = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); context.BranchIfTrue(lblBigEndian, GetFlag(PState.EFlag)); @@ -262,4 +261,4 @@ namespace ARMeilleure.Instructions SetIntA32(context, op.Rd, Const(op.Immediate)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitMemoryEx.cs b/src/ARMeilleure/Instructions/InstEmitMemoryEx.cs index c7ed01e34..8c95b33c5 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemoryEx.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemoryEx.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; using System.Diagnostics; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitMemoryExHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -15,10 +14,10 @@ namespace ARMeilleure.Instructions [Flags] private enum AccessType { - None = 0, - Ordered = 1, + None = 0, + Ordered = 1, Exclusive = 2, - OrderedEx = Ordered | Exclusive + OrderedEx = Ordered | Exclusive, } public static void Clrex(ArmEmitterContext context) @@ -34,10 +33,10 @@ namespace ARMeilleure.Instructions public static void Dmb(ArmEmitterContext context) => EmitBarrier(context); public static void Dsb(ArmEmitterContext context) => EmitBarrier(context); - public static void Ldar(ArmEmitterContext context) => EmitLdr(context, AccessType.Ordered); + public static void Ldar(ArmEmitterContext context) => EmitLdr(context, AccessType.Ordered); public static void Ldaxr(ArmEmitterContext context) => EmitLdr(context, AccessType.OrderedEx); - public static void Ldxr(ArmEmitterContext context) => EmitLdr(context, AccessType.Exclusive); - public static void Ldxp(ArmEmitterContext context) => EmitLdp(context, AccessType.Exclusive); + public static void Ldxr(ArmEmitterContext context) => EmitLdr(context, AccessType.Exclusive); + public static void Ldxp(ArmEmitterContext context) => EmitLdp(context, AccessType.Exclusive); public static void Ldaxp(ArmEmitterContext context) => EmitLdp(context, AccessType.OrderedEx); private static void EmitLdr(ArmEmitterContext context, AccessType accType) @@ -54,7 +53,7 @@ namespace ARMeilleure.Instructions { OpCodeMemEx op = (OpCodeMemEx)context.CurrOp; - bool ordered = (accType & AccessType.Ordered) != 0; + bool ordered = (accType & AccessType.Ordered) != 0; bool exclusive = (accType & AccessType.Exclusive) != 0; if (ordered) @@ -80,17 +79,17 @@ namespace ARMeilleure.Instructions Operand valueHigh = context.ShiftRightUI(value, Const(32)); - SetIntOrZR(context, op.Rt, valueLow); + SetIntOrZR(context, op.Rt, valueLow); SetIntOrZR(context, op.Rt2, valueHigh); } else if (op.Size == 3) { Operand value = EmitLoadExclusive(context, address, exclusive, 4); - Operand valueLow = context.VectorExtract(OperandType.I64, value, 0); + Operand valueLow = context.VectorExtract(OperandType.I64, value, 0); Operand valueHigh = context.VectorExtract(OperandType.I64, value, 1); - SetIntOrZR(context, op.Rt, valueLow); + SetIntOrZR(context, op.Rt, valueLow); SetIntOrZR(context, op.Rt2, valueHigh); } else @@ -112,10 +111,10 @@ namespace ARMeilleure.Instructions // Memory Prefetch, execute as no-op. } - public static void Stlr(ArmEmitterContext context) => EmitStr(context, AccessType.Ordered); + public static void Stlr(ArmEmitterContext context) => EmitStr(context, AccessType.Ordered); public static void Stlxr(ArmEmitterContext context) => EmitStr(context, AccessType.OrderedEx); - public static void Stxr(ArmEmitterContext context) => EmitStr(context, AccessType.Exclusive); - public static void Stxp(ArmEmitterContext context) => EmitStp(context, AccessType.Exclusive); + public static void Stxr(ArmEmitterContext context) => EmitStr(context, AccessType.Exclusive); + public static void Stxp(ArmEmitterContext context) => EmitStp(context, AccessType.Exclusive); public static void Stlxp(ArmEmitterContext context) => EmitStp(context, AccessType.OrderedEx); private static void EmitStr(ArmEmitterContext context, AccessType accType) @@ -132,7 +131,7 @@ namespace ARMeilleure.Instructions { OpCodeMemEx op = (OpCodeMemEx)context.CurrOp; - bool ordered = (accType & AccessType.Ordered) != 0; + bool ordered = (accType & AccessType.Ordered) != 0; bool exclusive = (accType & AccessType.Exclusive) != 0; Operand address = context.Copy(GetIntOrSP(context, op.Rn)); @@ -153,8 +152,8 @@ namespace ARMeilleure.Instructions } else /* if (op.Size == 3) */ { - value = context.VectorInsert(context.VectorZero(), t, 0); - value = context.VectorInsert(value, t2, 1); + value = context.VectorInsert(context.VectorZero(), t, 0); + value = context.VectorInsert(value, t2, 1); } EmitStoreExclusive(context, address, value, exclusive, op.Size + 1, op.Rs, a32: false); @@ -175,4 +174,4 @@ namespace ARMeilleure.Instructions context.MemoryBarrier(); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitMemoryExHelper.cs b/src/ARMeilleure/Instructions/InstEmitMemoryExHelper.cs index 9a69442a6..c9a99a3b5 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemoryExHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemoryExHelper.cs @@ -1,7 +1,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -33,7 +32,7 @@ namespace ARMeilleure.Instructions Operand arg0 = context.LoadArgument(OperandType.I64, 0); - Operand exAddrPtr = context.Add(arg0, Const((long)NativeContext.GetExclusiveAddressOffset())); + Operand exAddrPtr = context.Add(arg0, Const((long)NativeContext.GetExclusiveAddressOffset())); Operand exValuePtr = context.Add(arg0, Const((long)NativeContext.GetExclusiveValueOffset())); context.Store(exAddrPtr, context.BitwiseAnd(address, Const(address.Type, GetExclusiveAddressMask()))); @@ -118,14 +117,14 @@ namespace ARMeilleure.Instructions 1 => context.Load16(exValuePtr), 2 => context.Load(OperandType.I32, exValuePtr), 3 => context.Load(OperandType.I64, exValuePtr), - _ => context.Load(OperandType.V128, exValuePtr) + _ => context.Load(OperandType.V128, exValuePtr), }; Operand currValue = size switch { 0 => context.CompareAndSwap8(physAddr, exValue, value), 1 => context.CompareAndSwap16(physAddr, exValue, value), - _ => context.CompareAndSwap(physAddr, exValue, value) + _ => context.CompareAndSwap(physAddr, exValue, value), }; // STEP 3: Check if we succeeded by comparing expected and in-memory values. @@ -133,14 +132,14 @@ namespace ARMeilleure.Instructions if (size == 4) { - Operand currValueLow = context.VectorExtract(OperandType.I64, currValue, 0); + Operand currValueLow = context.VectorExtract(OperandType.I64, currValue, 0); Operand currValueHigh = context.VectorExtract(OperandType.I64, currValue, 1); - Operand exValueLow = context.VectorExtract(OperandType.I64, exValue, 0); + Operand exValueLow = context.VectorExtract(OperandType.I64, exValue, 0); Operand exValueHigh = context.VectorExtract(OperandType.I64, exValue, 1); storeFailed = context.BitwiseOr( - context.ICompareNotEqual(currValueLow, exValueLow), + context.ICompareNotEqual(currValueLow, exValueLow), context.ICompareNotEqual(currValueHigh, exValueHigh)); } else diff --git a/src/ARMeilleure/Instructions/InstEmitMemoryHelper.cs b/src/ARMeilleure/Instructions/InstEmitMemoryHelper.cs index f97e395ce..a807eed51 100644 --- a/src/ARMeilleure/Instructions/InstEmitMemoryHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitMemoryHelper.cs @@ -5,7 +5,6 @@ using ARMeilleure.Translation; using ARMeilleure.Translation.PTC; using System; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -20,7 +19,7 @@ namespace ARMeilleure.Instructions { Zx, Sx32, - Sx64 + Sx64, } public static void EmitLoadZx(ArmEmitterContext context, Operand address, int rt, int size) @@ -66,9 +65,15 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: value = context.SignExtend8 (destType, value); break; - case 1: value = context.SignExtend16(destType, value); break; - case 2: value = context.SignExtend32(destType, value); break; + case 0: + value = context.SignExtend8(destType, value); + break; + case 1: + value = context.SignExtend16(destType, value); + break; + case 2: + value = context.SignExtend32(destType, value); + break; } } @@ -128,7 +133,7 @@ namespace ARMeilleure.Instructions Operand temp = context.AllocateLocal(size == 3 ? OperandType.I64 : OperandType.I32); Operand lblSlowPath = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: false, size); @@ -136,10 +141,18 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: value = context.Load8 (physAddr); break; - case 1: value = context.Load16(physAddr); break; - case 2: value = context.Load (OperandType.I32, physAddr); break; - case 3: value = context.Load (OperandType.I64, physAddr); break; + case 0: + value = context.Load8(physAddr); + break; + case 1: + value = context.Load16(physAddr); + break; + case 2: + value = context.Load(OperandType.I32, physAddr); + break; + case 3: + value = context.Load(OperandType.I64, physAddr); + break; } context.Copy(temp, value); @@ -161,7 +174,7 @@ namespace ARMeilleure.Instructions private static void EmitReadInt(ArmEmitterContext context, Operand address, int rt, int size) { Operand lblSlowPath = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: false, size); @@ -169,10 +182,18 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: value = context.Load8 (physAddr); break; - case 1: value = context.Load16(physAddr); break; - case 2: value = context.Load (OperandType.I32, physAddr); break; - case 3: value = context.Load (OperandType.I64, physAddr); break; + case 0: + value = context.Load8(physAddr); + break; + case 1: + value = context.Load16(physAddr); + break; + case 2: + value = context.Load(OperandType.I32, physAddr); + break; + case 3: + value = context.Load(OperandType.I64, physAddr); + break; } SetInt(context, rt, value); @@ -204,7 +225,7 @@ namespace ARMeilleure.Instructions 1 => context.Load16(physAddr), 2 => context.Load(OperandType.I32, physAddr), 3 => context.Load(OperandType.I64, physAddr), - _ => context.Load(OperandType.V128, physAddr) + _ => context.Load(OperandType.V128, physAddr), }; } @@ -217,7 +238,7 @@ namespace ARMeilleure.Instructions int size) { Operand lblSlowPath = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: false, size); @@ -225,11 +246,21 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: value = context.VectorInsert8 (vector, context.Load8(physAddr), elem); break; - case 1: value = context.VectorInsert16(vector, context.Load16(physAddr), elem); break; - case 2: value = context.VectorInsert (vector, context.Load(OperandType.I32, physAddr), elem); break; - case 3: value = context.VectorInsert (vector, context.Load(OperandType.I64, physAddr), elem); break; - case 4: value = context.Load (OperandType.V128, physAddr); break; + case 0: + value = context.VectorInsert8(vector, context.Load8(physAddr), elem); + break; + case 1: + value = context.VectorInsert16(vector, context.Load16(physAddr), elem); + break; + case 2: + value = context.VectorInsert(vector, context.Load(OperandType.I32, physAddr), elem); + break; + case 3: + value = context.VectorInsert(vector, context.Load(OperandType.I64, physAddr), elem); + break; + case 4: + value = context.Load(OperandType.V128, physAddr); + break; } context.Copy(GetVec(rt), value); @@ -254,7 +285,7 @@ namespace ARMeilleure.Instructions private static void EmitWriteInt(ArmEmitterContext context, Operand address, int rt, int size) { Operand lblSlowPath = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: true, size); @@ -267,10 +298,18 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: context.Store8 (physAddr, value); break; - case 1: context.Store16(physAddr, value); break; - case 2: context.Store (physAddr, value); break; - case 3: context.Store (physAddr, value); break; + case 0: + context.Store8(physAddr, value); + break; + case 1: + context.Store16(physAddr, value); + break; + case 2: + context.Store(physAddr, value); + break; + case 3: + context.Store(physAddr, value); + break; } if (!context.Memory.Type.IsHostMapped()) @@ -321,7 +360,7 @@ namespace ARMeilleure.Instructions int size) { Operand lblSlowPath = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); Operand physAddr = EmitPtPointerLoad(context, address, lblSlowPath, write: true, size); @@ -329,11 +368,21 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: context.Store8 (physAddr, context.VectorExtract8(value, elem)); break; - case 1: context.Store16(physAddr, context.VectorExtract16(value, elem)); break; - case 2: context.Store (physAddr, context.VectorExtract(OperandType.I32, value, elem)); break; - case 3: context.Store (physAddr, context.VectorExtract(OperandType.I64, value, elem)); break; - case 4: context.Store (physAddr, value); break; + case 0: + context.Store8(physAddr, context.VectorExtract8(value, elem)); + break; + case 1: + context.Store16(physAddr, context.VectorExtract16(value, elem)); + break; + case 2: + context.Store(physAddr, context.VectorExtract(OperandType.I32, value, elem)); + break; + case 3: + context.Store(physAddr, context.VectorExtract(OperandType.I64, value, elem)); + break; + case 4: + context.Store(physAddr, value); + break; } if (!context.Memory.Type.IsHostMapped()) @@ -464,10 +513,18 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadByte)); break; - case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt16)); break; - case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt32)); break; - case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt64)); break; + case 0: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadByte)); + break; + case 1: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt16)); + break; + case 2: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt32)); + break; + case 3: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt64)); + break; } return context.Call(info, address); @@ -485,21 +542,39 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadByte)); break; - case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt16)); break; - case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt32)); break; - case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt64)); break; - case 4: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadVector128)); break; + case 0: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadByte)); + break; + case 1: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt16)); + break; + case 2: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt32)); + break; + case 3: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadUInt64)); + break; + case 4: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.ReadVector128)); + break; } Operand value = context.Call(info, address); switch (size) { - case 0: value = context.VectorInsert8 (vector, value, elem); break; - case 1: value = context.VectorInsert16(vector, value, elem); break; - case 2: value = context.VectorInsert (vector, value, elem); break; - case 3: value = context.VectorInsert (vector, value, elem); break; + case 0: + value = context.VectorInsert8(vector, value, elem); + break; + case 1: + value = context.VectorInsert16(vector, value, elem); + break; + case 2: + value = context.VectorInsert(vector, value, elem); + break; + case 3: + value = context.VectorInsert(vector, value, elem); + break; } context.Copy(GetVec(rt), value); @@ -511,10 +586,18 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteByte)); break; - case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt16)); break; - case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt32)); break; - case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt64)); break; + case 0: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteByte)); + break; + case 1: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt16)); + break; + case 2: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt32)); + break; + case 3: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt64)); + break; } Operand value = GetInt(context, rt); @@ -538,11 +621,21 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteByte)); break; - case 1: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt16)); break; - case 2: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt32)); break; - case 3: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt64)); break; - case 4: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteVector128)); break; + case 0: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteByte)); + break; + case 1: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt16)); + break; + case 2: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt32)); + break; + case 3: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteUInt64)); + break; + case 4: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.WriteVector128)); + break; } Operand value = default; @@ -551,10 +644,18 @@ namespace ARMeilleure.Instructions { switch (size) { - case 0: value = context.VectorExtract8 (GetVec(rt), elem); break; - case 1: value = context.VectorExtract16(GetVec(rt), elem); break; - case 2: value = context.VectorExtract (OperandType.I32, GetVec(rt), elem); break; - case 3: value = context.VectorExtract (OperandType.I64, GetVec(rt), elem); break; + case 0: + value = context.VectorExtract8(GetVec(rt), elem); + break; + case 1: + value = context.VectorExtract16(GetVec(rt), elem); + break; + case 2: + value = context.VectorExtract(OperandType.I32, GetVec(rt), elem); + break; + case 3: + value = context.VectorExtract(OperandType.I64, GetVec(rt), elem); + break; } } else @@ -585,18 +686,14 @@ namespace ARMeilleure.Instructions // ARM32 helpers. public static Operand GetMemM(ArmEmitterContext context, bool setCarry = true) { - switch (context.CurrOp) + return context.CurrOp switch { - case IOpCode32MemRsImm op: return GetMShiftedByImmediate(context, op, setCarry); - - case IOpCode32MemReg op: return GetIntA32(context, op.Rm); - - case IOpCode32Mem op: return Const(op.Immediate); - - case OpCode32SimdMemImm op: return Const(op.Immediate); - - default: throw InvalidOpCodeType(context.CurrOp); - } + IOpCode32MemRsImm op => GetMShiftedByImmediate(context, op, setCarry), + IOpCode32MemReg op => GetIntA32(context, op.Rm), + IOpCode32Mem op => Const(op.Immediate), + OpCode32SimdMemImm op => Const(op.Immediate), + _ => throw InvalidOpCodeType(context.CurrOp), + }; } private static Exception InvalidOpCodeType(OpCode opCode) @@ -614,9 +711,15 @@ namespace ARMeilleure.Instructions { switch (op.ShiftType) { - case ShiftType.Lsr: shift = 32; break; - case ShiftType.Asr: shift = 32; break; - case ShiftType.Ror: shift = 1; break; + case ShiftType.Lsr: + shift = 32; + break; + case ShiftType.Asr: + shift = 32; + break; + case ShiftType.Ror: + shift = 1; + break; } } @@ -626,9 +729,15 @@ namespace ARMeilleure.Instructions switch (op.ShiftType) { - case ShiftType.Lsl: m = InstEmitAluHelper.GetLslC(context, m, setCarry, shift); break; - case ShiftType.Lsr: m = InstEmitAluHelper.GetLsrC(context, m, setCarry, shift); break; - case ShiftType.Asr: m = InstEmitAluHelper.GetAsrC(context, m, setCarry, shift); break; + case ShiftType.Lsl: + m = InstEmitAluHelper.GetLslC(context, m, setCarry, shift); + break; + case ShiftType.Lsr: + m = InstEmitAluHelper.GetLsrC(context, m, setCarry, shift); + break; + case ShiftType.Asr: + m = InstEmitAluHelper.GetAsrC(context, m, setCarry, shift); + break; case ShiftType.Ror: if (op.Immediate != 0) { diff --git a/src/ARMeilleure/Instructions/InstEmitMove.cs b/src/ARMeilleure/Instructions/InstEmitMove.cs index d551bf2da..f23ac333b 100644 --- a/src/ARMeilleure/Instructions/InstEmitMove.cs +++ b/src/ARMeilleure/Instructions/InstEmitMove.cs @@ -38,4 +38,4 @@ namespace ARMeilleure.Instructions SetIntOrZR(context, op.Rd, Const(op.GetOperandType(), op.Immediate)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitMul.cs b/src/ARMeilleure/Instructions/InstEmitMul.cs index 65d11b30d..89dc09938 100644 --- a/src/ARMeilleure/Instructions/InstEmitMul.cs +++ b/src/ARMeilleure/Instructions/InstEmitMul.cs @@ -2,7 +2,7 @@ using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; - +using System.Diagnostics.CodeAnalysis; using static ARMeilleure.Instructions.InstEmitHelper; namespace ARMeilleure.Instructions @@ -33,14 +33,15 @@ namespace ARMeilleure.Instructions public static void Umsubl(ArmEmitterContext context) => EmitMull(context, MullFlags.Subtract); [Flags] + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] private enum MullFlags { Subtract = 0, - Add = 1 << 0, - Signed = 1 << 1, + Add = 1 << 0, + Signed = 1 << 1, - SignedAdd = Signed | Add, - SignedSubtract = Signed | Subtract + SignedAdd = Signed | Add, + SignedSubtract = Signed | Subtract, } private static void EmitMull(ArmEmitterContext context, MullFlags flags) @@ -97,4 +98,4 @@ namespace ARMeilleure.Instructions SetIntOrZR(context, op.Rd, d); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitMul32.cs b/src/ARMeilleure/Instructions/InstEmitMul32.cs index 0822f92c3..b9680fb69 100644 --- a/src/ARMeilleure/Instructions/InstEmitMul32.cs +++ b/src/ARMeilleure/Instructions/InstEmitMul32.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System; - using static ARMeilleure.Instructions.InstEmitAluHelper; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -20,7 +19,7 @@ namespace ARMeilleure.Instructions Signed = 1 << 2, SignedAdd = Signed | Add, - SignedSubtract = Signed | Subtract + SignedSubtract = Signed | Subtract, } public static void Mla(ArmEmitterContext context) @@ -287,14 +286,14 @@ namespace ARMeilleure.Instructions { IOpCode32AluUmull op = (IOpCode32AluUmull)context.CurrOp; - Operand n = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rn)); - Operand m = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rm)); + Operand n = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rn)); + Operand m = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.Rm)); Operand dHi = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.RdHi)); Operand dLo = context.ZeroExtend32(OperandType.I64, GetIntA32(context, op.RdLo)); Operand res = context.Multiply(n, m); - res = context.Add(res, dHi); - res = context.Add(res, dLo); + res = context.Add(res, dHi); + res = context.Add(res, dLo); Operand hi = context.ConvertI64ToI32(context.ShiftRightUI(res, Const(32))); Operand lo = context.ConvertI64ToI32(res); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdArithmetic.cs b/src/ARMeilleure/Instructions/InstEmitSimdArithmetic.cs index 7e7f26b1a..543aab023 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdArithmetic.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdArithmetic.cs @@ -7,7 +7,6 @@ using ARMeilleure.State; using ARMeilleure.Translation; using System; using System.Diagnostics; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper32; @@ -185,11 +184,12 @@ namespace ARMeilleure.Instructions int eSize = 8 << op.Size; - Operand res = eSize switch { - 8 => Clz_V_I8 (context, GetVec(op.Rn)), + Operand res = eSize switch + { + 8 => Clz_V_I8(context, GetVec(op.Rn)), 16 => Clz_V_I16(context, GetVec(op.Rn)), 32 => Clz_V_I32(context, GetVec(op.Rn)), - _ => default + _ => default, }; if (res != default) @@ -230,14 +230,14 @@ namespace ARMeilleure.Instructions Operand clzTable = X86GetScalar(context, 0x01_01_01_01_02_02_03_04); Operand maskLow = X86GetAllElements(context, 0x0f_0f_0f_0f); - Operand c04 = X86GetAllElements(context, 0x04_04_04_04); + Operand c04 = X86GetAllElements(context, 0x04_04_04_04); // CLZ of low 4 bits of elements in arg. Operand loClz = context.AddIntrinsic(Intrinsic.X86Pshufb, clzTable, arg); // Get the high 4 bits of elements in arg. Operand hiArg = context.AddIntrinsic(Intrinsic.X86Psrlw, arg, Const(4)); - hiArg = context.AddIntrinsic(Intrinsic.X86Pand, hiArg, maskLow); + hiArg = context.AddIntrinsic(Intrinsic.X86Pand, hiArg, maskLow); // CLZ of high 4 bits of elements in arg. Operand hiClz = context.AddIntrinsic(Intrinsic.X86Pshufb, clzTable, hiArg); @@ -257,8 +257,8 @@ namespace ARMeilleure.Instructions } Operand maskSwap = X86GetElements(context, 0x80_0f_80_0d_80_0b_80_09, 0x80_07_80_05_80_03_80_01); - Operand maskLow = X86GetAllElements(context, 0x00ff_00ff); - Operand c0008 = X86GetAllElements(context, 0x0008_0008); + Operand maskLow = X86GetAllElements(context, 0x00ff_00ff); + Operand c0008 = X86GetAllElements(context, 0x0008_0008); // CLZ pair of high 8 and low 8 bits of elements in arg. Operand hiloClz = Clz_V_I8(context, arg); @@ -282,12 +282,14 @@ namespace ARMeilleure.Instructions return default; } +#pragma warning disable IDE0055 // Disable formatting Operand AddVectorI32(Operand op0, Operand op1) => context.AddIntrinsic(Intrinsic.X86Paddd, op0, op1); Operand SubVectorI32(Operand op0, Operand op1) => context.AddIntrinsic(Intrinsic.X86Psubd, op0, op1); Operand ShiftRightVectorUI32(Operand op0, int imm8) => context.AddIntrinsic(Intrinsic.X86Psrld, op0, Const(imm8)); Operand OrVector(Operand op0, Operand op1) => context.AddIntrinsic(Intrinsic.X86Por, op0, op1); Operand AndVector(Operand op0, Operand op1) => context.AddIntrinsic(Intrinsic.X86Pand, op0, op1); Operand NotVector(Operand op0) => context.AddIntrinsic(Intrinsic.X86Pandn, op0, context.VectorOne()); +#pragma warning restore IDE0055 Operand c55555555 = X86GetAllElements(context, 0x55555555); Operand c33333333 = X86GetAllElements(context, 0x33333333); @@ -311,24 +313,24 @@ namespace ARMeilleure.Instructions // Count leading 1s, which is the population count. tmp0 = ShiftRightVectorUI32(res, 1); tmp0 = AndVector(tmp0, c55555555); - res = SubVectorI32(res, tmp0); + res = SubVectorI32(res, tmp0); tmp0 = ShiftRightVectorUI32(res, 2); tmp0 = AndVector(tmp0, c33333333); tmp1 = AndVector(res, c33333333); - res = AddVectorI32(tmp0, tmp1); + res = AddVectorI32(tmp0, tmp1); tmp0 = ShiftRightVectorUI32(res, 4); tmp0 = AddVectorI32(tmp0, res); - res = AndVector(tmp0, c0f0f0f0f); + res = AndVector(tmp0, c0f0f0f0f); tmp0 = ShiftRightVectorUI32(res, 8); - res = AddVectorI32(tmp0, res); + res = AddVectorI32(tmp0, res); tmp0 = ShiftRightVectorUI32(res, 16); - res = AddVectorI32(tmp0, res); + res = AddVectorI32(tmp0, res); - res = AndVector(res, c0000003f); + res = AndVector(res, c0000003f); return res; } @@ -881,6 +883,31 @@ namespace ARMeilleure.Instructions } } + public static void Fmaxp_S(ArmEmitterContext context) + { + if (Optimizations.UseAdvSimd) + { + InstEmitSimdHelperArm64.EmitScalarUnaryOpF(context, Intrinsic.Arm64FmaxpS); + } + else if (Optimizations.FastFP && Optimizations.UseSse41) + { + EmitSse2ScalarPairwiseOpF(context, (op1, op2) => + { + return EmitSse41ProcessNaNsOpF(context, (op1, op2) => + { + return EmitSse2VectorMaxMinOpF(context, op1, op2, isMax: true); + }, scalar: true, op1, op2); + }); + } + else + { + EmitScalarPairwiseOpF(context, (op1, op2) => + { + return EmitSoftFloatCall(context, nameof(SoftFloat32.FPMax), op1, op2); + }); + } + } + public static void Fmaxp_V(ArmEmitterContext context) { if (Optimizations.UseAdvSimd) @@ -1079,6 +1106,31 @@ namespace ARMeilleure.Instructions } } + public static void Fminp_S(ArmEmitterContext context) + { + if (Optimizations.UseAdvSimd) + { + InstEmitSimdHelperArm64.EmitScalarUnaryOpF(context, Intrinsic.Arm64FminpS); + } + else if (Optimizations.FastFP && Optimizations.UseSse41) + { + EmitSse2ScalarPairwiseOpF(context, (op1, op2) => + { + return EmitSse41ProcessNaNsOpF(context, (op1, op2) => + { + return EmitSse2VectorMaxMinOpF(context, op1, op2, isMax: false); + }, scalar: true, op1, op2); + }); + } + else + { + EmitScalarPairwiseOpF(context, (op1, op2) => + { + return EmitSoftFloatCall(context, nameof(SoftFloat32.FPMin), op1, op2); + }); + } + } + public static void Fminp_V(ArmEmitterContext context) { if (Optimizations.UseAdvSimd) @@ -2436,8 +2488,8 @@ namespace ARMeilleure.Instructions if (sizeF == 0) { - Operand maskHalf = X86GetScalar(context, 0.5f); - Operand maskThree = X86GetScalar(context, 3f); + Operand maskHalf = X86GetScalar(context, 0.5f); + Operand maskThree = X86GetScalar(context, 3f); Operand maskOneHalf = X86GetScalar(context, 1.5f); if (Optimizations.UseFma) @@ -2457,8 +2509,8 @@ namespace ARMeilleure.Instructions } else /* if (sizeF == 1) */ { - Operand maskHalf = X86GetScalar(context, 0.5d); - Operand maskThree = X86GetScalar(context, 3d); + Operand maskHalf = X86GetScalar(context, 0.5d); + Operand maskThree = X86GetScalar(context, 3d); Operand maskOneHalf = X86GetScalar(context, 1.5d); if (Optimizations.UseFma) @@ -2505,8 +2557,8 @@ namespace ARMeilleure.Instructions if (sizeF == 0) { - Operand maskHalf = X86GetAllElements(context, 0.5f); - Operand maskThree = X86GetAllElements(context, 3f); + Operand maskHalf = X86GetAllElements(context, 0.5f); + Operand maskThree = X86GetAllElements(context, 3f); Operand maskOneHalf = X86GetAllElements(context, 1.5f); if (Optimizations.UseFma) @@ -2519,7 +2571,7 @@ namespace ARMeilleure.Instructions res = context.AddIntrinsic(Intrinsic.X86Subps, maskThree, res); } - res = context.AddIntrinsic(Intrinsic.X86Mulps, maskHalf, res); + res = context.AddIntrinsic(Intrinsic.X86Mulps, maskHalf, res); res = EmitSse41RecipStepSelectOpF(context, n, m, res, maskOneHalf, scalar: false, sizeF); if (op.RegisterSize == RegisterSize.Simd64) @@ -2531,8 +2583,8 @@ namespace ARMeilleure.Instructions } else /* if (sizeF == 1) */ { - Operand maskHalf = X86GetAllElements(context, 0.5d); - Operand maskThree = X86GetAllElements(context, 3d); + Operand maskHalf = X86GetAllElements(context, 0.5d); + Operand maskThree = X86GetAllElements(context, 3d); Operand maskOneHalf = X86GetAllElements(context, 1.5d); if (Optimizations.UseFma) @@ -2545,7 +2597,7 @@ namespace ARMeilleure.Instructions res = context.AddIntrinsic(Intrinsic.X86Subpd, maskThree, res); } - res = context.AddIntrinsic(Intrinsic.X86Mulpd, maskHalf, res); + res = context.AddIntrinsic(Intrinsic.X86Mulpd, maskHalf, res); res = EmitSse41RecipStepSelectOpF(context, n, m, res, maskOneHalf, scalar: false, sizeF); context.Copy(GetVec(op.Rd), res); @@ -2824,10 +2876,10 @@ namespace ARMeilleure.Instructions for (int i = 0; i < 8; i++) { Operand mask = context.AddIntrinsic(Intrinsic.X86Psllw, n, Const(15 - i)); - mask = context.AddIntrinsic(Intrinsic.X86Psraw, mask, Const(15)); + mask = context.AddIntrinsic(Intrinsic.X86Psraw, mask, Const(15)); Operand tmp = context.AddIntrinsic(Intrinsic.X86Psllw, m, Const(i)); - tmp = context.AddIntrinsic(Intrinsic.X86Pand, tmp, mask); + tmp = context.AddIntrinsic(Intrinsic.X86Pand, tmp, mask); res = context.AddIntrinsic(Intrinsic.X86Pxor, res, tmp); } @@ -2839,12 +2891,12 @@ namespace ARMeilleure.Instructions for (int i = 0; i < 64; i++) { Operand mask = context.AddIntrinsic(Intrinsic.X86Movlhps, n, n); - mask = context.AddIntrinsic(Intrinsic.X86Psllq, mask, Const(63 - i)); - mask = context.AddIntrinsic(Intrinsic.X86Psrlq, mask, Const(63)); - mask = context.AddIntrinsic(Intrinsic.X86Psubq, zero, mask); + mask = context.AddIntrinsic(Intrinsic.X86Psllq, mask, Const(63 - i)); + mask = context.AddIntrinsic(Intrinsic.X86Psrlq, mask, Const(63)); + mask = context.AddIntrinsic(Intrinsic.X86Psubq, zero, mask); Operand tmp = EmitSse2Sll_128(context, m, i); - tmp = context.AddIntrinsic(Intrinsic.X86Pand, tmp, mask); + tmp = context.AddIntrinsic(Intrinsic.X86Pand, tmp, mask); res = context.AddIntrinsic(Intrinsic.X86Pxor, res, tmp); } @@ -3119,7 +3171,7 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand m = GetVec(op.Rm); - Operand res = context.AddIntrinsic(Intrinsic.X86Pand, n, m); + Operand res = context.AddIntrinsic(Intrinsic.X86Pand, n, m); Operand res2 = context.AddIntrinsic(Intrinsic.X86Pxor, n, m); Intrinsic shiftInst = op.Size == 1 ? Intrinsic.X86Psraw : Intrinsic.X86Psrad; @@ -4058,7 +4110,7 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand m = GetVec(op.Rm); - Operand res = context.AddIntrinsic(Intrinsic.X86Pand, n, m); + Operand res = context.AddIntrinsic(Intrinsic.X86Pand, n, m); Operand res2 = context.AddIntrinsic(Intrinsic.X86Pxor, n, m); Intrinsic shiftInst = op.Size == 1 ? Intrinsic.X86Psrlw : Intrinsic.X86Psrld; @@ -4594,7 +4646,7 @@ namespace ARMeilleure.Instructions { int pairIndex = index << 1; - Operand ne0 = EmitVectorExtract(context, op.Rn, pairIndex, op.Size, signed); + Operand ne0 = EmitVectorExtract(context, op.Rn, pairIndex, op.Size, signed); Operand ne1 = EmitVectorExtract(context, op.Rn, pairIndex + 1, op.Size, signed); Operand e = context.Add(ne0, ne1); @@ -4686,7 +4738,7 @@ namespace ARMeilleure.Instructions Debug.Assert(op1.Type == OperandType.I64 && op2.Type == OperandType.I64); Operand cmp = signed - ? context.ICompareGreaterOrEqual (op1, op2) + ? context.ICompareGreaterOrEqual(op1, op2) : context.ICompareGreaterOrEqualUI(op1, op2); return context.ConditionalSelect(cmp, op1, op2); @@ -4697,7 +4749,7 @@ namespace ARMeilleure.Instructions Debug.Assert(op1.Type == OperandType.I64 && op2.Type == OperandType.I64); Operand cmp = signed - ? context.ICompareLessOrEqual (op1, op2) + ? context.ICompareLessOrEqual(op1, op2) : context.ICompareLessOrEqualUI(op1, op2); return context.ConditionalSelect(cmp, op1, op2); @@ -4852,10 +4904,10 @@ namespace ARMeilleure.Instructions Operand mask1 = context.AddIntrinsic(Intrinsic.X86Cmpps, opF, opF, Const((int)CmpCondition.UnorderedQ)); - Operand mask2 = context.AddIntrinsic(Intrinsic.X86Pand, opF, qMask); - mask2 = context.AddIntrinsic(Intrinsic.X86Cmpps, mask2, qMask, Const((int)CmpCondition.Equal)); + Operand mask2 = context.AddIntrinsic(Intrinsic.X86Pand, opF, qMask); + mask2 = context.AddIntrinsic(Intrinsic.X86Cmpps, mask2, qMask, Const((int)CmpCondition.Equal)); - qNaNMask = isQNaN == null || (bool)isQNaN ? context.AddIntrinsic(Intrinsic.X86Andps, mask2, mask1) : default; + qNaNMask = isQNaN == null || (bool)isQNaN ? context.AddIntrinsic(Intrinsic.X86Andps, mask2, mask1) : default; sNaNMask = isQNaN == null || !(bool)isQNaN ? context.AddIntrinsic(Intrinsic.X86Andnps, mask2, mask1) : default; } else /* if ((op.Size & 1) == 1) */ @@ -4866,10 +4918,10 @@ namespace ARMeilleure.Instructions Operand mask1 = context.AddIntrinsic(Intrinsic.X86Cmppd, opF, opF, Const((int)CmpCondition.UnorderedQ)); - Operand mask2 = context.AddIntrinsic(Intrinsic.X86Pand, opF, qMask); - mask2 = context.AddIntrinsic(Intrinsic.X86Cmppd, mask2, qMask, Const((int)CmpCondition.Equal)); + Operand mask2 = context.AddIntrinsic(Intrinsic.X86Pand, opF, qMask); + mask2 = context.AddIntrinsic(Intrinsic.X86Cmppd, mask2, qMask, Const((int)CmpCondition.Equal)); - qNaNMask = isQNaN == null || (bool)isQNaN ? context.AddIntrinsic(Intrinsic.X86Andpd, mask2, mask1) : default; + qNaNMask = isQNaN == null || (bool)isQNaN ? context.AddIntrinsic(Intrinsic.X86Andpd, mask2, mask1) : default; sNaNMask = isQNaN == null || !(bool)isQNaN ? context.AddIntrinsic(Intrinsic.X86Andnpd, mask2, mask1) : default; } } @@ -4895,11 +4947,11 @@ namespace ARMeilleure.Instructions Operand qMask = scalar ? X86GetScalar(context, 1 << QBit) : X86GetAllElements(context, 1 << QBit); - Operand resNaNMask = context.AddIntrinsic(Intrinsic.X86Pandn, mSNaNMask, nQNaNMask); - resNaNMask = context.AddIntrinsic(Intrinsic.X86Por, resNaNMask, nSNaNMask); + Operand resNaNMask = context.AddIntrinsic(Intrinsic.X86Pandn, mSNaNMask, nQNaNMask); + resNaNMask = context.AddIntrinsic(Intrinsic.X86Por, resNaNMask, nSNaNMask); Operand resNaN = context.AddIntrinsic(Intrinsic.X86Blendvps, mCopy, nCopy, resNaNMask); - resNaN = context.AddIntrinsic(Intrinsic.X86Por, resNaN, qMask); + resNaN = context.AddIntrinsic(Intrinsic.X86Por, resNaN, qMask); Operand resMask = context.AddIntrinsic(Intrinsic.X86Cmpps, nCopy, mCopy, Const((int)CmpCondition.OrderedQ)); @@ -4929,11 +4981,11 @@ namespace ARMeilleure.Instructions Operand qMask = scalar ? X86GetScalar(context, 1L << QBit) : X86GetAllElements(context, 1L << QBit); - Operand resNaNMask = context.AddIntrinsic(Intrinsic.X86Pandn, mSNaNMask, nQNaNMask); - resNaNMask = context.AddIntrinsic(Intrinsic.X86Por, resNaNMask, nSNaNMask); + Operand resNaNMask = context.AddIntrinsic(Intrinsic.X86Pandn, mSNaNMask, nQNaNMask); + resNaNMask = context.AddIntrinsic(Intrinsic.X86Por, resNaNMask, nSNaNMask); Operand resNaN = context.AddIntrinsic(Intrinsic.X86Blendvpd, mCopy, nCopy, resNaNMask); - resNaN = context.AddIntrinsic(Intrinsic.X86Por, resNaN, qMask); + resNaN = context.AddIntrinsic(Intrinsic.X86Por, resNaN, qMask); Operand resMask = context.AddIntrinsic(Intrinsic.X86Cmppd, nCopy, mCopy, Const((int)CmpCondition.OrderedQ)); @@ -4964,10 +5016,10 @@ namespace ARMeilleure.Instructions Operand mask = X86GetAllElements(context, -0f); Operand res = context.AddIntrinsic(isMax ? Intrinsic.X86Maxps : Intrinsic.X86Minps, n, m); - res = context.AddIntrinsic(Intrinsic.X86Andnps, mask, res); + res = context.AddIntrinsic(Intrinsic.X86Andnps, mask, res); Operand resSign = context.AddIntrinsic(isMax ? Intrinsic.X86Pand : Intrinsic.X86Por, n, m); - resSign = context.AddIntrinsic(Intrinsic.X86Andps, mask, resSign); + resSign = context.AddIntrinsic(Intrinsic.X86Andps, mask, resSign); return context.AddIntrinsic(Intrinsic.X86Por, res, resSign); } @@ -4976,10 +5028,10 @@ namespace ARMeilleure.Instructions Operand mask = X86GetAllElements(context, -0d); Operand res = context.AddIntrinsic(isMax ? Intrinsic.X86Maxpd : Intrinsic.X86Minpd, n, m); - res = context.AddIntrinsic(Intrinsic.X86Andnpd, mask, res); + res = context.AddIntrinsic(Intrinsic.X86Andnpd, mask, res); Operand resSign = context.AddIntrinsic(isMax ? Intrinsic.X86Pand : Intrinsic.X86Por, n, m); - resSign = context.AddIntrinsic(Intrinsic.X86Andpd, mask, resSign); + resSign = context.AddIntrinsic(Intrinsic.X86Andpd, mask, resSign); return context.AddIntrinsic(Intrinsic.X86Por, res, resSign); } @@ -5003,7 +5055,7 @@ namespace ARMeilleure.Instructions if (sizeF == 0) { Operand negInfMask = scalar - ? X86GetScalar (context, isMaxNum ? float.NegativeInfinity : float.PositiveInfinity) + ? X86GetScalar(context, isMaxNum ? float.NegativeInfinity : float.PositiveInfinity) : X86GetAllElements(context, isMaxNum ? float.NegativeInfinity : float.PositiveInfinity); Operand nMask = context.AddIntrinsic(Intrinsic.X86Andnps, mQNaNMask, nQNaNMask); @@ -5038,7 +5090,7 @@ namespace ARMeilleure.Instructions else /* if (sizeF == 1) */ { Operand negInfMask = scalar - ? X86GetScalar (context, isMaxNum ? double.NegativeInfinity : double.PositiveInfinity) + ? X86GetScalar(context, isMaxNum ? double.NegativeInfinity : double.PositiveInfinity) : X86GetAllElements(context, isMaxNum ? double.NegativeInfinity : double.PositiveInfinity); Operand nMask = context.AddIntrinsic(Intrinsic.X86Andnpd, mQNaNMask, nQNaNMask); @@ -5072,7 +5124,7 @@ namespace ARMeilleure.Instructions { None, Add, - Subtract + Subtract, } private static void EmitSse41VectorMul_AddSub(ArmEmitterContext context, AddSub addSub) @@ -5187,10 +5239,10 @@ namespace ARMeilleure.Instructions Intrinsic subInst = X86PsubInstruction[size]; - Operand res = context.AddIntrinsic(subInst, n, m); + Operand res = context.AddIntrinsic(subInst, n, m); Operand res2 = context.AddIntrinsic(subInst, m, n); - res = context.AddIntrinsic(Intrinsic.X86Pand, cmpMask, res); + res = context.AddIntrinsic(Intrinsic.X86Pand, cmpMask, res); res2 = context.AddIntrinsic(Intrinsic.X86Pandn, cmpMask, res2); res = context.AddIntrinsic(Intrinsic.X86Por, res, res2); @@ -5214,7 +5266,7 @@ namespace ARMeilleure.Instructions } Operand high = context.AddIntrinsic(Intrinsic.X86Pslldq, op, Const(8)); - high = context.AddIntrinsic(Intrinsic.X86Psrlq, high, Const(64 - shift)); + high = context.AddIntrinsic(Intrinsic.X86Psrlq, high, Const(64 - shift)); Operand low = context.AddIntrinsic(Intrinsic.X86Psllq, op, Const(shift)); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdArithmetic32.cs b/src/ARMeilleure/Instructions/InstEmitSimdArithmetic32.cs index a9994e412..1d99cbc3d 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdArithmetic32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdArithmetic32.cs @@ -2,7 +2,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; - using static ARMeilleure.Instructions.InstEmitFlowHelper; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; @@ -190,7 +189,7 @@ namespace ARMeilleure.Instructions 2 => context.Multiply(context.ZeroExtend32(OperandType.I64, insert), Const(0x0000000100000001u)), 1 => context.Multiply(context.ZeroExtend16(OperandType.I64, insert), Const(0x0001000100010001u)), 0 => context.Multiply(context.ZeroExtend8(OperandType.I64, insert), Const(0x0101010101010101u)), - _ => throw new InvalidOperationException($"Invalid Vdup size \"{op.Size}\".") + _ => throw new InvalidOperationException($"Invalid Vdup size \"{op.Size}\"."), }; InsertScalar(context, op.Vd, insert); @@ -212,7 +211,7 @@ namespace ARMeilleure.Instructions 2 => context.Multiply(context.ZeroExtend32(OperandType.I64, insert), Const(0x0000000100000001u)), 1 => context.Multiply(context.ZeroExtend16(OperandType.I64, insert), Const(0x0001000100010001u)), 0 => context.Multiply(context.ZeroExtend8(OperandType.I64, insert), Const(0x0101010101010101u)), - _ => throw new InvalidOperationException($"Invalid Vdup size \"{op.Size}\".") + _ => throw new InvalidOperationException($"Invalid Vdup size \"{op.Size}\"."), }; InsertScalar(context, op.Vd, insert); @@ -1654,7 +1653,7 @@ namespace ARMeilleure.Instructions { IOpCode32Simd op = (IOpCode32Simd)context.CurrOp; - Func genericEmit = (n, m) => + Operand genericEmit(Operand n, Operand m) { Operand nNum = context.Copy(n); Operand mNum = context.Copy(m); @@ -1688,7 +1687,7 @@ namespace ARMeilleure.Instructions return context.AddIntrinsic(isMaxNum ? Intrinsic.X86Maxpd : Intrinsic.X86Minpd, nNum, mNum); } - }; + } if (scalar) { diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCmp.cs b/src/ARMeilleure/Instructions/InstEmitSimdCmp.cs index c32b64ba1..aab677869 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCmp.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCmp.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -493,7 +492,7 @@ namespace ARMeilleure.Instructions OpCodeSimdFcond op = (OpCodeSimdFcond)context.CurrOp; Operand lblTrue = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); context.BranchIfTrue(lblTrue, InstEmitFlowHelper.GetCondTrue(context, op.Cond)); @@ -510,7 +509,7 @@ namespace ARMeilleure.Instructions private static void EmitSetNzcv(ArmEmitterContext context, int nzcv) { - Operand Extract(int value, int bit) + static Operand Extract(int value, int bit) { if (bit != 0) { @@ -532,7 +531,7 @@ namespace ARMeilleure.Instructions { OpCodeSimdReg op = (OpCodeSimdReg)context.CurrOp; - bool cmpWithZero = !(op is OpCodeSimdFcond) ? op.Bit3 : false; + bool cmpWithZero = op is not OpCodeSimdFcond && op.Bit3; if (Optimizations.FastFP && (signalNaNs ? Optimizations.UseAvx : Optimizations.UseSse2)) { diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCrypto.cs b/src/ARMeilleure/Instructions/InstEmitSimdCrypto.cs index db24e0290..6226e35ae 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCrypto.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCrypto.cs @@ -17,7 +17,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AesdV, d, n); + } + else if (Optimizations.UseAesni) { res = context.AddIntrinsic(Intrinsic.X86Aesdeclast, context.AddIntrinsic(Intrinsic.X86Xorpd, d, n), context.VectorZero()); } @@ -38,7 +42,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AeseV, d, n); + } + else if (Optimizations.UseAesni) { res = context.AddIntrinsic(Intrinsic.X86Aesenclast, context.AddIntrinsic(Intrinsic.X86Xorpd, d, n), context.VectorZero()); } @@ -58,7 +66,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AesimcV, n); + } + else if (Optimizations.UseAesni) { res = context.AddIntrinsic(Intrinsic.X86Aesimc, n); } @@ -78,7 +90,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AesmcV, n); + } + else if (Optimizations.UseAesni) { Operand roundKey = context.VectorZero(); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCrypto32.cs b/src/ARMeilleure/Instructions/InstEmitSimdCrypto32.cs index f713a388c..24fd7c87e 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCrypto32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCrypto32.cs @@ -17,7 +17,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AesdV, d, n); + } + else if (Optimizations.UseAesni) { res = context.AddIntrinsic(Intrinsic.X86Aesdeclast, context.AddIntrinsic(Intrinsic.X86Xorpd, d, n), context.VectorZero()); } @@ -38,7 +42,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AeseV, d, n); + } + else if (Optimizations.UseAesni) { res = context.AddIntrinsic(Intrinsic.X86Aesenclast, context.AddIntrinsic(Intrinsic.X86Xorpd, d, n), context.VectorZero()); } @@ -58,7 +66,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AesimcV, n); + } + else if (Optimizations.UseAesni) { res = context.AddIntrinsic(Intrinsic.X86Aesimc, n); } @@ -78,7 +90,11 @@ namespace ARMeilleure.Instructions Operand res; - if (Optimizations.UseAesni) + if (Optimizations.UseArm64Aes) + { + res = context.AddIntrinsic(Intrinsic.Arm64AesmcV, n); + } + else if (Optimizations.UseAesni) { Operand roundKey = context.VectorZero(); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCvt.cs b/src/ARMeilleure/Instructions/InstEmitSimdCvt.cs index 652ad397c..3363a7c77 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCvt.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCvt.cs @@ -5,7 +5,6 @@ using ARMeilleure.Translation; using System; using System.Diagnostics; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -67,8 +66,8 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand res = context.AddIntrinsic(Intrinsic.X86Vcvtps2ph, n, Const(X86GetRoundControl(FPRoundingMode.ToNearest))); - res = context.AddIntrinsic(Intrinsic.X86Pslldq, res, Const(14)); // VectorZeroUpper112() - res = context.AddIntrinsic(Intrinsic.X86Psrldq, res, Const(14)); + res = context.AddIntrinsic(Intrinsic.X86Pslldq, res, Const(14)); // VectorZeroUpper112() + res = context.AddIntrinsic(Intrinsic.X86Psrldq, res, Const(14)); context.Copy(GetVec(op.Rd), res); } @@ -92,7 +91,7 @@ namespace ARMeilleure.Instructions Debug.Assert(!Optimizations.ForceLegacySse); Operand res = context.AddIntrinsic(Intrinsic.X86Vcvtph2ps, GetVec(op.Rn)); - res = context.VectorZeroUpper96(res); + res = context.VectorZeroUpper96(res); context.Copy(GetVec(op.Rd), res); } @@ -116,7 +115,7 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand res = context.AddIntrinsic(Intrinsic.X86Cvtsd2ss, context.VectorZero(), n); - res = context.AddIntrinsic(Intrinsic.X86Vcvtps2ph, res, Const(X86GetRoundControl(FPRoundingMode.ToNearest))); + res = context.AddIntrinsic(Intrinsic.X86Vcvtps2ph, res, Const(X86GetRoundControl(FPRoundingMode.ToNearest))); context.Copy(GetVec(op.Rd), res); } @@ -140,8 +139,8 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand res = context.AddIntrinsic(Intrinsic.X86Vcvtph2ps, GetVec(op.Rn)); - res = context.AddIntrinsic(Intrinsic.X86Cvtss2sd, context.VectorZero(), res); - res = context.VectorZeroUpper64(res); + res = context.AddIntrinsic(Intrinsic.X86Cvtss2sd, context.VectorZero(), res); + res = context.VectorZeroUpper64(res); context.Copy(GetVec(op.Rd), res); } @@ -273,7 +272,7 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand res = op.RegisterSize == RegisterSize.Simd128 ? context.AddIntrinsic(Intrinsic.X86Movhlps, n, n) : n; - res = context.AddIntrinsic(Intrinsic.X86Cvtps2pd, res); + res = context.AddIntrinsic(Intrinsic.X86Cvtps2pd, res); context.Copy(GetVec(op.Rd), res); } @@ -284,7 +283,7 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand res = op.RegisterSize == RegisterSize.Simd128 ? context.AddIntrinsic(Intrinsic.X86Movhlps, n, n) : n; - res = context.AddIntrinsic(Intrinsic.X86Vcvtph2ps, res); + res = context.AddIntrinsic(Intrinsic.X86Vcvtph2ps, res); context.Copy(GetVec(op.Rd), res); } @@ -387,10 +386,10 @@ namespace ARMeilleure.Instructions Intrinsic movInst = op.RegisterSize == RegisterSize.Simd128 ? Intrinsic.X86Movlhps : Intrinsic.X86Movhlps; Operand nInt = context.AddIntrinsic(Intrinsic.X86Cvtpd2ps, GetVec(op.Rn)); - nInt = context.AddIntrinsic(Intrinsic.X86Movlhps, nInt, nInt); + nInt = context.AddIntrinsic(Intrinsic.X86Movlhps, nInt, nInt); Operand res = context.VectorZeroUpper64(d); - res = context.AddIntrinsic(movInst, res, nInt); + res = context.AddIntrinsic(movInst, res, nInt); context.Copy(d, res); } @@ -404,10 +403,10 @@ namespace ARMeilleure.Instructions Intrinsic movInst = op.RegisterSize == RegisterSize.Simd128 ? Intrinsic.X86Movlhps : Intrinsic.X86Movhlps; Operand nInt = context.AddIntrinsic(Intrinsic.X86Vcvtps2ph, n, Const(X86GetRoundControl(FPRoundingMode.ToNearest))); - nInt = context.AddIntrinsic(Intrinsic.X86Movlhps, nInt, nInt); + nInt = context.AddIntrinsic(Intrinsic.X86Movlhps, nInt, nInt); Operand res = context.VectorZeroUpper64(d); - res = context.AddIntrinsic(movInst, res, nInt); + res = context.AddIntrinsic(movInst, res, nInt); context.Copy(d, res); } @@ -1225,15 +1224,15 @@ namespace ARMeilleure.Instructions { Debug.Assert(opF.Type == OperandType.V128); - Operand longL = context.AddIntrinsicLong (Intrinsic.X86Cvtsd2si, opF); // opFL - Operand res = context.VectorCreateScalar(longL); + Operand longL = context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, opF); // opFL + Operand res = context.VectorCreateScalar(longL); if (!scalar) { - Operand opFH = context.AddIntrinsic (Intrinsic.X86Movhlps, res, opF); // res doesn't matter. - Operand longH = context.AddIntrinsicLong (Intrinsic.X86Cvtsd2si, opFH); - Operand resH = context.VectorCreateScalar(longH); - res = context.AddIntrinsic (Intrinsic.X86Movlhps, res, resH); + Operand opFH = context.AddIntrinsic(Intrinsic.X86Movhlps, res, opF); // res doesn't matter. + Operand longH = context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, opFH); + Operand resH = context.VectorCreateScalar(longH); + res = context.AddIntrinsic(Intrinsic.X86Movlhps, res, resH); } return res; @@ -1244,14 +1243,14 @@ namespace ARMeilleure.Instructions Debug.Assert(op.Type == OperandType.V128); Operand longL = context.AddIntrinsicLong(Intrinsic.X86Cvtsi2si, op); // opL - Operand res = context.AddIntrinsic (Intrinsic.X86Cvtsi2sd, context.VectorZero(), longL); + Operand res = context.AddIntrinsic(Intrinsic.X86Cvtsi2sd, context.VectorZero(), longL); if (!scalar) { - Operand opH = context.AddIntrinsic (Intrinsic.X86Movhlps, res, op); // res doesn't matter. + Operand opH = context.AddIntrinsic(Intrinsic.X86Movhlps, res, op); // res doesn't matter. Operand longH = context.AddIntrinsicLong(Intrinsic.X86Cvtsi2si, opH); - Operand resH = context.AddIntrinsic (Intrinsic.X86Cvtsi2sd, res, longH); // res doesn't matter. - res = context.AddIntrinsic (Intrinsic.X86Movlhps, res, resH); + Operand resH = context.AddIntrinsic(Intrinsic.X86Cvtsi2sd, res, longH); // res doesn't matter. + res = context.AddIntrinsic(Intrinsic.X86Movlhps, res, resH); } return res; @@ -1278,7 +1277,7 @@ namespace ARMeilleure.Instructions int fpScaled = 0x3F800000 - fBits * 0x800000; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); res = context.AddIntrinsic(Intrinsic.X86Mulps, res, fpScaledMask); @@ -1307,7 +1306,7 @@ namespace ARMeilleure.Instructions long fpScaled = 0x3FF0000000000000L - fBits * 0x10000000000000L; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); res = context.AddIntrinsic(Intrinsic.X86Mulpd, res, fpScaledMask); @@ -1334,16 +1333,16 @@ namespace ARMeilleure.Instructions if (sizeF == 0) { Operand mask = scalar // 65536.000f (1 << 16) - ? X86GetScalar (context, 0x47800000) + ? X86GetScalar(context, 0x47800000) : X86GetAllElements(context, 0x47800000); Operand res = context.AddIntrinsic(Intrinsic.X86Psrld, n, Const(16)); - res = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, res); - res = context.AddIntrinsic(Intrinsic.X86Mulps, res, mask); + res = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, res); + res = context.AddIntrinsic(Intrinsic.X86Mulps, res, mask); Operand res2 = context.AddIntrinsic(Intrinsic.X86Pslld, n, Const(16)); - res2 = context.AddIntrinsic(Intrinsic.X86Psrld, res2, Const(16)); - res2 = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, res2); + res2 = context.AddIntrinsic(Intrinsic.X86Psrld, res2, Const(16)); + res2 = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, res2); res = context.AddIntrinsic(Intrinsic.X86Addps, res, res2); @@ -1355,7 +1354,7 @@ namespace ARMeilleure.Instructions int fpScaled = 0x3F800000 - fBits * 0x800000; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); res = context.AddIntrinsic(Intrinsic.X86Mulps, res, fpScaledMask); @@ -1375,16 +1374,16 @@ namespace ARMeilleure.Instructions else /* if (sizeF == 1) */ { Operand mask = scalar // 4294967296.0000000d (1L << 32) - ? X86GetScalar (context, 0x41F0000000000000L) + ? X86GetScalar(context, 0x41F0000000000000L) : X86GetAllElements(context, 0x41F0000000000000L); - Operand res = context.AddIntrinsic (Intrinsic.X86Psrlq, n, Const(32)); - res = EmitSse2CvtInt64ToDoubleOp(context, res, scalar); - res = context.AddIntrinsic (Intrinsic.X86Mulpd, res, mask); + Operand res = context.AddIntrinsic(Intrinsic.X86Psrlq, n, Const(32)); + res = EmitSse2CvtInt64ToDoubleOp(context, res, scalar); + res = context.AddIntrinsic(Intrinsic.X86Mulpd, res, mask); - Operand res2 = context.AddIntrinsic (Intrinsic.X86Psllq, n, Const(32)); - res2 = context.AddIntrinsic (Intrinsic.X86Psrlq, res2, Const(32)); - res2 = EmitSse2CvtInt64ToDoubleOp(context, res2, scalar); + Operand res2 = context.AddIntrinsic(Intrinsic.X86Psllq, n, Const(32)); + res2 = context.AddIntrinsic(Intrinsic.X86Psrlq, res2, Const(32)); + res2 = EmitSse2CvtInt64ToDoubleOp(context, res2, scalar); res = context.AddIntrinsic(Intrinsic.X86Addpd, res, res2); @@ -1396,7 +1395,7 @@ namespace ARMeilleure.Instructions long fpScaled = 0x3FF0000000000000L - fBits * 0x10000000000000L; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); res = context.AddIntrinsic(Intrinsic.X86Mulpd, res, fpScaledMask); @@ -1423,7 +1422,7 @@ namespace ARMeilleure.Instructions if (sizeF == 0) { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (op is OpCodeSimdShImm fixedOp) { @@ -1433,7 +1432,7 @@ namespace ARMeilleure.Instructions int fpScaled = 0x3F800000 + fBits * 0x800000; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); nRes = context.AddIntrinsic(Intrinsic.X86Mulps, nRes, fpScaledMask); @@ -1451,7 +1450,7 @@ namespace ARMeilleure.Instructions Operand nInt = context.AddIntrinsic(Intrinsic.X86Cvtps2dq, nRes); Operand fpMaxValMask = scalar // 2.14748365E9f (2147483648) - ? X86GetScalar (context, 0x4F000000) + ? X86GetScalar(context, 0x4F000000) : X86GetAllElements(context, 0x4F000000); nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan)); @@ -1472,7 +1471,7 @@ namespace ARMeilleure.Instructions else /* if (sizeF == 1) */ { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (op is OpCodeSimdShImm fixedOp) { @@ -1482,7 +1481,7 @@ namespace ARMeilleure.Instructions long fpScaled = 0x3FF0000000000000L + fBits * 0x10000000000000L; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); nRes = context.AddIntrinsic(Intrinsic.X86Mulpd, nRes, fpScaledMask); @@ -1500,7 +1499,7 @@ namespace ARMeilleure.Instructions Operand nLong = EmitSse2CvtDoubleToInt64OpF(context, nRes, scalar); Operand fpMaxValMask = scalar // 9.2233720368547760E18d (9223372036854775808) - ? X86GetScalar (context, 0x43E0000000000000L) + ? X86GetScalar(context, 0x43E0000000000000L) : X86GetAllElements(context, 0x43E0000000000000L); nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan)); @@ -1528,7 +1527,7 @@ namespace ARMeilleure.Instructions if (sizeF == 0) { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (op is OpCodeSimdShImm fixedOp) { @@ -1538,7 +1537,7 @@ namespace ARMeilleure.Instructions int fpScaled = 0x3F800000 + fBits * 0x800000; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); nRes = context.AddIntrinsic(Intrinsic.X86Mulps, nRes, fpScaledMask); @@ -1556,10 +1555,10 @@ namespace ARMeilleure.Instructions Operand zero = context.VectorZero(); Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); Operand fpMaxValMask = scalar // 2.14748365E9f (2147483648) - ? X86GetScalar (context, 0x4F000000) + ? X86GetScalar(context, 0x4F000000) : X86GetAllElements(context, 0x4F000000); Operand nInt = context.AddIntrinsic(Intrinsic.X86Cvtps2dq, nRes); @@ -1567,14 +1566,14 @@ namespace ARMeilleure.Instructions nRes = context.AddIntrinsic(Intrinsic.X86Subps, nRes, fpMaxValMask); nCmp = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); Operand nInt2 = context.AddIntrinsic(Intrinsic.X86Cvtps2dq, nRes); nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan)); - Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nInt2, nRes); - dRes = context.AddIntrinsic(Intrinsic.X86Paddd, dRes, nInt); + Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nInt2, nRes); + dRes = context.AddIntrinsic(Intrinsic.X86Paddd, dRes, nInt); if (scalar) { @@ -1590,7 +1589,7 @@ namespace ARMeilleure.Instructions else /* if (sizeF == 1) */ { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (op is OpCodeSimdShImm fixedOp) { @@ -1600,7 +1599,7 @@ namespace ARMeilleure.Instructions long fpScaled = 0x3FF0000000000000L + fBits * 0x10000000000000L; Operand fpScaledMask = scalar - ? X86GetScalar (context, fpScaled) + ? X86GetScalar(context, fpScaled) : X86GetAllElements(context, fpScaled); nRes = context.AddIntrinsic(Intrinsic.X86Mulpd, nRes, fpScaledMask); @@ -1618,10 +1617,10 @@ namespace ARMeilleure.Instructions Operand zero = context.VectorZero(); Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); Operand fpMaxValMask = scalar // 9.2233720368547760E18d (9223372036854775808) - ? X86GetScalar (context, 0x43E0000000000000L) + ? X86GetScalar(context, 0x43E0000000000000L) : X86GetAllElements(context, 0x43E0000000000000L); Operand nLong = EmitSse2CvtDoubleToInt64OpF(context, nRes, scalar); @@ -1629,14 +1628,14 @@ namespace ARMeilleure.Instructions nRes = context.AddIntrinsic(Intrinsic.X86Subpd, nRes, fpMaxValMask); nCmp = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); Operand nLong2 = EmitSse2CvtDoubleToInt64OpF(context, nRes, scalar); nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan)); - Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nLong2, nRes); - dRes = context.AddIntrinsic(Intrinsic.X86Paddq, dRes, nLong); + Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nLong2, nRes); + dRes = context.AddIntrinsic(Intrinsic.X86Paddq, dRes, nLong); if (scalar) { @@ -1656,7 +1655,7 @@ namespace ARMeilleure.Instructions if (op.Size == 0) { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (isFixed) { @@ -1678,7 +1677,7 @@ namespace ARMeilleure.Instructions } Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (Intrinsic.X86Cvtss2si, nRes) + ? context.AddIntrinsicInt(Intrinsic.X86Cvtss2si, nRes) : context.AddIntrinsicLong(Intrinsic.X86Cvtss2si, nRes); int fpMaxVal = op.RegisterSize == RegisterSize.Int32 @@ -1703,7 +1702,7 @@ namespace ARMeilleure.Instructions else /* if (op.Size == 1) */ { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (isFixed) { @@ -1725,7 +1724,7 @@ namespace ARMeilleure.Instructions } Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (Intrinsic.X86Cvtsd2si, nRes) + ? context.AddIntrinsicInt(Intrinsic.X86Cvtsd2si, nRes) : context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, nRes); long fpMaxVal = op.RegisterSize == RegisterSize.Int32 @@ -1758,7 +1757,7 @@ namespace ARMeilleure.Instructions if (op.Size == 0) { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (isFixed) { @@ -1782,7 +1781,7 @@ namespace ARMeilleure.Instructions Operand zero = context.VectorZero(); Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); int fpMaxVal = op.RegisterSize == RegisterSize.Int32 ? 0x4F000000 // 2.14748365E9f (2147483648) @@ -1791,16 +1790,16 @@ namespace ARMeilleure.Instructions Operand fpMaxValMask = X86GetScalar(context, fpMaxVal); Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (Intrinsic.X86Cvtss2si, nRes) + ? context.AddIntrinsicInt(Intrinsic.X86Cvtss2si, nRes) : context.AddIntrinsicLong(Intrinsic.X86Cvtss2si, nRes); nRes = context.AddIntrinsic(Intrinsic.X86Subss, nRes, fpMaxValMask); nCmp = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); Operand nIntOrLong2 = op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (Intrinsic.X86Cvtss2si, nRes) + ? context.AddIntrinsicInt(Intrinsic.X86Cvtss2si, nRes) : context.AddIntrinsicLong(Intrinsic.X86Cvtss2si, nRes); nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan)); @@ -1813,14 +1812,14 @@ namespace ARMeilleure.Instructions } Operand dRes = context.BitwiseExclusiveOr(nIntOrLong2, nInt); - dRes = context.Add(dRes, nIntOrLong); + dRes = context.Add(dRes, nIntOrLong); SetIntOrZR(context, op.Rd, dRes); } else /* if (op.Size == 1) */ { Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, n, n, Const((int)CmpCondition.OrderedQ)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n); if (isFixed) { @@ -1844,7 +1843,7 @@ namespace ARMeilleure.Instructions Operand zero = context.VectorZero(); Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); long fpMaxVal = op.RegisterSize == RegisterSize.Int32 ? 0x41E0000000000000L // 2147483648.0000000d (2147483648) @@ -1853,16 +1852,16 @@ namespace ARMeilleure.Instructions Operand fpMaxValMask = X86GetScalar(context, fpMaxVal); Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (Intrinsic.X86Cvtsd2si, nRes) + ? context.AddIntrinsicInt(Intrinsic.X86Cvtsd2si, nRes) : context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, nRes); nRes = context.AddIntrinsic(Intrinsic.X86Subsd, nRes, fpMaxValMask); nCmp = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual)); - nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); + nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp); Operand nIntOrLong2 = op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (Intrinsic.X86Cvtsd2si, nRes) + ? context.AddIntrinsicInt(Intrinsic.X86Cvtsd2si, nRes) : context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, nRes); nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan)); @@ -1875,7 +1874,7 @@ namespace ARMeilleure.Instructions } Operand dRes = context.BitwiseExclusiveOr(nIntOrLong2, nLong); - dRes = context.Add(dRes, nIntOrLong); + dRes = context.Add(dRes, nIntOrLong); SetIntOrZR(context, op.Rd, dRes); } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs b/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs index 33ae83df6..b03855910 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdCvt32.cs @@ -5,7 +5,6 @@ using ARMeilleure.Translation; using System; using System.Diagnostics; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper32; @@ -115,6 +114,35 @@ namespace ARMeilleure.Instructions } } + public static void Vcvt_V_Fixed(ArmEmitterContext context) + { + OpCode32SimdCvtFFixed op = (OpCode32SimdCvtFFixed)context.CurrOp; + + var toFixed = op.Opc == 1; + int fracBits = op.Fbits; + var unsigned = op.U; + + if (toFixed) // F32 to S32 or U32 (fixed) + { + EmitVectorUnaryOpF32(context, (op1) => + { + var scaledValue = context.Multiply(op1, ConstF(MathF.Pow(2f, fracBits))); + MethodInfo info = unsigned ? typeof(SoftFallback).GetMethod(nameof(SoftFallback.SatF32ToU32)) : typeof(SoftFallback).GetMethod(nameof(SoftFallback.SatF32ToS32)); + + return context.Call(info, scaledValue); + }); + } + else // S32 or U32 (fixed) to F32 + { + EmitVectorUnaryOpI32(context, (op1) => + { + var floatValue = unsigned ? context.ConvertToFPUI(OperandType.FP32, op1) : context.ConvertToFP(OperandType.FP32, op1); + + return context.Multiply(floatValue, ConstF(1f / MathF.Pow(2f, fracBits))); + }, !unsigned); + } + } + public static void Vcvt_FD(ArmEmitterContext context) { OpCode32SimdS op = (OpCode32SimdS)context.CurrOp; @@ -165,7 +193,7 @@ namespace ARMeilleure.Instructions { Operand m = GetVecA32(op.Vm >> 1); - Operand toConvert = InstEmitSimdHelper32Arm64.EmitExtractScalar(context, m, op.Vm, doubleSize); + Operand toConvert = InstEmitSimdHelper32Arm64.EmitExtractScalar(context, m, op.Vm, true); Intrinsic inst = (unsigned ? Intrinsic.Arm64FcvtzuGp : Intrinsic.Arm64FcvtzsGp) | Intrinsic.Arm64VDouble; @@ -175,7 +203,7 @@ namespace ARMeilleure.Instructions } else { - InstEmitSimdHelper32Arm64.EmitScalarUnaryOpF32(context, unsigned ? Intrinsic.Arm64FcvtzuS : Intrinsic.Arm64FcvtzsS); + InstEmitSimdHelper32Arm64.EmitScalarUnaryOpF32(context, unsigned ? Intrinsic.Arm64FcvtzuS : Intrinsic.Arm64FcvtzsS, false); } } else if (!roundWithFpscr && Optimizations.UseSse41) @@ -217,33 +245,22 @@ namespace ARMeilleure.Instructions string name = nameof(Math.Round); MethodInfo info = (op.Size & 1) == 0 - ? typeof(MathF).GetMethod(name, new Type[] { typeof(float), typeof(MidpointRounding) }) - : typeof(Math). GetMethod(name, new Type[] { typeof(double), typeof(MidpointRounding) }); + ? typeof(MathF).GetMethod(name, new Type[] { typeof(float), typeof(MidpointRounding) }) + : typeof(Math).GetMethod(name, new Type[] { typeof(double), typeof(MidpointRounding) }); return context.Call(info, n, Const((int)roundMode)); } private static FPRoundingMode RMToRoundMode(int rm) { - FPRoundingMode roundMode; - switch (rm) + return rm switch { - case 0b00: - roundMode = FPRoundingMode.ToNearestAway; - break; - case 0b01: - roundMode = FPRoundingMode.ToNearest; - break; - case 0b10: - roundMode = FPRoundingMode.TowardsPlusInfinity; - break; - case 0b11: - roundMode = FPRoundingMode.TowardsMinusInfinity; - break; - default: - throw new ArgumentOutOfRangeException(nameof(rm)); - } - return roundMode; + 0b00 => FPRoundingMode.ToNearestAway, + 0b01 => FPRoundingMode.ToNearest, + 0b10 => FPRoundingMode.TowardsPlusInfinity, + 0b11 => FPRoundingMode.TowardsMinusInfinity, + _ => throw new ArgumentOutOfRangeException(nameof(rm)), + }; } // VCVTA/M/N/P (floating-point). @@ -260,28 +277,68 @@ namespace ARMeilleure.Instructions if (Optimizations.UseAdvSimd) { - if (unsigned) + bool doubleSize = floatSize == OperandType.FP64; + + if (doubleSize) { - inst = rm switch { - 0b00 => Intrinsic.Arm64FcvtauS, - 0b01 => Intrinsic.Arm64FcvtnuS, - 0b10 => Intrinsic.Arm64FcvtpuS, - 0b11 => Intrinsic.Arm64FcvtmuS, - _ => throw new ArgumentOutOfRangeException(nameof(rm)) - }; + Operand m = GetVecA32(op.Vm >> 1); + + Operand toConvert = InstEmitSimdHelper32Arm64.EmitExtractScalar(context, m, op.Vm, true); + + if (unsigned) + { + inst = rm switch + { + 0b00 => Intrinsic.Arm64FcvtauGp, + 0b01 => Intrinsic.Arm64FcvtnuGp, + 0b10 => Intrinsic.Arm64FcvtpuGp, + 0b11 => Intrinsic.Arm64FcvtmuGp, + _ => throw new InvalidOperationException($"{nameof(rm)} contains an invalid value: {rm}"), + }; + } + else + { + inst = rm switch + { + 0b00 => Intrinsic.Arm64FcvtasGp, + 0b01 => Intrinsic.Arm64FcvtnsGp, + 0b10 => Intrinsic.Arm64FcvtpsGp, + 0b11 => Intrinsic.Arm64FcvtmsGp, + _ => throw new InvalidOperationException($"{nameof(rm)} contains an invalid value: {rm}"), + }; + } + + Operand asInteger = context.AddIntrinsicInt(inst | Intrinsic.Arm64VDouble, toConvert); + + InsertScalar(context, op.Vd, asInteger); } else { - inst = rm switch { - 0b00 => Intrinsic.Arm64FcvtasS, - 0b01 => Intrinsic.Arm64FcvtnsS, - 0b10 => Intrinsic.Arm64FcvtpsS, - 0b11 => Intrinsic.Arm64FcvtmsS, - _ => throw new ArgumentOutOfRangeException(nameof(rm)) - }; - } + if (unsigned) + { + inst = rm switch + { + 0b00 => Intrinsic.Arm64FcvtauS, + 0b01 => Intrinsic.Arm64FcvtnuS, + 0b10 => Intrinsic.Arm64FcvtpuS, + 0b11 => Intrinsic.Arm64FcvtmuS, + _ => throw new InvalidOperationException($"{nameof(rm)} contains an invalid value: {rm}"), + }; + } + else + { + inst = rm switch + { + 0b00 => Intrinsic.Arm64FcvtasS, + 0b01 => Intrinsic.Arm64FcvtnsS, + 0b10 => Intrinsic.Arm64FcvtpsS, + 0b11 => Intrinsic.Arm64FcvtmsS, + _ => throw new InvalidOperationException($"{nameof(rm)} contains an invalid value: {rm}"), + }; + } - InstEmitSimdHelper32Arm64.EmitScalarUnaryOpF32(context, inst); + InstEmitSimdHelper32Arm64.EmitScalarUnaryOpF32(context, inst); + } } else if (Optimizations.UseSse41) { @@ -396,12 +453,13 @@ namespace ARMeilleure.Instructions if (Optimizations.UseAdvSimd) { - Intrinsic inst = rm switch { + Intrinsic inst = rm switch + { 0b00 => Intrinsic.Arm64FrintaS, 0b01 => Intrinsic.Arm64FrintnS, 0b10 => Intrinsic.Arm64FrintpS, 0b11 => Intrinsic.Arm64FrintmS, - _ => throw new ArgumentOutOfRangeException(nameof(rm)) + _ => throw new InvalidOperationException($"{nameof(rm)} contains an invalid value: {rm}"), }; InstEmitSimdHelper32Arm64.EmitScalarUnaryOpF32(context, inst); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHash.cs b/src/ARMeilleure/Instructions/InstEmitSimdHash.cs index 4fb048eed..aee12d7dc 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHash.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHash.cs @@ -8,7 +8,7 @@ namespace ARMeilleure.Instructions { static partial class InstEmit { -#region "Sha1" + #region "Sha1" public static void Sha1c_V(ArmEmitterContext context) { OpCodeSimdReg op = (OpCodeSimdReg)context.CurrOp; @@ -89,9 +89,9 @@ namespace ARMeilleure.Instructions context.Copy(GetVec(op.Rd), res); } -#endregion + #endregion -#region "Sha256" + #region "Sha256" public static void Sha256h_V(ArmEmitterContext context) { OpCodeSimdReg op = (OpCodeSimdReg)context.CurrOp; @@ -142,6 +142,6 @@ namespace ARMeilleure.Instructions context.Copy(GetVec(op.Rd), res); } -#endregion + #endregion } } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHash32.cs b/src/ARMeilleure/Instructions/InstEmitSimdHash32.cs index 51334608d..c2bb951ab 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHash32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHash32.cs @@ -8,7 +8,7 @@ namespace ARMeilleure.Instructions { static partial class InstEmit32 { -#region "Sha256" + #region "Sha256" public static void Sha256h_V(ArmEmitterContext context) { OpCode32SimdReg op = (OpCode32SimdReg)context.CurrOp; @@ -59,6 +59,6 @@ namespace ARMeilleure.Instructions context.Copy(GetVecA32(op.Qd), res); } -#endregion + #endregion } } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHashHelper.cs b/src/ARMeilleure/Instructions/InstEmitSimdHashHelper.cs index 23e4948d9..a672b159f 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHashHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHashHelper.cs @@ -18,9 +18,9 @@ namespace ARMeilleure.Instructions Operand round2 = context.AddIntrinsic(Intrinsic.X86Sha256Rnds2, src1, src2, w); Operand round4 = context.AddIntrinsic(Intrinsic.X86Sha256Rnds2, src2, round2, w2); - + Operand res = context.AddIntrinsic(Intrinsic.X86Shufps, round4, round2, Const(part2 ? 0x11 : 0xbb)); - + return res; } @@ -53,4 +53,4 @@ namespace ARMeilleure.Instructions return context.Call(typeof(SoftFallback).GetMethod(nameof(SoftFallback.Sha256SchedulePart2)), x, y, z); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHelper.cs b/src/ARMeilleure/Instructions/InstEmitSimdHelper.cs index c44c9b4d9..0b5527409 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHelper.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHelper.cs @@ -6,7 +6,6 @@ using ARMeilleure.Translation; using System; using System.Diagnostics; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -18,19 +17,19 @@ namespace ARMeilleure.Instructions static class InstEmitSimdHelper { -#region "Masks" + #region "Masks" public static readonly long[] EvenMasks = new long[] { 14L << 56 | 12L << 48 | 10L << 40 | 08L << 32 | 06L << 24 | 04L << 16 | 02L << 8 | 00L << 0, // B 13L << 56 | 12L << 48 | 09L << 40 | 08L << 32 | 05L << 24 | 04L << 16 | 01L << 8 | 00L << 0, // H - 11L << 56 | 10L << 48 | 09L << 40 | 08L << 32 | 03L << 24 | 02L << 16 | 01L << 8 | 00L << 0 // S + 11L << 56 | 10L << 48 | 09L << 40 | 08L << 32 | 03L << 24 | 02L << 16 | 01L << 8 | 00L << 0, // S }; public static readonly long[] OddMasks = new long[] { 15L << 56 | 13L << 48 | 11L << 40 | 09L << 32 | 07L << 24 | 05L << 16 | 03L << 8 | 01L << 0, // B 15L << 56 | 14L << 48 | 11L << 40 | 10L << 32 | 07L << 24 | 06L << 16 | 03L << 8 | 02L << 0, // H - 15L << 56 | 14L << 48 | 13L << 40 | 12L << 32 | 07L << 24 | 06L << 16 | 05L << 8 | 04L << 0 // S + 15L << 56 | 14L << 48 | 13L << 40 | 12L << 32 | 07L << 24 | 06L << 16 | 05L << 8 | 04L << 0, // S }; public static readonly long ZeroMask = 128L << 56 | 128L << 48 | 128L << 40 | 128L << 32 | 128L << 24 | 128L << 16 | 128L << 8 | 128L << 0; @@ -38,19 +37,19 @@ namespace ARMeilleure.Instructions public static ulong X86GetGf2p8LogicalShiftLeft(int shift) { ulong identity = (0b00000001UL << 56) | (0b00000010UL << 48) | (0b00000100UL << 40) | (0b00001000UL << 32) | - (0b00010000UL << 24) | (0b00100000UL << 16) | (0b01000000UL << 8) | (0b10000000UL << 0); + (0b00010000UL << 24) | (0b00100000UL << 16) | (0b01000000UL << 8) | (0b10000000UL << 0); return shift >= 0 ? identity >> (shift * 8) : identity << (-shift * 8); } -#endregion + #endregion -#region "X86 SSE Intrinsics" + #region "X86 SSE Intrinsics" public static readonly Intrinsic[] X86PaddInstruction = new Intrinsic[] { Intrinsic.X86Paddb, Intrinsic.X86Paddw, Intrinsic.X86Paddd, - Intrinsic.X86Paddq + Intrinsic.X86Paddq, }; public static readonly Intrinsic[] X86PcmpeqInstruction = new Intrinsic[] @@ -58,7 +57,7 @@ namespace ARMeilleure.Instructions Intrinsic.X86Pcmpeqb, Intrinsic.X86Pcmpeqw, Intrinsic.X86Pcmpeqd, - Intrinsic.X86Pcmpeqq + Intrinsic.X86Pcmpeqq, }; public static readonly Intrinsic[] X86PcmpgtInstruction = new Intrinsic[] @@ -66,49 +65,49 @@ namespace ARMeilleure.Instructions Intrinsic.X86Pcmpgtb, Intrinsic.X86Pcmpgtw, Intrinsic.X86Pcmpgtd, - Intrinsic.X86Pcmpgtq + Intrinsic.X86Pcmpgtq, }; public static readonly Intrinsic[] X86PmaxsInstruction = new Intrinsic[] { Intrinsic.X86Pmaxsb, Intrinsic.X86Pmaxsw, - Intrinsic.X86Pmaxsd + Intrinsic.X86Pmaxsd, }; public static readonly Intrinsic[] X86PmaxuInstruction = new Intrinsic[] { Intrinsic.X86Pmaxub, Intrinsic.X86Pmaxuw, - Intrinsic.X86Pmaxud + Intrinsic.X86Pmaxud, }; public static readonly Intrinsic[] X86PminsInstruction = new Intrinsic[] { Intrinsic.X86Pminsb, Intrinsic.X86Pminsw, - Intrinsic.X86Pminsd + Intrinsic.X86Pminsd, }; public static readonly Intrinsic[] X86PminuInstruction = new Intrinsic[] { Intrinsic.X86Pminub, Intrinsic.X86Pminuw, - Intrinsic.X86Pminud + Intrinsic.X86Pminud, }; public static readonly Intrinsic[] X86PmovsxInstruction = new Intrinsic[] { Intrinsic.X86Pmovsxbw, Intrinsic.X86Pmovsxwd, - Intrinsic.X86Pmovsxdq + Intrinsic.X86Pmovsxdq, }; public static readonly Intrinsic[] X86PmovzxInstruction = new Intrinsic[] { Intrinsic.X86Pmovzxbw, Intrinsic.X86Pmovzxwd, - Intrinsic.X86Pmovzxdq + Intrinsic.X86Pmovzxdq, }; public static readonly Intrinsic[] X86PsllInstruction = new Intrinsic[] @@ -116,14 +115,14 @@ namespace ARMeilleure.Instructions 0, Intrinsic.X86Psllw, Intrinsic.X86Pslld, - Intrinsic.X86Psllq + Intrinsic.X86Psllq, }; public static readonly Intrinsic[] X86PsraInstruction = new Intrinsic[] { 0, Intrinsic.X86Psraw, - Intrinsic.X86Psrad + Intrinsic.X86Psrad, }; public static readonly Intrinsic[] X86PsrlInstruction = new Intrinsic[] @@ -131,7 +130,7 @@ namespace ARMeilleure.Instructions 0, Intrinsic.X86Psrlw, Intrinsic.X86Psrld, - Intrinsic.X86Psrlq + Intrinsic.X86Psrlq, }; public static readonly Intrinsic[] X86PsubInstruction = new Intrinsic[] @@ -139,7 +138,7 @@ namespace ARMeilleure.Instructions Intrinsic.X86Psubb, Intrinsic.X86Psubw, Intrinsic.X86Psubd, - Intrinsic.X86Psubq + Intrinsic.X86Psubq, }; public static readonly Intrinsic[] X86PunpckhInstruction = new Intrinsic[] @@ -147,7 +146,7 @@ namespace ARMeilleure.Instructions Intrinsic.X86Punpckhbw, Intrinsic.X86Punpckhwd, Intrinsic.X86Punpckhdq, - Intrinsic.X86Punpckhqdq + Intrinsic.X86Punpckhqdq, }; public static readonly Intrinsic[] X86PunpcklInstruction = new Intrinsic[] @@ -155,9 +154,9 @@ namespace ARMeilleure.Instructions Intrinsic.X86Punpcklbw, Intrinsic.X86Punpcklwd, Intrinsic.X86Punpckldq, - Intrinsic.X86Punpcklqdq + Intrinsic.X86Punpcklqdq, }; -#endregion + #endregion public static void EnterArmFpMode(EmitterContext context, Func getFpFlag) { @@ -310,15 +309,16 @@ namespace ARMeilleure.Instructions public static int X86GetRoundControl(FPRoundingMode roundMode) { - switch (roundMode) + return roundMode switch { - case FPRoundingMode.ToNearest: return 8 | 0; // even - case FPRoundingMode.TowardsPlusInfinity: return 8 | 2; - case FPRoundingMode.TowardsMinusInfinity: return 8 | 1; - case FPRoundingMode.TowardsZero: return 8 | 3; - } - - throw new ArgumentException($"Invalid rounding mode \"{roundMode}\"."); +#pragma warning disable IDE0055 // Disable formatting + FPRoundingMode.ToNearest => 8 | 0, // even + FPRoundingMode.TowardsPlusInfinity => 8 | 2, + FPRoundingMode.TowardsMinusInfinity => 8 | 1, + FPRoundingMode.TowardsZero => 8 | 3, + _ => throw new ArgumentException($"Invalid rounding mode \"{roundMode}\"."), +#pragma warning restore IDE0055 + }; } public static Operand EmitSse41RoundToNearestWithTiesToAwayOpF(ArmEmitterContext context, Operand n, bool scalar) @@ -334,11 +334,11 @@ namespace ARMeilleure.Instructions if ((op.Size & 1) == 0) { Operand signMask = scalar ? X86GetScalar(context, int.MinValue) : X86GetAllElements(context, int.MinValue); - signMask = context.AddIntrinsic(Intrinsic.X86Pand, signMask, nCopy); + signMask = context.AddIntrinsic(Intrinsic.X86Pand, signMask, nCopy); // 0x3EFFFFFF == BitConverter.SingleToInt32Bits(0.5f) - 1 Operand valueMask = scalar ? X86GetScalar(context, 0x3EFFFFFF) : X86GetAllElements(context, 0x3EFFFFFF); - valueMask = context.AddIntrinsic(Intrinsic.X86Por, valueMask, signMask); + valueMask = context.AddIntrinsic(Intrinsic.X86Por, valueMask, signMask); nCopy = context.AddIntrinsic(scalar ? Intrinsic.X86Addss : Intrinsic.X86Addps, nCopy, valueMask); @@ -347,11 +347,11 @@ namespace ARMeilleure.Instructions else { Operand signMask = scalar ? X86GetScalar(context, long.MinValue) : X86GetAllElements(context, long.MinValue); - signMask = context.AddIntrinsic(Intrinsic.X86Pand, signMask, nCopy); + signMask = context.AddIntrinsic(Intrinsic.X86Pand, signMask, nCopy); // 0x3FDFFFFFFFFFFFFFL == BitConverter.DoubleToInt64Bits(0.5d) - 1L Operand valueMask = scalar ? X86GetScalar(context, 0x3FDFFFFFFFFFFFFFL) : X86GetAllElements(context, 0x3FDFFFFFFFFFFFFFL); - valueMask = context.AddIntrinsic(Intrinsic.X86Por, valueMask, signMask); + valueMask = context.AddIntrinsic(Intrinsic.X86Por, valueMask, signMask); nCopy = context.AddIntrinsic(scalar ? Intrinsic.X86Addsd : Intrinsic.X86Addpd, nCopy, valueMask); @@ -461,7 +461,7 @@ namespace ARMeilleure.Instructions MethodInfo info = (op.Size & 1) == 0 ? typeof(MathF).GetMethod(name, new Type[] { typeof(float) }) - : typeof(Math). GetMethod(name, new Type[] { typeof(double) }); + : typeof(Math).GetMethod(name, new Type[] { typeof(double) }); return context.Call(info, n); } @@ -473,8 +473,8 @@ namespace ARMeilleure.Instructions string name = nameof(Math.Round); MethodInfo info = (op.Size & 1) == 0 - ? typeof(MathF).GetMethod(name, new Type[] { typeof(float), typeof(MidpointRounding) }) - : typeof(Math). GetMethod(name, new Type[] { typeof(double), typeof(MidpointRounding) }); + ? typeof(MathF).GetMethod(name, new Type[] { typeof(float), typeof(MidpointRounding) }) + : typeof(Math).GetMethod(name, new Type[] { typeof(double), typeof(MidpointRounding) }); return context.Call(info, n, Const((int)roundMode)); } @@ -482,7 +482,7 @@ namespace ARMeilleure.Instructions public static Operand EmitGetRoundingMode(ArmEmitterContext context) { Operand rMode = context.ShiftLeft(GetFpFlag(FPState.RMode1Flag), Const(1)); - rMode = context.BitwiseOr(rMode, GetFpFlag(FPState.RMode0Flag)); + rMode = context.BitwiseOr(rMode, GetFpFlag(FPState.RMode0Flag)); return rMode; } @@ -1015,8 +1015,8 @@ namespace ARMeilleure.Instructions for (int index = 0; index < elems; index++) { - Operand ne = EmitVectorExtract(context, op.Rn, index, op.Size + 1, signed); - Operand me = EmitVectorExtract(context, op.Rm, part + index, op.Size, signed); + Operand ne = EmitVectorExtract(context, op.Rn, index, op.Size + 1, signed); + Operand me = EmitVectorExtract(context, op.Rm, part + index, op.Size, signed); res = EmitVectorInsert(context, res, emit(ne, me), index, op.Size + 1); } @@ -1077,9 +1077,9 @@ namespace ARMeilleure.Instructions for (int index = 0; index < elems; index++) { - Operand de = EmitVectorExtract(context, op.Rd, index, op.Size + 1, signed); - Operand ne = EmitVectorExtract(context, op.Rn, part + index, op.Size, signed); - Operand me = EmitVectorExtract(context, op.Rm, part + index, op.Size, signed); + Operand de = EmitVectorExtract(context, op.Rd, index, op.Size + 1, signed); + Operand ne = EmitVectorExtract(context, op.Rn, part + index, op.Size, signed); + Operand me = EmitVectorExtract(context, op.Rm, part + index, op.Size, signed); res = EmitVectorInsert(context, res, emit(de, ne, me), index, op.Size + 1); } @@ -1143,8 +1143,8 @@ namespace ARMeilleure.Instructions for (int index = 0; index < elems; index++) { - Operand de = EmitVectorExtract(context, op.Rd, index, op.Size + 1, signed); - Operand ne = EmitVectorExtract(context, op.Rn, part + index, op.Size, signed); + Operand de = EmitVectorExtract(context, op.Rd, index, op.Size + 1, signed); + Operand ne = EmitVectorExtract(context, op.Rn, part + index, op.Size, signed); res = EmitVectorInsert(context, res, emit(de, ne, me), index, op.Size + 1); } @@ -1174,13 +1174,13 @@ namespace ARMeilleure.Instructions { int pairIndex = index << 1; - Operand n0 = EmitVectorExtract(context, op.Rn, pairIndex, op.Size, signed); + Operand n0 = EmitVectorExtract(context, op.Rn, pairIndex, op.Size, signed); Operand n1 = EmitVectorExtract(context, op.Rn, pairIndex + 1, op.Size, signed); - Operand m0 = EmitVectorExtract(context, op.Rm, pairIndex, op.Size, signed); + Operand m0 = EmitVectorExtract(context, op.Rm, pairIndex, op.Size, signed); Operand m1 = EmitVectorExtract(context, op.Rm, pairIndex + 1, op.Size, signed); - res = EmitVectorInsert(context, res, emit(n0, n1), index, op.Size); + res = EmitVectorInsert(context, res, emit(n0, n1), index, op.Size); res = EmitVectorInsert(context, res, emit(m0, m1), pairs + index, op.Size); } @@ -1197,11 +1197,11 @@ namespace ARMeilleure.Instructions if (op.RegisterSize == RegisterSize.Simd64) { Operand zeroEvenMask = X86GetElements(context, ZeroMask, EvenMasks[op.Size]); - Operand zeroOddMask = X86GetElements(context, ZeroMask, OddMasks [op.Size]); + Operand zeroOddMask = X86GetElements(context, ZeroMask, OddMasks[op.Size]); Operand mN = context.AddIntrinsic(Intrinsic.X86Punpcklqdq, n, m); // m:n - Operand left = context.AddIntrinsic(Intrinsic.X86Pshufb, mN, zeroEvenMask); // 0:even from m:n + Operand left = context.AddIntrinsic(Intrinsic.X86Pshufb, mN, zeroEvenMask); // 0:even from m:n Operand right = context.AddIntrinsic(Intrinsic.X86Pshufb, mN, zeroOddMask); // 0:odd from m:n context.Copy(GetVec(op.Rd), context.AddIntrinsic(inst[op.Size], left, right)); @@ -1213,14 +1213,14 @@ namespace ARMeilleure.Instructions Operand oddEvenN = context.AddIntrinsic(Intrinsic.X86Pshufb, n, oddEvenMask); // odd:even from n Operand oddEvenM = context.AddIntrinsic(Intrinsic.X86Pshufb, m, oddEvenMask); // odd:even from m - Operand left = context.AddIntrinsic(Intrinsic.X86Punpcklqdq, oddEvenN, oddEvenM); + Operand left = context.AddIntrinsic(Intrinsic.X86Punpcklqdq, oddEvenN, oddEvenM); Operand right = context.AddIntrinsic(Intrinsic.X86Punpckhqdq, oddEvenN, oddEvenM); context.Copy(GetVec(op.Rd), context.AddIntrinsic(inst[op.Size], left, right)); } else { - Operand left = context.AddIntrinsic(Intrinsic.X86Punpcklqdq, n, m); + Operand left = context.AddIntrinsic(Intrinsic.X86Punpcklqdq, n, m); Operand right = context.AddIntrinsic(Intrinsic.X86Punpckhqdq, n, m); context.Copy(GetVec(op.Rd), context.AddIntrinsic(inst[3], left, right)); @@ -1299,17 +1299,17 @@ namespace ARMeilleure.Instructions Debug.Assert((op.Size & 1) == 0 && op.RegisterSize == RegisterSize.Simd128); - const int sm0 = 0 << 6 | 0 << 4 | 0 << 2 | 0 << 0; - const int sm1 = 1 << 6 | 1 << 4 | 1 << 2 | 1 << 0; - const int sm2 = 2 << 6 | 2 << 4 | 2 << 2 | 2 << 0; - const int sm3 = 3 << 6 | 3 << 4 | 3 << 2 | 3 << 0; + const int SM0 = 0 << 6 | 0 << 4 | 0 << 2 | 0 << 0; + const int SM1 = 1 << 6 | 1 << 4 | 1 << 2 | 1 << 0; + const int SM2 = 2 << 6 | 2 << 4 | 2 << 2 | 2 << 0; + const int SM3 = 3 << 6 | 3 << 4 | 3 << 2 | 3 << 0; Operand nCopy = context.Copy(GetVec(op.Rn)); - Operand part0 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(sm0)); - Operand part1 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(sm1)); - Operand part2 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(sm2)); - Operand part3 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(sm3)); + Operand part0 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(SM0)); + Operand part1 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(SM1)); + Operand part2 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(SM2)); + Operand part3 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, nCopy, Const(SM3)); Operand res = emit(emit(part0, part1), emit(part2, part3)); @@ -1340,13 +1340,13 @@ namespace ARMeilleure.Instructions if ((op.Size & 1) == 0) { - const int sm0 = 2 << 6 | 2 << 4 | 2 << 2 | 0 << 0; - const int sm1 = 2 << 6 | 2 << 4 | 2 << 2 | 1 << 0; + const int SM0 = 2 << 6 | 2 << 4 | 2 << 2 | 0 << 0; + const int SM1 = 2 << 6 | 2 << 4 | 2 << 2 | 1 << 0; Operand zeroN = context.VectorZeroUpper64(n); - op0 = context.AddIntrinsic(Intrinsic.X86Pshufd, zeroN, Const(sm0)); - op1 = context.AddIntrinsic(Intrinsic.X86Pshufd, zeroN, Const(sm1)); + op0 = context.AddIntrinsic(Intrinsic.X86Pshufd, zeroN, Const(SM0)); + op1 = context.AddIntrinsic(Intrinsic.X86Pshufd, zeroN, Const(SM1)); } else /* if ((op.Size & 1) == 1) */ { @@ -1381,7 +1381,7 @@ namespace ARMeilleure.Instructions Operand m0 = context.VectorExtract(type, GetVec(op.Rm), pairIndex); Operand m1 = context.VectorExtract(type, GetVec(op.Rm), pairIndex + 1); - res = context.VectorInsert(res, emit(n0, n1), index); + res = context.VectorInsert(res, emit(n0, n1), index); res = context.VectorInsert(res, emit(m0, m1), pairs + index); } @@ -1412,11 +1412,11 @@ namespace ARMeilleure.Instructions } else /* if (op.RegisterSize == RegisterSize.Simd128) */ { - const int sm0 = 2 << 6 | 0 << 4 | 2 << 2 | 0 << 0; - const int sm1 = 3 << 6 | 1 << 4 | 3 << 2 | 1 << 0; + const int SM0 = 2 << 6 | 0 << 4 | 2 << 2 | 0 << 0; + const int SM1 = 3 << 6 | 1 << 4 | 3 << 2 | 1 << 0; - Operand part0 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, mCopy, Const(sm0)); - Operand part1 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, mCopy, Const(sm1)); + Operand part0 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, mCopy, Const(SM0)); + Operand part1 = context.AddIntrinsic(Intrinsic.X86Shufps, nCopy, mCopy, Const(SM1)); context.Copy(GetVec(op.Rd), emit(part0, part1)); } @@ -1433,18 +1433,18 @@ namespace ARMeilleure.Instructions public enum CmpCondition { // Legacy Sse. - Equal = 0, // Ordered, non-signaling. - LessThan = 1, // Ordered, signaling. - LessThanOrEqual = 2, // Ordered, signaling. - UnorderedQ = 3, // Non-signaling. - NotLessThan = 5, // Unordered, signaling. + Equal = 0, // Ordered, non-signaling. + LessThan = 1, // Ordered, signaling. + LessThanOrEqual = 2, // Ordered, signaling. + UnorderedQ = 3, // Non-signaling. + NotLessThan = 5, // Unordered, signaling. NotLessThanOrEqual = 6, // Unordered, signaling. - OrderedQ = 7, // Non-signaling. + OrderedQ = 7, // Non-signaling. // Vex. GreaterThanOrEqual = 13, // Ordered, signaling. - GreaterThan = 14, // Ordered, signaling. - OrderedS = 23 // Signaling. + GreaterThan = 14, // Ordered, signaling. + OrderedS = 23, // Signaling. } [Flags] @@ -1459,7 +1459,7 @@ namespace ARMeilleure.Instructions Add = 1 << 3, Sub = 1 << 4, - Accumulate = 1 << 5 + Accumulate = 1 << 5, } public static void EmitScalarSaturatingUnaryOpSx(ArmEmitterContext context, Func1I emit) @@ -1579,7 +1579,7 @@ namespace ARMeilleure.Instructions { Operand de; Operand ne = EmitVectorExtract(context, op.Rn, index, op.Size, !signed); - Operand me = EmitVectorExtract(context, op.Rd, index, op.Size, signed); + Operand me = EmitVectorExtract(context, op.Rd, index, op.Size, signed); if (op.Size <= 2) { @@ -1627,7 +1627,7 @@ namespace ARMeilleure.Instructions [Flags] public enum SaturatingNarrowFlags { - Scalar = 1 << 0, + Scalar = 1 << 0, SignedSrc = 1 << 1, SignedDst = 1 << 2, @@ -1637,14 +1637,14 @@ namespace ARMeilleure.Instructions VectorSxSx = SignedSrc | SignedDst, VectorSxZx = SignedSrc, - VectorZxZx = 0 + VectorZxZx = 0, } public static void EmitSaturatingNarrowOp(ArmEmitterContext context, SaturatingNarrowFlags flags) { OpCodeSimd op = (OpCodeSimd)context.CurrOp; - bool scalar = (flags & SaturatingNarrowFlags.Scalar) != 0; + bool scalar = (flags & SaturatingNarrowFlags.Scalar) != 0; bool signedSrc = (flags & SaturatingNarrowFlags.SignedSrc) != 0; bool signedDst = (flags & SaturatingNarrowFlags.SignedDst) != 0; @@ -2034,18 +2034,30 @@ namespace ARMeilleure.Instructions { switch (size) { - case 0: res = context.SignExtend8 (OperandType.I64, res); break; - case 1: res = context.SignExtend16(OperandType.I64, res); break; - case 2: res = context.SignExtend32(OperandType.I64, res); break; + case 0: + res = context.SignExtend8(OperandType.I64, res); + break; + case 1: + res = context.SignExtend16(OperandType.I64, res); + break; + case 2: + res = context.SignExtend32(OperandType.I64, res); + break; } } else { switch (size) { - case 0: res = context.ZeroExtend8 (OperandType.I64, res); break; - case 1: res = context.ZeroExtend16(OperandType.I64, res); break; - case 2: res = context.ZeroExtend32(OperandType.I64, res); break; + case 0: + res = context.ZeroExtend8(OperandType.I64, res); + break; + case 1: + res = context.ZeroExtend16(OperandType.I64, res); + break; + case 2: + res = context.ZeroExtend32(OperandType.I64, res); + break; } } @@ -2063,10 +2075,18 @@ namespace ARMeilleure.Instructions switch (size) { - case 0: vector = context.VectorInsert8 (vector, value, index); break; - case 1: vector = context.VectorInsert16(vector, value, index); break; - case 2: vector = context.VectorInsert (vector, value, index); break; - case 3: vector = context.VectorInsert (vector, value, index); break; + case 0: + vector = context.VectorInsert8(vector, value, index); + break; + case 1: + vector = context.VectorInsert16(vector, value, index); + break; + case 2: + vector = context.VectorInsert(vector, value, index); + break; + case 3: + vector = context.VectorInsert(vector, value, index); + break; } return vector; diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHelper32.cs b/src/ARMeilleure/Instructions/InstEmitSimdHelper32.cs index 36d27d425..c1c59b87b 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHelper32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHelper32.cs @@ -4,7 +4,6 @@ using ARMeilleure.Translation; using System; using System.Diagnostics; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -19,18 +18,13 @@ namespace ARMeilleure.Instructions { public static (int, int) GetQuadwordAndSubindex(int index, RegisterSize size) { - switch (size) + return size switch { - case RegisterSize.Simd128: - return (index >> 1, 0); - case RegisterSize.Simd64: - case RegisterSize.Int64: - return (index >> 1, index & 1); - case RegisterSize.Int32: - return (index >> 2, index & 3); - } - - throw new ArgumentException("Unrecognized Vector Register Size."); + RegisterSize.Simd128 => (index >> 1, 0), + RegisterSize.Simd64 or RegisterSize.Int64 => (index >> 1, index & 1), + RegisterSize.Int32 => (index >> 2, index & 3), + _ => throw new ArgumentException("Unrecognized Vector Register Size."), + }; } public static Operand ExtractScalar(ArmEmitterContext context, OperandType type, int reg) @@ -327,7 +321,7 @@ namespace ARMeilleure.Instructions for (int index = 0; index < elems; index++) { Operand ne = EmitVectorExtract32(context, op.Qn, op.In + index, op.Size + 1, signed); - Operand me = EmitVectorExtract32(context, op.Qm, op.Im + index, op.Size, signed); + Operand me = EmitVectorExtract32(context, op.Qm, op.Im + index, op.Size, signed); if (op.Size == 2) { @@ -380,8 +374,8 @@ namespace ARMeilleure.Instructions for (int index = 0; index < elems; index++) { Operand de = EmitVectorExtract32(context, op.Qd, op.Id + index, op.Size + 1, signed); - Operand ne = EmitVectorExtract32(context, op.Qn, op.In + index, op.Size, signed); - Operand me = EmitVectorExtract32(context, op.Qm, op.Im + index, op.Size, signed); + Operand ne = EmitVectorExtract32(context, op.Qn, op.In + index, op.Size, signed); + Operand me = EmitVectorExtract32(context, op.Qm, op.Im + index, op.Size, signed); if (op.Size == 2) { @@ -778,7 +772,10 @@ namespace ARMeilleure.Instructions { // Index into 0, 0 into index. This swap happens at the start of an A32 scalar op if required. int index = reg & (doubleWidth ? 1 : 3); - if (index == 0) return target; + if (index == 0) + { + return target; + } if (doubleWidth) { @@ -974,7 +971,7 @@ namespace ARMeilleure.Instructions Intrinsic inst = (op.Size & 1) != 0 ? inst64 : inst32; - EmitScalarBinaryOpSimd32(context, (n, m) => context.AddIntrinsic(inst, n, m)); + EmitScalarBinaryOpSimd32(context, (n, m) => context.AddIntrinsic(inst, n, m)); } public static void EmitScalarTernaryOpSimd32(ArmEmitterContext context, Func3I scalarFunc) @@ -1195,7 +1192,7 @@ namespace ARMeilleure.Instructions : typeof(SoftFloat64).GetMethod(name); Array.Resize(ref callArgs, callArgs.Length + 1); - callArgs[callArgs.Length - 1] = Const(1); + callArgs[^1] = Const(1); context.ExitArmFpMode(); context.StoreToContext(); @@ -1245,16 +1242,24 @@ namespace ARMeilleure.Instructions { switch (size) { - case 0: res = context.SignExtend8(OperandType.I32, res); break; - case 1: res = context.SignExtend16(OperandType.I32, res); break; + case 0: + res = context.SignExtend8(OperandType.I32, res); + break; + case 1: + res = context.SignExtend16(OperandType.I32, res); + break; } } else { switch (size) { - case 0: res = context.ZeroExtend8(OperandType.I32, res); break; - case 1: res = context.ZeroExtend16(OperandType.I32, res); break; + case 0: + res = context.ZeroExtend8(OperandType.I32, res); + break; + case 1: + res = context.ZeroExtend16(OperandType.I32, res); + break; } } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHelper32Arm64.cs b/src/ARMeilleure/Instructions/InstEmitSimdHelper32Arm64.cs index 98236be6d..568c07122 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHelper32Arm64.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHelper32Arm64.cs @@ -1,11 +1,9 @@ - using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System; using System.Diagnostics; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -74,7 +72,10 @@ namespace ARMeilleure.Instructions public static Operand EmitExtractScalar(ArmEmitterContext context, Operand target, int reg, bool doubleWidth) { int index = reg & (doubleWidth ? 1 : 3); - if (index == 0) return target; // Element is already at index 0, so just return the vector directly. + if (index == 0) + { + return target; // Element is already at index 0, so just return the vector directly. + } if (doubleWidth) { @@ -192,11 +193,10 @@ namespace ARMeilleure.Instructions EmitVectorTernaryOpSimd32(context, (d, n, m) => context.AddIntrinsic(inst, d, n, m)); } - public static void EmitScalarUnaryOpSimd32(ArmEmitterContext context, Func1I scalarFunc) + public static void EmitScalarUnaryOpSimd32(ArmEmitterContext context, Func1I scalarFunc, bool doubleSize) { OpCode32SimdS op = (OpCode32SimdS)context.CurrOp; - bool doubleSize = (op.Size & 1) != 0; int shift = doubleSize ? 1 : 2; Operand m = GetVecA32(op.Vm >> shift); Operand d = GetVecA32(op.Vd >> shift); @@ -215,8 +215,13 @@ namespace ARMeilleure.Instructions { OpCode32SimdS op = (OpCode32SimdS)context.CurrOp; - inst |= ((op.Size & 1) != 0 ? Intrinsic.Arm64VDouble : Intrinsic.Arm64VFloat) | Intrinsic.Arm64V128; - EmitScalarUnaryOpSimd32(context, (m) => (inst == 0) ? m : context.AddIntrinsic(inst, m)); + EmitScalarUnaryOpF32(context, inst, (op.Size & 1) != 0); + } + + public static void EmitScalarUnaryOpF32(ArmEmitterContext context, Intrinsic inst, bool doubleSize) + { + inst |= (doubleSize ? Intrinsic.Arm64VDouble : Intrinsic.Arm64VFloat) | Intrinsic.Arm64V128; + EmitScalarUnaryOpSimd32(context, (m) => (inst == 0) ? m : context.AddIntrinsic(inst, m), doubleSize); } public static void EmitScalarBinaryOpSimd32(ArmEmitterContext context, Func2I scalarFunc) @@ -245,7 +250,7 @@ namespace ARMeilleure.Instructions OpCode32SimdRegS op = (OpCode32SimdRegS)context.CurrOp; inst |= ((op.Size & 1) != 0 ? Intrinsic.Arm64VDouble : Intrinsic.Arm64VFloat) | Intrinsic.Arm64V128; - EmitScalarBinaryOpSimd32(context, (n, m) => context.AddIntrinsic(inst, n, m)); + EmitScalarBinaryOpSimd32(context, (n, m) => context.AddIntrinsic(inst, n, m)); } public static void EmitScalarTernaryOpSimd32(ArmEmitterContext context, Func3I scalarFunc) @@ -332,16 +337,17 @@ namespace ARMeilleure.Instructions CmpCondition.GreaterThanOrEqual => Intrinsic.Arm64FcmgeVz, CmpCondition.LessThan => Intrinsic.Arm64FcmltVz, CmpCondition.LessThanOrEqual => Intrinsic.Arm64FcmleVz, - _ => throw new InvalidOperationException() + _ => throw new InvalidOperationException(), }; } - else { + else + { inst = cond switch { CmpCondition.Equal => Intrinsic.Arm64FcmeqV, CmpCondition.GreaterThan => Intrinsic.Arm64FcmgtV, CmpCondition.GreaterThanOrEqual => Intrinsic.Arm64FcmgeV, - _ => throw new InvalidOperationException() + _ => throw new InvalidOperationException(), }; } @@ -363,4 +369,4 @@ namespace ARMeilleure.Instructions } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitSimdHelperArm64.cs b/src/ARMeilleure/Instructions/InstEmitSimdHelperArm64.cs index f0d242ae2..70dfc0fbd 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdHelperArm64.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdHelperArm64.cs @@ -50,7 +50,7 @@ namespace ARMeilleure.Instructions } SetIntOrZR(context, op.Rd, op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (inst, n) + ? context.AddIntrinsicInt(inst, n) : context.AddIntrinsicLong(inst, n)); } @@ -288,7 +288,7 @@ namespace ARMeilleure.Instructions } SetIntOrZR(context, op.Rd, op.RegisterSize == RegisterSize.Int32 - ? context.AddIntrinsicInt (inst, n, Const(fBits)) + ? context.AddIntrinsicInt(inst, n, Const(fBits)) : context.AddIntrinsicLong(inst, n, Const(fBits))); } @@ -695,7 +695,7 @@ namespace ARMeilleure.Instructions { OpCodeSimdReg op = (OpCodeSimdReg)context.CurrOp; - bool cmpWithZero = !(op is OpCodeSimdFcond) ? op.Bit3 : false; + bool cmpWithZero = op is not OpCodeSimdFcond && op.Bit3; Intrinsic inst = signalNaNs ? Intrinsic.Arm64FcmpeS : Intrinsic.Arm64FcmpS; @@ -717,4 +717,4 @@ namespace ARMeilleure.Instructions SetFlag(context, PState.NFlag, context.BitwiseAnd(context.ShiftRightUI(nzcv, Const(31)), one)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitSimdLogical.cs b/src/ARMeilleure/Instructions/InstEmitSimdLogical.cs index 2bf531e6c..ace8e4c54 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdLogical.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdLogical.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; using System.Diagnostics; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -80,10 +79,11 @@ namespace ARMeilleure.Instructions int eSize = 8 << op.Size; Operand d = GetVec(op.Rd); - Operand imm = eSize switch { + Operand imm = eSize switch + { 16 => X86GetAllElements(context, (short)~op.Immediate), 32 => X86GetAllElements(context, (int)~op.Immediate), - _ => throw new InvalidOperationException($"Invalid element size {eSize}.") + _ => throw new InvalidOperationException($"Invalid element size {eSize}."), }; Operand res = context.AddIntrinsic(Intrinsic.X86Pand, d, imm); @@ -380,10 +380,11 @@ namespace ARMeilleure.Instructions int eSize = 8 << op.Size; Operand d = GetVec(op.Rd); - Operand imm = eSize switch { + Operand imm = eSize switch + { 16 => X86GetAllElements(context, (short)op.Immediate), 32 => X86GetAllElements(context, (int)op.Immediate), - _ => throw new InvalidOperationException($"Invalid element size {eSize}.") + _ => throw new InvalidOperationException($"Invalid element size {eSize}."), }; Operand res = context.AddIntrinsic(Intrinsic.X86Por, d, imm); @@ -407,17 +408,17 @@ namespace ARMeilleure.Instructions if (Optimizations.UseGfni) { - const long bitMatrix = + const long BitMatrix = (0b10000000L << 56) | (0b01000000L << 48) | (0b00100000L << 40) | (0b00010000L << 32) | (0b00001000L << 24) | (0b00000100L << 16) | - (0b00000010L << 8) | - (0b00000001L << 0); + (0b00000010L << 8) | + (0b00000001L << 0); - Operand vBitMatrix = X86GetAllElements(context, bitMatrix); + Operand vBitMatrix = X86GetAllElements(context, BitMatrix); Operand res = context.AddIntrinsic(Intrinsic.X86Gf2p8affineqb, GetVec(op.Rn), vBitMatrix, Const(0)); @@ -451,13 +452,13 @@ namespace ARMeilleure.Instructions Debug.Assert(op.Type == OperandType.I64); Operand val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(op, Const(0xaaul)), Const(1)), - context.ShiftLeft (context.BitwiseAnd(op, Const(0x55ul)), Const(1))); + context.ShiftLeft(context.BitwiseAnd(op, Const(0x55ul)), Const(1))); val = context.BitwiseOr(context.ShiftRightUI(context.BitwiseAnd(val, Const(0xccul)), Const(2)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x33ul)), Const(2))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x33ul)), Const(2))); return context.BitwiseOr(context.ShiftRightUI(val, Const(4)), - context.ShiftLeft (context.BitwiseAnd(val, Const(0x0ful)), Const(4))); + context.ShiftLeft(context.BitwiseAnd(val, Const(0x0ful)), Const(4))); } public static void Rev16_V(ArmEmitterContext context) @@ -468,12 +469,12 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); - const long maskE0 = 06L << 56 | 07L << 48 | 04L << 40 | 05L << 32 | 02L << 24 | 03L << 16 | 00L << 8 | 01L << 0; - const long maskE1 = 14L << 56 | 15L << 48 | 12L << 40 | 13L << 32 | 10L << 24 | 11L << 16 | 08L << 8 | 09L << 0; + const long MaskE0 = 06L << 56 | 07L << 48 | 04L << 40 | 05L << 32 | 02L << 24 | 03L << 16 | 00L << 8 | 01L << 0; + const long MaskE1 = 14L << 56 | 15L << 48 | 12L << 40 | 13L << 32 | 10L << 24 | 11L << 16 | 08L << 8 | 09L << 0; - Operand mask = X86GetScalar(context, maskE0); + Operand mask = X86GetScalar(context, MaskE0); - mask = EmitVectorInsert(context, mask, Const(maskE1), 1, 3); + mask = EmitVectorInsert(context, mask, Const(MaskE1), 1, 3); Operand res = context.AddIntrinsic(Intrinsic.X86Pshufb, n, mask); @@ -502,21 +503,21 @@ namespace ARMeilleure.Instructions if (op.Size == 0) { - const long maskE0 = 04L << 56 | 05L << 48 | 06L << 40 | 07L << 32 | 00L << 24 | 01L << 16 | 02L << 8 | 03L << 0; - const long maskE1 = 12L << 56 | 13L << 48 | 14L << 40 | 15L << 32 | 08L << 24 | 09L << 16 | 10L << 8 | 11L << 0; + const long MaskE0 = 04L << 56 | 05L << 48 | 06L << 40 | 07L << 32 | 00L << 24 | 01L << 16 | 02L << 8 | 03L << 0; + const long MaskE1 = 12L << 56 | 13L << 48 | 14L << 40 | 15L << 32 | 08L << 24 | 09L << 16 | 10L << 8 | 11L << 0; - mask = X86GetScalar(context, maskE0); + mask = X86GetScalar(context, MaskE0); - mask = EmitVectorInsert(context, mask, Const(maskE1), 1, 3); + mask = EmitVectorInsert(context, mask, Const(MaskE1), 1, 3); } else /* if (op.Size == 1) */ { - const long maskE0 = 05L << 56 | 04L << 48 | 07L << 40 | 06L << 32 | 01L << 24 | 00L << 16 | 03L << 8 | 02L << 0; - const long maskE1 = 13L << 56 | 12L << 48 | 15L << 40 | 14L << 32 | 09L << 24 | 08L << 16 | 11L << 8 | 10L << 0; + const long MaskE0 = 05L << 56 | 04L << 48 | 07L << 40 | 06L << 32 | 01L << 24 | 00L << 16 | 03L << 8 | 02L << 0; + const long MaskE1 = 13L << 56 | 12L << 48 | 15L << 40 | 14L << 32 | 09L << 24 | 08L << 16 | 11L << 8 | 10L << 0; - mask = X86GetScalar(context, maskE0); + mask = X86GetScalar(context, MaskE0); - mask = EmitVectorInsert(context, mask, Const(maskE1), 1, 3); + mask = EmitVectorInsert(context, mask, Const(MaskE1), 1, 3); } Operand res = context.AddIntrinsic(Intrinsic.X86Pshufb, n, mask); @@ -546,30 +547,30 @@ namespace ARMeilleure.Instructions if (op.Size == 0) { - const long maskE0 = 00L << 56 | 01L << 48 | 02L << 40 | 03L << 32 | 04L << 24 | 05L << 16 | 06L << 8 | 07L << 0; - const long maskE1 = 08L << 56 | 09L << 48 | 10L << 40 | 11L << 32 | 12L << 24 | 13L << 16 | 14L << 8 | 15L << 0; + const long MaskE0 = 00L << 56 | 01L << 48 | 02L << 40 | 03L << 32 | 04L << 24 | 05L << 16 | 06L << 8 | 07L << 0; + const long MaskE1 = 08L << 56 | 09L << 48 | 10L << 40 | 11L << 32 | 12L << 24 | 13L << 16 | 14L << 8 | 15L << 0; - mask = X86GetScalar(context, maskE0); + mask = X86GetScalar(context, MaskE0); - mask = EmitVectorInsert(context, mask, Const(maskE1), 1, 3); + mask = EmitVectorInsert(context, mask, Const(MaskE1), 1, 3); } else if (op.Size == 1) { - const long maskE0 = 01L << 56 | 00L << 48 | 03L << 40 | 02L << 32 | 05L << 24 | 04L << 16 | 07L << 8 | 06L << 0; - const long maskE1 = 09L << 56 | 08L << 48 | 11L << 40 | 10L << 32 | 13L << 24 | 12L << 16 | 15L << 8 | 14L << 0; + const long MaskE0 = 01L << 56 | 00L << 48 | 03L << 40 | 02L << 32 | 05L << 24 | 04L << 16 | 07L << 8 | 06L << 0; + const long MaskE1 = 09L << 56 | 08L << 48 | 11L << 40 | 10L << 32 | 13L << 24 | 12L << 16 | 15L << 8 | 14L << 0; - mask = X86GetScalar(context, maskE0); + mask = X86GetScalar(context, MaskE0); - mask = EmitVectorInsert(context, mask, Const(maskE1), 1, 3); + mask = EmitVectorInsert(context, mask, Const(MaskE1), 1, 3); } else /* if (op.Size == 2) */ { - const long maskE0 = 03L << 56 | 02L << 48 | 01L << 40 | 00L << 32 | 07L << 24 | 06L << 16 | 05L << 8 | 04L << 0; - const long maskE1 = 11L << 56 | 10L << 48 | 09L << 40 | 08L << 32 | 15L << 24 | 14L << 16 | 13L << 8 | 12L << 0; + const long MaskE0 = 03L << 56 | 02L << 48 | 01L << 40 | 00L << 32 | 07L << 24 | 06L << 16 | 05L << 8 | 04L << 0; + const long MaskE1 = 11L << 56 | 10L << 48 | 09L << 40 | 08L << 32 | 15L << 24 | 14L << 16 | 13L << 8 | 12L << 0; - mask = X86GetScalar(context, maskE0); + mask = X86GetScalar(context, MaskE0); - mask = EmitVectorInsert(context, mask, Const(maskE1), 1, 3); + mask = EmitVectorInsert(context, mask, Const(MaskE1), 1, 3); } Operand res = context.AddIntrinsic(Intrinsic.X86Pshufb, n, mask); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdLogical32.cs b/src/ARMeilleure/Instructions/InstEmitSimdLogical32.cs index 68ef4ed17..747acb101 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdLogical32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdLogical32.cs @@ -52,9 +52,15 @@ namespace ARMeilleure.Instructions // Replicate fields to fill the 64-bits, if size is < 64-bits. switch (op.Size) { - case 0: immediate *= 0x0101010101010101L; break; - case 1: immediate *= 0x0001000100010001L; break; - case 2: immediate *= 0x0000000100000001L; break; + case 0: + immediate *= 0x0101010101010101L; + break; + case 1: + immediate *= 0x0001000100010001L; + break; + case 2: + immediate *= 0x0000000100000001L; + break; } Operand imm = Const(immediate); @@ -199,9 +205,15 @@ namespace ARMeilleure.Instructions // Replicate fields to fill the 64-bits, if size is < 64-bits. switch (op.Size) { - case 0: immediate *= 0x0101010101010101L; break; - case 1: immediate *= 0x0001000100010001L; break; - case 2: immediate *= 0x0000000100000001L; break; + case 0: + immediate *= 0x0101010101010101L; + break; + case 1: + immediate *= 0x0001000100010001L; + break; + case 2: + immediate *= 0x0000000100000001L; + break; } Operand imm = Const(immediate); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdMemory.cs b/src/ARMeilleure/Instructions/InstEmitSimdMemory.cs index 9b19872af..dedf0fa05 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdMemory.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdMemory.cs @@ -40,6 +40,7 @@ namespace ARMeilleure.Instructions long offset = 0; +#pragma warning disable IDE0055 // Disable formatting for (int rep = 0; rep < op.Reps; rep++) for (int elem = 0; elem < op.Elems; elem++) for (int sElem = 0; sElem < op.SElems; sElem++) @@ -66,6 +67,7 @@ namespace ARMeilleure.Instructions offset += 1 << op.Size; } +#pragma warning restore IDE0055 if (op.WBack) { @@ -157,4 +159,4 @@ namespace ARMeilleure.Instructions context.Copy(n, context.Add(n, m)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/InstEmitSimdMove.cs b/src/ARMeilleure/Instructions/InstEmitSimdMove.cs index b58a32f69..85c98fe3a 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdMove.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdMove.cs @@ -3,7 +3,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System.Collections.Generic; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -12,19 +11,19 @@ namespace ARMeilleure.Instructions { static partial class InstEmit { -#region "Masks" + #region "Masks" private static readonly long[] _masksE0_Uzp = new long[] { 13L << 56 | 09L << 48 | 05L << 40 | 01L << 32 | 12L << 24 | 08L << 16 | 04L << 8 | 00L << 0, - 11L << 56 | 10L << 48 | 03L << 40 | 02L << 32 | 09L << 24 | 08L << 16 | 01L << 8 | 00L << 0 + 11L << 56 | 10L << 48 | 03L << 40 | 02L << 32 | 09L << 24 | 08L << 16 | 01L << 8 | 00L << 0, }; private static readonly long[] _masksE1_Uzp = new long[] { 15L << 56 | 11L << 48 | 07L << 40 | 03L << 32 | 14L << 24 | 10L << 16 | 06L << 8 | 02L << 0, - 15L << 56 | 14L << 48 | 07L << 40 | 06L << 32 | 13L << 24 | 12L << 16 | 05L << 8 | 04L << 0 + 15L << 56 | 14L << 48 | 07L << 40 | 06L << 32 | 13L << 24 | 12L << 16 | 05L << 8 | 04L << 0, }; -#endregion + #endregion public static void Dup_Gp(ArmEmitterContext context) { @@ -36,9 +35,17 @@ namespace ARMeilleure.Instructions { switch (op.Size) { - case 0: n = context.ZeroExtend8 (n.Type, n); n = context.Multiply(n, Const(n.Type, 0x01010101)); break; - case 1: n = context.ZeroExtend16(n.Type, n); n = context.Multiply(n, Const(n.Type, 0x00010001)); break; - case 2: n = context.ZeroExtend32(n.Type, n); break; + case 0: + n = context.ZeroExtend8(n.Type, n); + n = context.Multiply(n, Const(n.Type, 0x01010101)); + break; + case 1: + n = context.ZeroExtend16(n.Type, n); + n = context.Multiply(n, Const(n.Type, 0x00010001)); + break; + case 2: + n = context.ZeroExtend32(n.Type, n); + break; } Operand res = context.VectorInsert(context.VectorZero(), n, 0); @@ -209,7 +216,7 @@ namespace ARMeilleure.Instructions OpCodeSimdFcond op = (OpCodeSimdFcond)context.CurrOp; Operand lblTrue = Label(); - Operand lblEnd = Label(); + Operand lblEnd = Label(); Operand isTrue = InstEmitFlowHelper.GetCondTrue(context, op.Cond); @@ -353,7 +360,7 @@ namespace ARMeilleure.Instructions { OpCodeSimdIns op = (OpCodeSimdIns)context.CurrOp; - Operand d = GetVec(op.Rd); + Operand d = GetVec(op.Rd); Operand ne = EmitVectorExtractZx(context, op.Rn, op.SrcIndex, op.Size); context.Copy(d, EmitVectorInsert(context, d, ne, op.DstIndex, op.Size)); @@ -497,8 +504,12 @@ namespace ARMeilleure.Instructions switch (op.Size) { - case 0: imm *= 0x01010101; break; - case 1: imm *= 0x00010001; break; + case 0: + imm *= 0x01010101; + break; + case 1: + imm *= 0x00010001; + break; } if (not) @@ -543,7 +554,7 @@ namespace ARMeilleure.Instructions Operand n = GetVec(op.Rn); Operand mMask = context.AddIntrinsic(Intrinsic.X86Pcmpgtb, m, mask); - mMask = context.AddIntrinsic(Intrinsic.X86Por, mMask, m); + mMask = context.AddIntrinsic(Intrinsic.X86Por, mMask, m); res = context.AddIntrinsic(Intrinsic.X86Pshufb, n, mMask); } @@ -557,7 +568,7 @@ namespace ARMeilleure.Instructions Operand mSubMask = context.AddIntrinsic(Intrinsic.X86Psubb, m, idxMask); Operand mMask = context.AddIntrinsic(Intrinsic.X86Pcmpgtb, mSubMask, mask); - mMask = context.AddIntrinsic(Intrinsic.X86Por, mMask, mSubMask); + mMask = context.AddIntrinsic(Intrinsic.X86Por, mMask, mSubMask); Operand res2 = context.AddIntrinsic(Intrinsic.X86Pshufb, ni, mMask); @@ -566,7 +577,7 @@ namespace ARMeilleure.Instructions if (!isTbl) { - Operand idxMask = X86GetAllElements(context, (0x1010101010101010L * op.Size) - 0x0101010101010101L); + Operand idxMask = X86GetAllElements(context, (0x1010101010101010L * op.Size) - 0x0101010101010101L); Operand zeroMask = context.VectorZero(); Operand mPosMask = context.AddIntrinsic(Intrinsic.X86Pcmpgtb, m, idxMask); @@ -590,7 +601,7 @@ namespace ARMeilleure.Instructions { Operand d = GetVec(op.Rd); - List args = new List(); + List args = new(); if (!isTbl) { @@ -612,20 +623,36 @@ namespace ARMeilleure.Instructions { switch (op.Size) { - case 1: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl1)); break; - case 2: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl2)); break; - case 3: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl3)); break; - case 4: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl4)); break; + case 1: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl1)); + break; + case 2: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl2)); + break; + case 3: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl3)); + break; + case 4: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbl4)); + break; } } else { switch (op.Size) { - case 1: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx1)); break; - case 2: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx2)); break; - case 3: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx3)); break; - case 4: info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx4)); break; + case 1: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx1)); + break; + case 2: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx2)); + break; + case 3: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx3)); + break; + case 4: + info = typeof(SoftFallback).GetMethod(nameof(SoftFallback.Tbx4)); + break; } } @@ -644,7 +671,7 @@ namespace ARMeilleure.Instructions if (op.Size < 3) { long maskE0 = EvenMasks[op.Size]; - long maskE1 = OddMasks [op.Size]; + long maskE1 = OddMasks[op.Size]; mask = X86GetScalar(context, maskE0); @@ -691,7 +718,7 @@ namespace ARMeilleure.Instructions Operand ne = EmitVectorExtractZx(context, op.Rn, pairIndex + part, op.Size); Operand me = EmitVectorExtractZx(context, op.Rm, pairIndex + part, op.Size); - res = EmitVectorInsert(context, res, ne, pairIndex, op.Size); + res = EmitVectorInsert(context, res, ne, pairIndex, op.Size); res = EmitVectorInsert(context, res, me, pairIndex + 1, op.Size); } @@ -712,7 +739,7 @@ namespace ARMeilleure.Instructions if (op.Size < 3) { long maskE0 = EvenMasks[op.Size]; - long maskE1 = OddMasks [op.Size]; + long maskE1 = OddMasks[op.Size]; mask = X86GetScalar(context, maskE0); @@ -784,7 +811,7 @@ namespace ARMeilleure.Instructions Operand ne = EmitVectorExtractZx(context, op.Rn, idx + part, op.Size); Operand me = EmitVectorExtractZx(context, op.Rm, idx + part, op.Size); - res = EmitVectorInsert(context, res, ne, index, op.Size); + res = EmitVectorInsert(context, res, ne, index, op.Size); res = EmitVectorInsert(context, res, me, pairs + index, op.Size); } @@ -839,7 +866,7 @@ namespace ARMeilleure.Instructions Operand ne = EmitVectorExtractZx(context, op.Rn, baseIndex + index, op.Size); Operand me = EmitVectorExtractZx(context, op.Rm, baseIndex + index, op.Size); - res = EmitVectorInsert(context, res, ne, pairIndex, op.Size); + res = EmitVectorInsert(context, res, ne, pairIndex, op.Size); res = EmitVectorInsert(context, res, me, pairIndex + 1, op.Size); } diff --git a/src/ARMeilleure/Instructions/InstEmitSimdMove32.cs b/src/ARMeilleure/Instructions/InstEmitSimdMove32.cs index b8b91b31d..050d35e9d 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdMove32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdMove32.cs @@ -2,7 +2,6 @@ using ARMeilleure.IntermediateRepresentation; using ARMeilleure.Translation; using System; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper32; @@ -17,13 +16,13 @@ namespace ARMeilleure.Instructions private static readonly long[] _masksE0_Uzp = new long[] { 13L << 56 | 09L << 48 | 05L << 40 | 01L << 32 | 12L << 24 | 08L << 16 | 04L << 8 | 00L << 0, - 11L << 56 | 10L << 48 | 03L << 40 | 02L << 32 | 09L << 24 | 08L << 16 | 01L << 8 | 00L << 0 + 11L << 56 | 10L << 48 | 03L << 40 | 02L << 32 | 09L << 24 | 08L << 16 | 01L << 8 | 00L << 0, }; private static readonly long[] _masksE1_Uzp = new long[] { 15L << 56 | 11L << 48 | 07L << 40 | 03L << 32 | 14L << 24 | 10L << 16 | 06L << 8 | 02L << 0, - 15L << 56 | 14L << 48 | 07L << 40 | 06L << 32 | 13L << 24 | 12L << 16 | 05L << 8 | 04L << 0 + 15L << 56 | 14L << 48 | 07L << 40 | 06L << 32 | 13L << 24 | 12L << 16 | 05L << 8 | 04L << 0, }; #endregion @@ -220,7 +219,7 @@ namespace ARMeilleure.Instructions for (int index = 1; index < length; index++) { int newVn = (op.Vn + index) & 0x1F; - (int qn, int ind) = GetQuadwordAndSubindex(newVn, op.RegisterSize); + (int qn, _) = GetQuadwordAndSubindex(newVn, op.RegisterSize); Operand ni = EmitMoveDoubleWordToSide(context, GetVecA32(qn), newVn, 0); Operand idxMask = X86GetAllElements(context, 0x0808080808080808L * index); diff --git a/src/ARMeilleure/Instructions/InstEmitSimdShift.cs b/src/ARMeilleure/Instructions/InstEmitSimdShift.cs index 19e41119b..be0670645 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdShift.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdShift.cs @@ -6,7 +6,6 @@ using ARMeilleure.Translation; using System; using System.Diagnostics; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -17,12 +16,12 @@ namespace ARMeilleure.Instructions static partial class InstEmit { -#region "Masks" + #region "Masks" private static readonly long[] _masks_SliSri = new long[] // Replication masks. { - 0x0101010101010101L, 0x0001000100010001L, 0x0000000100000001L, 0x0000000000000001L + 0x0101010101010101L, 0x0001000100010001L, 0x0000000100000001L, 0x0000000000000001L, }; -#endregion + #endregion public static void Rshrn_V(ArmEmitterContext context) { @@ -51,9 +50,15 @@ namespace ARMeilleure.Instructions switch (op.Size + 1) { - case 1: mask = X86GetAllElements(context, (int)roundConst * 0x00010001); break; - case 2: mask = X86GetAllElements(context, (int)roundConst); break; - case 3: mask = X86GetAllElements(context, roundConst); break; + case 1: + mask = X86GetAllElements(context, (int)roundConst * 0x00010001); + break; + case 2: + mask = X86GetAllElements(context, (int)roundConst); + break; + case 3: + mask = X86GetAllElements(context, roundConst); + break; } Intrinsic addInst = X86PaddInstruction[op.Size + 1]; @@ -1174,14 +1179,14 @@ namespace ARMeilleure.Instructions Scalar = 1 << 0, Signed = 1 << 1, - Round = 1 << 2, + Round = 1 << 2, Accumulate = 1 << 3, ScalarSx = Scalar | Signed, ScalarZx = Scalar, VectorSx = Signed, - VectorZx = 0 + VectorZx = 0, } private static void EmitScalarShrImmOpSx(ArmEmitterContext context, ShrImmFlags flags) @@ -1210,9 +1215,9 @@ namespace ARMeilleure.Instructions Operand res = context.VectorZero(); - bool scalar = (flags & ShrImmFlags.Scalar) != 0; - bool signed = (flags & ShrImmFlags.Signed) != 0; - bool round = (flags & ShrImmFlags.Round) != 0; + bool scalar = (flags & ShrImmFlags.Scalar) != 0; + bool signed = (flags & ShrImmFlags.Signed) != 0; + bool round = (flags & ShrImmFlags.Round) != 0; bool accumulate = (flags & ShrImmFlags.Accumulate) != 0; int shift = GetImmShr(op); @@ -1288,7 +1293,7 @@ namespace ARMeilleure.Instructions [Flags] private enum ShrImmSaturatingNarrowFlags { - Scalar = 1 << 0, + Scalar = 1 << 0, SignedSrc = 1 << 1, SignedDst = 1 << 2, @@ -1300,7 +1305,7 @@ namespace ARMeilleure.Instructions VectorSxSx = SignedSrc | SignedDst, VectorSxZx = SignedSrc, - VectorZxZx = 0 + VectorZxZx = 0, } private static void EmitRoundShrImmSaturatingNarrowOp(ArmEmitterContext context, ShrImmSaturatingNarrowFlags flags) @@ -1312,10 +1317,10 @@ namespace ARMeilleure.Instructions { OpCodeSimdShImm op = (OpCodeSimdShImm)context.CurrOp; - bool scalar = (flags & ShrImmSaturatingNarrowFlags.Scalar) != 0; + bool scalar = (flags & ShrImmSaturatingNarrowFlags.Scalar) != 0; bool signedSrc = (flags & ShrImmSaturatingNarrowFlags.SignedSrc) != 0; bool signedDst = (flags & ShrImmSaturatingNarrowFlags.SignedDst) != 0; - bool round = (flags & ShrImmSaturatingNarrowFlags.Round) != 0; + bool round = (flags & ShrImmSaturatingNarrowFlags.Round) != 0; int shift = GetImmShr(op); @@ -1585,7 +1590,7 @@ namespace ARMeilleure.Instructions Scalar = 1 << 0, Signed = 1 << 1, Round = 1 << 2, - Saturating = 1 << 3 + Saturating = 1 << 3, } private static void EmitShlRegOp(ArmEmitterContext context, ShlRegFlags flags = ShlRegFlags.None) diff --git a/src/ARMeilleure/Instructions/InstEmitSimdShift32.cs b/src/ARMeilleure/Instructions/InstEmitSimdShift32.cs index 9ac680884..5c7d48287 100644 --- a/src/ARMeilleure/Instructions/InstEmitSimdShift32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSimdShift32.cs @@ -5,7 +5,6 @@ using ARMeilleure.Translation; using System; using System.Diagnostics; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper; using static ARMeilleure.Instructions.InstEmitSimdHelper32; @@ -291,7 +290,7 @@ namespace ARMeilleure.Instructions VectorSxSx = SignedSrc | SignedDst, VectorSxZx = SignedSrc, - VectorZxZx = 0 + VectorZxZx = 0, } private static void EmitRoundShrImmSaturatingNarrowOp(ArmEmitterContext context, ShrImmSaturatingNarrowFlags flags) @@ -303,10 +302,10 @@ namespace ARMeilleure.Instructions { OpCode32SimdShImm op = (OpCode32SimdShImm)context.CurrOp; - bool scalar = (flags & ShrImmSaturatingNarrowFlags.Scalar) != 0; + bool scalar = (flags & ShrImmSaturatingNarrowFlags.Scalar) != 0; bool signedSrc = (flags & ShrImmSaturatingNarrowFlags.SignedSrc) != 0; bool signedDst = (flags & ShrImmSaturatingNarrowFlags.SignedDst) != 0; - bool round = (flags & ShrImmSaturatingNarrowFlags.Round) != 0; + bool round = (flags & ShrImmSaturatingNarrowFlags.Round) != 0; if (scalar) { diff --git a/src/ARMeilleure/Instructions/InstEmitSystem.cs b/src/ARMeilleure/Instructions/InstEmitSystem.cs index f84829aa1..8c430fc23 100644 --- a/src/ARMeilleure/Instructions/InstEmitSystem.cs +++ b/src/ARMeilleure/Instructions/InstEmitSystem.cs @@ -28,18 +28,39 @@ namespace ARMeilleure.Instructions switch (GetPackedId(op)) { - case 0b11_011_0000_0000_001: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCtrEl0)); break; - case 0b11_011_0000_0000_111: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetDczidEl0)); break; - case 0b11_011_0100_0010_000: EmitGetNzcv(context); return; - case 0b11_011_0100_0100_000: EmitGetFpcr(context); return; - case 0b11_011_0100_0100_001: EmitGetFpsr(context); return; - case 0b11_011_1101_0000_010: EmitGetTpidrEl0(context); return; - case 0b11_011_1101_0000_011: EmitGetTpidrroEl0(context); return; - case 0b11_011_1110_0000_000: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntfrqEl0)); break; - case 0b11_011_1110_0000_001: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntpctEl0)); break; - case 0b11_011_1110_0000_010: info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntvctEl0)); break; + case 0b11_011_0000_0000_001: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCtrEl0)); + break; + case 0b11_011_0000_0000_111: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetDczidEl0)); + break; + case 0b11_011_0100_0010_000: + EmitGetNzcv(context); + return; + case 0b11_011_0100_0100_000: + EmitGetFpcr(context); + return; + case 0b11_011_0100_0100_001: + EmitGetFpsr(context); + return; + case 0b11_011_1101_0000_010: + EmitGetTpidrEl0(context); + return; + case 0b11_011_1101_0000_011: + EmitGetTpidrroEl0(context); + return; + case 0b11_011_1110_0000_000: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntfrqEl0)); + break; + case 0b11_011_1110_0000_001: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntpctEl0)); + break; + case 0b11_011_1110_0000_010: + info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntvctEl0)); + break; - default: throw new NotImplementedException($"Unknown MRS 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); + default: + throw new NotImplementedException($"Unknown MRS 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); } SetIntOrZR(context, op.Rt, context.Call(info)); @@ -51,12 +72,21 @@ namespace ARMeilleure.Instructions switch (GetPackedId(op)) { - case 0b11_011_0100_0010_000: EmitSetNzcv(context); return; - case 0b11_011_0100_0100_000: EmitSetFpcr(context); return; - case 0b11_011_0100_0100_001: EmitSetFpsr(context); return; - case 0b11_011_1101_0000_010: EmitSetTpidrEl0(context); return; + case 0b11_011_0100_0010_000: + EmitSetNzcv(context); + return; + case 0b11_011_0100_0100_000: + EmitSetFpcr(context); + return; + case 0b11_011_0100_0100_001: + EmitSetFpsr(context); + return; + case 0b11_011_1101_0000_010: + EmitSetTpidrEl0(context); + return; - default: throw new NotImplementedException($"Unknown MSR 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); + default: + throw new NotImplementedException($"Unknown MSR 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); } } @@ -75,20 +105,20 @@ namespace ARMeilleure.Instructions switch (GetPackedId(op)) { case 0b11_011_0111_0100_001: - { - // DC ZVA - Operand t = GetIntOrZR(context, op.Rt); - - for (long offset = 0; offset < DczSizeInBytes; offset += 8) { - Operand address = context.Add(t, Const(offset)); + // DC ZVA + Operand t = GetIntOrZR(context, op.Rt); - InstEmitMemoryHelper.EmitStore(context, address, RegisterConsts.ZeroIndex, 3); + for (long offset = 0; offset < DczSizeInBytes; offset += 8) + { + Operand address = context.Add(t, Const(offset)); + + InstEmitMemoryHelper.EmitStore(context, address, RegisterConsts.ZeroIndex, 3); + } + + break; } - break; - } - // No-op case 0b11_011_0111_1110_001: // DC CIVAC break; @@ -104,7 +134,7 @@ namespace ARMeilleure.Instructions { int id; - id = op.Op2 << 0; + id = op.Op2 << 0; id |= op.CRm << 3; id |= op.CRn << 7; id |= op.Op1 << 11; @@ -188,7 +218,7 @@ namespace ARMeilleure.Instructions OpCodeSystem op = (OpCodeSystem)context.CurrOp; Operand nzcv = GetIntOrZR(context, op.Rt); - nzcv = context.ConvertI64ToI32(nzcv); + nzcv = context.ConvertI64ToI32(nzcv); SetFlag(context, PState.VFlag, context.BitwiseAnd(context.ShiftRightUI(nzcv, Const((int)PState.VFlag)), Const(1))); SetFlag(context, PState.CFlag, context.BitwiseAnd(context.ShiftRightUI(nzcv, Const((int)PState.CFlag)), Const(1))); @@ -201,7 +231,7 @@ namespace ARMeilleure.Instructions OpCodeSystem op = (OpCodeSystem)context.CurrOp; Operand fpcr = GetIntOrZR(context, op.Rt); - fpcr = context.ConvertI64ToI32(fpcr); + fpcr = context.ConvertI64ToI32(fpcr); for (int flag = 0; flag < RegisterConsts.FpFlagsCount; flag++) { @@ -221,7 +251,7 @@ namespace ARMeilleure.Instructions context.ClearQcFlagIfModified(); Operand fpsr = GetIntOrZR(context, op.Rt); - fpsr = context.ConvertI64ToI32(fpsr); + fpsr = context.ConvertI64ToI32(fpsr); for (int flag = 0; flag < RegisterConsts.FpFlagsCount; flag++) { diff --git a/src/ARMeilleure/Instructions/InstEmitSystem32.cs b/src/ARMeilleure/Instructions/InstEmitSystem32.cs index f2732c998..82e625715 100644 --- a/src/ARMeilleure/Instructions/InstEmitSystem32.cs +++ b/src/ARMeilleure/Instructions/InstEmitSystem32.cs @@ -4,7 +4,6 @@ using ARMeilleure.State; using ARMeilleure.Translation; using System; using System.Reflection; - using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -34,7 +33,8 @@ namespace ARMeilleure.Instructions switch (op.Opc2) { case 2: - EmitSetTpidrEl0(context); return; + EmitSetTpidrEl0(context); + return; default: throw new NotImplementedException($"Unknown MRC Opc2 0x{op.Opc2:X} at 0x{op.Address:X} (0x{op.RawOpCode:X})."); @@ -83,17 +83,13 @@ namespace ARMeilleure.Instructions throw new NotImplementedException($"Unknown MRC CRm 0x{op.CRm:X} at 0x{op.Address:X} (0x{op.RawOpCode:X})."); } - switch (op.Opc2) + result = op.Opc2 switch { - case 2: - result = EmitGetTpidrEl0(context); break; - - case 3: - result = EmitGetTpidrroEl0(context); break; - - default: - throw new NotImplementedException($"Unknown MRC Opc2 0x{op.Opc2:X} at 0x{op.Address:X} (0x{op.RawOpCode:X})."); - } + 2 => EmitGetTpidrEl0(context), + 3 => EmitGetTpidrroEl0(context), + _ => throw new NotImplementedException( + $"Unknown MRC Opc2 0x{op.Opc2:X} at 0x{op.Address:X} (0x{op.RawOpCode:X})."), + }; break; @@ -126,27 +122,16 @@ namespace ARMeilleure.Instructions } int opc = op.MrrcOp; - - MethodInfo info; - - switch (op.CRm) + MethodInfo info = op.CRm switch { - case 14: // Timer. - switch (opc) - { - case 0: - info = typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntpctEl0)); break; - - default: - throw new NotImplementedException($"Unknown MRRC Opc1 0x{opc:X} at 0x{op.Address:X} (0x{op.RawOpCode:X})."); - } - - break; - - default: - throw new NotImplementedException($"Unknown MRRC 0x{op.RawOpCode:X} at 0x{op.Address:X}."); - } - + // Timer. + 14 => opc switch + { + 0 => typeof(NativeInterface).GetMethod(nameof(NativeInterface.GetCntpctEl0)), + _ => throw new NotImplementedException($"Unknown MRRC Opc1 0x{opc:X} at 0x{op.Address:X} (0x{op.RawOpCode:X})."), + }, + _ => throw new NotImplementedException($"Unknown MRRC 0x{op.RawOpCode:X} at 0x{op.Address:X}."), + }; Operand result = context.Call(info); SetIntA32(context, op.Rt, context.ConvertI64ToI32(result)); @@ -235,7 +220,8 @@ namespace ARMeilleure.Instructions case 0b0000: // FPSID throw new NotImplementedException("Supervisor Only"); case 0b0001: // FPSCR - EmitGetFpscr(context); return; + EmitGetFpscr(context); + return; case 0b0101: // MVFR2 throw new NotImplementedException("MVFR2"); case 0b0110: // MVFR1 @@ -258,7 +244,8 @@ namespace ARMeilleure.Instructions case 0b0000: // FPSID throw new NotImplementedException("Supervisor Only"); case 0b0001: // FPSCR - EmitSetFpscr(context); return; + EmitSetFpscr(context); + return; case 0b0101: // MVFR2 throw new NotImplementedException("MVFR2"); case 0b0110: // MVFR1 diff --git a/src/ARMeilleure/Instructions/InstName.cs b/src/ARMeilleure/Instructions/InstName.cs index fd71d92e6..32ae38dad 100644 --- a/src/ARMeilleure/Instructions/InstName.cs +++ b/src/ARMeilleure/Instructions/InstName.cs @@ -228,6 +228,7 @@ namespace ARMeilleure.Instructions Fmaxnmp_S, Fmaxnmp_V, Fmaxnmv_V, + Fmaxp_S, Fmaxp_V, Fmaxv_V, Fmin_S, @@ -237,6 +238,7 @@ namespace ARMeilleure.Instructions Fminnmp_S, Fminnmp_V, Fminnmv_V, + Fminp_S, Fminp_V, Fminv_V, Fmla_Se, diff --git a/src/ARMeilleure/Instructions/NativeInterface.cs b/src/ARMeilleure/Instructions/NativeInterface.cs index 2c35387a6..d1b2e353c 100644 --- a/src/ARMeilleure/Instructions/NativeInterface.cs +++ b/src/ARMeilleure/Instructions/NativeInterface.cs @@ -64,12 +64,12 @@ namespace ARMeilleure.Instructions #region "System registers" public static ulong GetCtrEl0() { - return (ulong)GetContext().CtrEl0; + return GetContext().CtrEl0; } public static ulong GetDczidEl0() { - return (ulong)GetContext().DczidEl0; + return GetContext().DczidEl0; } public static ulong GetCntfrqEl0() @@ -192,4 +192,4 @@ namespace ARMeilleure.Instructions return Context.Memory; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Instructions/SoftFallback.cs b/src/ARMeilleure/Instructions/SoftFallback.cs index 06d76a67c..c4fe677bf 100644 --- a/src/ARMeilleure/Instructions/SoftFallback.cs +++ b/src/ARMeilleure/Instructions/SoftFallback.cs @@ -5,7 +5,7 @@ namespace ARMeilleure.Instructions { static class SoftFallback { -#region "ShrImm64" + #region "ShrImm64" public static long SignedShrImm64(long value, long roundConst, int shift) { if (roundConst == 0L) @@ -89,12 +89,15 @@ namespace ARMeilleure.Instructions } } } -#endregion + #endregion -#region "Saturation" + #region "Saturation" public static int SatF32ToS32(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value >= int.MaxValue ? int.MaxValue : value <= int.MinValue ? int.MinValue : (int)value; @@ -102,7 +105,10 @@ namespace ARMeilleure.Instructions public static long SatF32ToS64(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value >= long.MaxValue ? long.MaxValue : value <= long.MinValue ? long.MinValue : (long)value; @@ -110,7 +116,10 @@ namespace ARMeilleure.Instructions public static uint SatF32ToU32(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value >= uint.MaxValue ? uint.MaxValue : value <= uint.MinValue ? uint.MinValue : (uint)value; @@ -118,7 +127,10 @@ namespace ARMeilleure.Instructions public static ulong SatF32ToU64(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value >= ulong.MaxValue ? ulong.MaxValue : value <= ulong.MinValue ? ulong.MinValue : (ulong)value; @@ -126,7 +138,10 @@ namespace ARMeilleure.Instructions public static int SatF64ToS32(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value >= int.MaxValue ? int.MaxValue : value <= int.MinValue ? int.MinValue : (int)value; @@ -134,7 +149,10 @@ namespace ARMeilleure.Instructions public static long SatF64ToS64(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value >= long.MaxValue ? long.MaxValue : value <= long.MinValue ? long.MinValue : (long)value; @@ -142,7 +160,10 @@ namespace ARMeilleure.Instructions public static uint SatF64ToU32(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value >= uint.MaxValue ? uint.MaxValue : value <= uint.MinValue ? uint.MinValue : (uint)value; @@ -150,14 +171,17 @@ namespace ARMeilleure.Instructions public static ulong SatF64ToU64(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value >= ulong.MaxValue ? ulong.MaxValue : value <= ulong.MinValue ? ulong.MinValue : (ulong)value; } -#endregion + #endregion -#region "Count" + #region "Count" public static ulong CountLeadingSigns(ulong value, int size) // size is 8, 16, 32 or 64 (SIMD&FP or Base Inst.). { value ^= value >> 1; @@ -197,9 +221,9 @@ namespace ARMeilleure.Instructions return (ulong)count; } -#endregion + #endregion -#region "Table" + #region "Table" public static V128 Tbl1(V128 vector, int bytes, V128 tb0) { return TblOrTbx(default, vector, bytes, tb0); @@ -270,21 +294,21 @@ namespace ARMeilleure.Instructions return new V128(res); } -#endregion + #endregion -#region "Crc32" - private const uint Crc32RevPoly = 0xedb88320; + #region "Crc32" + private const uint Crc32RevPoly = 0xedb88320; private const uint Crc32cRevPoly = 0x82f63b78; - public static uint Crc32b(uint crc, byte value) => Crc32 (crc, Crc32RevPoly, value); + public static uint Crc32b(uint crc, byte value) => Crc32(crc, Crc32RevPoly, value); public static uint Crc32h(uint crc, ushort value) => Crc32h(crc, Crc32RevPoly, value); - public static uint Crc32w(uint crc, uint value) => Crc32w(crc, Crc32RevPoly, value); - public static uint Crc32x(uint crc, ulong value) => Crc32x(crc, Crc32RevPoly, value); + public static uint Crc32w(uint crc, uint value) => Crc32w(crc, Crc32RevPoly, value); + public static uint Crc32x(uint crc, ulong value) => Crc32x(crc, Crc32RevPoly, value); - public static uint Crc32cb(uint crc, byte value) => Crc32 (crc, Crc32cRevPoly, value); + public static uint Crc32cb(uint crc, byte value) => Crc32(crc, Crc32cRevPoly, value); public static uint Crc32ch(uint crc, ushort value) => Crc32h(crc, Crc32cRevPoly, value); - public static uint Crc32cw(uint crc, uint value) => Crc32w(crc, Crc32cRevPoly, value); - public static uint Crc32cx(uint crc, ulong value) => Crc32x(crc, Crc32cRevPoly, value); + public static uint Crc32cw(uint crc, uint value) => Crc32w(crc, Crc32cRevPoly, value); + public static uint Crc32cx(uint crc, ulong value) => Crc32x(crc, Crc32cRevPoly, value); private static uint Crc32h(uint crc, uint poly, ushort val) { @@ -331,9 +355,9 @@ namespace ARMeilleure.Instructions return crc; } -#endregion + #endregion -#region "Aes" + #region "Aes" public static V128 Decrypt(V128 value, V128 roundKey) { return CryptoHelper.AesInvSubBytes(CryptoHelper.AesInvShiftRows(value ^ roundKey)); @@ -353,9 +377,9 @@ namespace ARMeilleure.Instructions { return CryptoHelper.AesMixColumns(value); } -#endregion + #endregion -#region "Sha1" + #region "Sha1" public static V128 HashChoose(V128 hash_abcd, uint hash_e, V128 wk) { for (int e = 0; e <= 3; e++) @@ -426,7 +450,7 @@ namespace ARMeilleure.Instructions ulong t2 = w4_7.Extract(0); ulong t1 = w0_3.Extract(1); - V128 result = new V128(t1, t2); + V128 result = new(t1, t2); return result ^ (w0_3 ^ w8_11); } @@ -472,9 +496,9 @@ namespace ARMeilleure.Instructions { return (value << count) | (value >> (32 - count)); } -#endregion + #endregion -#region "Sha256" + #region "Sha256" public static V128 HashLower(V128 hash_abcd, V128 hash_efgh, V128 wk) { return Sha256Hash(hash_abcd, hash_efgh, wk, part1: true); @@ -487,7 +511,7 @@ namespace ARMeilleure.Instructions public static V128 Sha256SchedulePart1(V128 w0_3, V128 w4_7) { - V128 result = new V128(); + V128 result = new(); for (int e = 0; e <= 3; e++) { @@ -505,7 +529,7 @@ namespace ARMeilleure.Instructions public static V128 Sha256SchedulePart2(V128 w0_3, V128 w8_11, V128 w12_15) { - V128 result = new V128(); + V128 result = new(); ulong t1 = w12_15.Extract(1); @@ -602,13 +626,13 @@ namespace ARMeilleure.Instructions ? (uint)(value & 0xFFFFFFFFUL) : (uint)(value >> 32); } -#endregion + #endregion public static V128 PolynomialMult64_128(ulong op1, ulong op2) { V128 result = V128.Zero; - V128 op2_128 = new V128(op2, 0); + V128 op2_128 = new(op2, 0); for (int i = 0; i < 64; i++) { diff --git a/src/ARMeilleure/Instructions/SoftFloat.cs b/src/ARMeilleure/Instructions/SoftFloat.cs index 9e3db68d9..a67349e6e 100644 --- a/src/ARMeilleure/Instructions/SoftFloat.cs +++ b/src/ARMeilleure/Instructions/SoftFloat.cs @@ -8,7 +8,7 @@ namespace ARMeilleure.Instructions { static SoftFloat() { - RecipEstimateTable = BuildRecipEstimateTable(); + RecipEstimateTable = BuildRecipEstimateTable(); RecipSqrtEstimateTable = BuildRecipSqrtEstimateTable(); } @@ -63,7 +63,7 @@ namespace ARMeilleure.Instructions while (src * (aux + 1u) * (aux + 1u) < (1u << 28)) { - aux = aux + 1u; + aux++; } uint dst = (aux + 1u) >> 1; @@ -133,8 +133,8 @@ namespace ARMeilleure.Instructions { sign = (~(uint)valueBits & 0x8000u) == 0u; - uint exp16 = ((uint)valueBits & 0x7C00u) >> 10; - uint frac16 = (uint)valueBits & 0x03FFu; + uint exp16 = ((uint)valueBits & 0x7C00u) >> 10; + uint frac16 = (uint)valueBits & 0x03FFu; double real; @@ -175,22 +175,22 @@ namespace ARMeilleure.Instructions public static ushort FPRoundCv(double real, ExecutionContext context) { - const int minimumExp = -14; + const int MinimumExp = -14; - const int e = 5; - const int f = 10; + const int E = 5; + const int F = 10; - bool sign; + bool sign; double mantissa; if (real < 0d) { - sign = true; + sign = true; mantissa = -real; } else { - sign = false; + sign = false; mantissa = real; } @@ -208,15 +208,15 @@ namespace ARMeilleure.Instructions exponent++; } - uint biasedExp = (uint)Math.Max(exponent - minimumExp + 1, 0); + uint biasedExp = (uint)Math.Max(exponent - MinimumExp + 1, 0); if (biasedExp == 0u) { - mantissa /= Math.Pow(2d, minimumExp - exponent); + mantissa /= Math.Pow(2d, MinimumExp - exponent); } - uint intMant = (uint)Math.Floor(mantissa * Math.Pow(2d, f)); - double error = mantissa * Math.Pow(2d, f) - (double)intMant; + uint intMant = (uint)Math.Floor(mantissa * Math.Pow(2d, F)); + double error = mantissa * Math.Pow(2d, F) - (double)intMant; if (biasedExp == 0u && (error != 0d || (context.Fpcr & FPCR.Ufe) != 0)) { @@ -228,38 +228,40 @@ namespace ARMeilleure.Instructions switch (context.Fpcr.GetRoundingMode()) { - default: case FPRoundingMode.ToNearest: - roundUp = (error > 0.5d || (error == 0.5d && (intMant & 1u) == 1u)); + roundUp = (error > 0.5d || (error == 0.5d && (intMant & 1u) == 1u)); overflowToInf = true; break; case FPRoundingMode.TowardsPlusInfinity: - roundUp = (error != 0d && !sign); + roundUp = (error != 0d && !sign); overflowToInf = !sign; break; case FPRoundingMode.TowardsMinusInfinity: - roundUp = (error != 0d && sign); + roundUp = (error != 0d && sign); overflowToInf = sign; break; case FPRoundingMode.TowardsZero: - roundUp = false; + roundUp = false; overflowToInf = false; break; + + default: + throw new ArgumentException($"Invalid rounding mode \"{context.Fpcr.GetRoundingMode()}\"."); } if (roundUp) { intMant++; - if (intMant == 1u << f) + if (intMant == 1u << F) { biasedExp = 1u; } - if (intMant == 1u << (f + 1)) + if (intMant == 1u << (F + 1)) { biasedExp++; intMant >>= 1; @@ -270,7 +272,7 @@ namespace ARMeilleure.Instructions if ((context.Fpcr & FPCR.Ahp) == 0) { - if (biasedExp >= (1u << e) - 1u) + if (biasedExp >= (1u << E) - 1u) { resultBits = overflowToInf ? FPInfinity(sign) : FPMaxNormal(sign); @@ -285,7 +287,7 @@ namespace ARMeilleure.Instructions } else { - if (biasedExp >= 1u << e) + if (biasedExp >= 1u << E) { resultBits = (ushort)((sign ? 1u : 0u) << 15 | 0x7FFFu); @@ -352,22 +354,22 @@ namespace ARMeilleure.Instructions private static float FPRoundCv(double real, ExecutionContext context) { - const int minimumExp = -126; + const int MinimumExp = -126; - const int e = 8; - const int f = 23; + const int E = 8; + const int F = 23; - bool sign; + bool sign; double mantissa; if (real < 0d) { - sign = true; + sign = true; mantissa = -real; } else { - sign = false; + sign = false; mantissa = real; } @@ -385,22 +387,22 @@ namespace ARMeilleure.Instructions exponent++; } - if ((context.Fpcr & FPCR.Fz) != 0 && exponent < minimumExp) + if ((context.Fpcr & FPCR.Fz) != 0 && exponent < MinimumExp) { context.Fpsr |= FPSR.Ufc; return SoftFloat32.FPZero(sign); } - uint biasedExp = (uint)Math.Max(exponent - minimumExp + 1, 0); + uint biasedExp = (uint)Math.Max(exponent - MinimumExp + 1, 0); if (biasedExp == 0u) { - mantissa /= Math.Pow(2d, minimumExp - exponent); + mantissa /= Math.Pow(2d, MinimumExp - exponent); } - uint intMant = (uint)Math.Floor(mantissa * Math.Pow(2d, f)); - double error = mantissa * Math.Pow(2d, f) - (double)intMant; + uint intMant = (uint)Math.Floor(mantissa * Math.Pow(2d, F)); + double error = mantissa * Math.Pow(2d, F) - (double)intMant; if (biasedExp == 0u && (error != 0d || (context.Fpcr & FPCR.Ufe) != 0)) { @@ -412,38 +414,40 @@ namespace ARMeilleure.Instructions switch (context.Fpcr.GetRoundingMode()) { - default: case FPRoundingMode.ToNearest: - roundUp = (error > 0.5d || (error == 0.5d && (intMant & 1u) == 1u)); + roundUp = (error > 0.5d || (error == 0.5d && (intMant & 1u) == 1u)); overflowToInf = true; break; case FPRoundingMode.TowardsPlusInfinity: - roundUp = (error != 0d && !sign); + roundUp = (error != 0d && !sign); overflowToInf = !sign; break; case FPRoundingMode.TowardsMinusInfinity: - roundUp = (error != 0d && sign); + roundUp = (error != 0d && sign); overflowToInf = sign; break; case FPRoundingMode.TowardsZero: - roundUp = false; + roundUp = false; overflowToInf = false; break; + + default: + throw new ArgumentException($"Invalid rounding mode \"{context.Fpcr.GetRoundingMode()}\"."); } if (roundUp) { intMant++; - if (intMant == 1u << f) + if (intMant == 1u << F) { biasedExp = 1u; } - if (intMant == 1u << (f + 1)) + if (intMant == 1u << (F + 1)) { biasedExp++; intMant >>= 1; @@ -452,7 +456,7 @@ namespace ARMeilleure.Instructions float result; - if (biasedExp >= (1u << e) - 1u) + if (biasedExp >= (1u << E) - 1u) { result = overflowToInf ? SoftFloat32.FPInfinity(sign) : SoftFloat32.FPMaxNormal(sign); @@ -525,22 +529,22 @@ namespace ARMeilleure.Instructions private static double FPRoundCv(double real, ExecutionContext context) { - const int minimumExp = -1022; + const int MinimumExp = -1022; - const int e = 11; - const int f = 52; + const int E = 11; + const int F = 52; - bool sign; + bool sign; double mantissa; if (real < 0d) { - sign = true; + sign = true; mantissa = -real; } else { - sign = false; + sign = false; mantissa = real; } @@ -558,22 +562,22 @@ namespace ARMeilleure.Instructions exponent++; } - if ((context.Fpcr & FPCR.Fz) != 0 && exponent < minimumExp) + if ((context.Fpcr & FPCR.Fz) != 0 && exponent < MinimumExp) { context.Fpsr |= FPSR.Ufc; return SoftFloat64.FPZero(sign); } - uint biasedExp = (uint)Math.Max(exponent - minimumExp + 1, 0); + uint biasedExp = (uint)Math.Max(exponent - MinimumExp + 1, 0); if (biasedExp == 0u) { - mantissa /= Math.Pow(2d, minimumExp - exponent); + mantissa /= Math.Pow(2d, MinimumExp - exponent); } - ulong intMant = (ulong)Math.Floor(mantissa * Math.Pow(2d, f)); - double error = mantissa * Math.Pow(2d, f) - (double)intMant; + ulong intMant = (ulong)Math.Floor(mantissa * Math.Pow(2d, F)); + double error = mantissa * Math.Pow(2d, F) - (double)intMant; if (biasedExp == 0u && (error != 0d || (context.Fpcr & FPCR.Ufe) != 0)) { @@ -585,38 +589,40 @@ namespace ARMeilleure.Instructions switch (context.Fpcr.GetRoundingMode()) { - default: case FPRoundingMode.ToNearest: - roundUp = (error > 0.5d || (error == 0.5d && (intMant & 1u) == 1u)); + roundUp = (error > 0.5d || (error == 0.5d && (intMant & 1u) == 1u)); overflowToInf = true; break; case FPRoundingMode.TowardsPlusInfinity: - roundUp = (error != 0d && !sign); + roundUp = (error != 0d && !sign); overflowToInf = !sign; break; case FPRoundingMode.TowardsMinusInfinity: - roundUp = (error != 0d && sign); + roundUp = (error != 0d && sign); overflowToInf = sign; break; case FPRoundingMode.TowardsZero: - roundUp = false; + roundUp = false; overflowToInf = false; break; + + default: + throw new ArgumentException($"Invalid rounding mode \"{context.Fpcr.GetRoundingMode()}\"."); } if (roundUp) { intMant++; - if (intMant == 1ul << f) + if (intMant == 1ul << F) { biasedExp = 1u; } - if (intMant == 1ul << (f + 1)) + if (intMant == 1ul << (F + 1)) { biasedExp++; intMant >>= 1; @@ -625,7 +631,7 @@ namespace ARMeilleure.Instructions double result; - if (biasedExp >= (1u << e) - 1u) + if (biasedExp >= (1u << E) - 1u) { result = overflowToInf ? SoftFloat64.FPInfinity(sign) : SoftFloat64.FPMaxNormal(sign); @@ -722,8 +728,8 @@ namespace ARMeilleure.Instructions sign = (~valueBits & 0x80000000u) == 0u; - uint exp32 = (valueBits & 0x7F800000u) >> 23; - uint frac32 = valueBits & 0x007FFFFFu; + uint exp32 = (valueBits & 0x7F800000u) >> 23; + uint frac32 = valueBits & 0x007FFFFFu; double real; @@ -792,8 +798,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if (inf1 && inf2 && sign1 == !sign2) { @@ -834,8 +842,8 @@ namespace ARMeilleure.Instructions ExecutionContext context = NativeInterface.GetContext(); FPCR fpcr = context.Fpcr; - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out _, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out _, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out _, out _, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out _, out _, context, fpcr); int result; @@ -989,8 +997,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && inf2) || (zero1 && zero2)) { @@ -1226,8 +1236,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -1270,11 +1282,13 @@ namespace ARMeilleure.Instructions FPCR fpcr = standardFpscr ? context.StandardFpcrValue : context.Fpcr; valueA = valueA.FPUnpack(out FPType typeA, out bool signA, out uint addend, context, fpcr); - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out uint op1, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out uint op2, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out bool sign1, out uint op1, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out bool sign2, out uint op2, context, fpcr); - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; float result = FPProcessNaNs3(typeA, type1, type2, addend, op1, op2, out bool done, context, fpcr); @@ -1287,10 +1301,11 @@ namespace ARMeilleure.Instructions if (!done) { - bool infA = typeA == FPType.Infinity; bool zeroA = typeA == FPType.Zero; + bool infA = typeA == FPType.Infinity; + bool zeroA = typeA == FPType.Zero; - bool signP = sign1 ^ sign2; - bool infP = inf1 || inf2; + bool signP = sign1 ^ sign2; + bool infP = inf1 || inf2; bool zeroP = zero1 || zero2; if ((inf1 && zero2) || (zero1 && inf2) || (infA && infP && signA != signP)) @@ -1353,8 +1368,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -1429,21 +1446,18 @@ namespace ARMeilleure.Instructions } else if (MathF.Abs(value) < MathF.Pow(2f, -128)) { - bool overflowToInf; - - switch (fpcr.GetRoundingMode()) + var overflowToInf = fpcr.GetRoundingMode() switch { - default: - case FPRoundingMode.ToNearest: overflowToInf = true; break; - case FPRoundingMode.TowardsPlusInfinity: overflowToInf = !sign; break; - case FPRoundingMode.TowardsMinusInfinity: overflowToInf = sign; break; - case FPRoundingMode.TowardsZero: overflowToInf = false; break; - } - + FPRoundingMode.ToNearest => true, + FPRoundingMode.TowardsPlusInfinity => !sign, + FPRoundingMode.TowardsMinusInfinity => sign, + FPRoundingMode.TowardsZero => false, + _ => throw new ArgumentException($"Invalid rounding mode \"{fpcr.GetRoundingMode()}\"."), + }; result = overflowToInf ? FPInfinity(sign) : FPMaxNormal(sign); SoftFloat.FPProcessException(FPException.Overflow, context, fpcr); - SoftFloat.FPProcessException(FPException.Inexact, context, fpcr); + SoftFloat.FPProcessException(FPException.Inexact, context, fpcr); } else if ((fpcr & FPCR.Fz) != 0 && (MathF.Abs(value) >= MathF.Pow(2f, 126))) { @@ -1499,15 +1513,17 @@ namespace ARMeilleure.Instructions ExecutionContext context = NativeInterface.GetContext(); FPCR fpcr = context.StandardFpcrValue; - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out uint op1, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out uint op2, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out _, out uint op1, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out _, out uint op2, context, fpcr); float result = FPProcessNaNs(type1, type2, op1, op2, out bool done, context, fpcr); if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; float product; @@ -1540,8 +1556,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -1672,8 +1690,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if (inf1 && inf2 && sign1 == sign2) { @@ -1714,15 +1734,17 @@ namespace ARMeilleure.Instructions ExecutionContext context = NativeInterface.GetContext(); FPCR fpcr = context.StandardFpcrValue; - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out uint op1, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out uint op2, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out _, out uint op1, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out _, out uint op2, context, fpcr); float result = FPProcessNaNs(type1, type2, op1, op2, out bool done, context, fpcr); if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; float product; @@ -1755,8 +1777,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -1841,8 +1865,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if (inf1 && inf2 && sign1 == sign2) { @@ -1939,7 +1965,7 @@ namespace ARMeilleure.Instructions { if ((valueBits & 0x007FFFFFu) == 0u || (fpcr & FPCR.Fz) != 0) { - type = FPType.Zero; + type = FPType.Zero; value = FPZero(sign); if ((valueBits & 0x007FFFFFu) != 0u) @@ -1960,7 +1986,7 @@ namespace ARMeilleure.Instructions } else { - type = (~valueBits & 0x00400000u) == 0u ? FPType.QNaN : FPType.SNaN; + type = (~valueBits & 0x00400000u) == 0u ? FPType.QNaN : FPType.SNaN; value = FPZero(sign); } } @@ -2134,8 +2160,8 @@ namespace ARMeilleure.Instructions sign = (~valueBits & 0x8000000000000000ul) == 0u; - ulong exp64 = (valueBits & 0x7FF0000000000000ul) >> 52; - ulong frac64 = valueBits & 0x000FFFFFFFFFFFFFul; + ulong exp64 = (valueBits & 0x7FF0000000000000ul) >> 52; + ulong frac64 = valueBits & 0x000FFFFFFFFFFFFFul; double real; @@ -2204,8 +2230,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if (inf1 && inf2 && sign1 == !sign2) { @@ -2246,8 +2274,8 @@ namespace ARMeilleure.Instructions ExecutionContext context = NativeInterface.GetContext(); FPCR fpcr = context.Fpcr; - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out _, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out _, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out _, out _, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out _, out _, context, fpcr); int result; @@ -2401,8 +2429,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && inf2) || (zero1 && zero2)) { @@ -2638,8 +2668,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -2682,11 +2714,13 @@ namespace ARMeilleure.Instructions FPCR fpcr = standardFpscr ? context.StandardFpcrValue : context.Fpcr; valueA = valueA.FPUnpack(out FPType typeA, out bool signA, out ulong addend, context, fpcr); - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out ulong op1, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out ulong op2, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out bool sign1, out ulong op1, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out bool sign2, out ulong op2, context, fpcr); - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; double result = FPProcessNaNs3(typeA, type1, type2, addend, op1, op2, out bool done, context, fpcr); @@ -2699,10 +2733,11 @@ namespace ARMeilleure.Instructions if (!done) { - bool infA = typeA == FPType.Infinity; bool zeroA = typeA == FPType.Zero; + bool infA = typeA == FPType.Infinity; + bool zeroA = typeA == FPType.Zero; - bool signP = sign1 ^ sign2; - bool infP = inf1 || inf2; + bool signP = sign1 ^ sign2; + bool infP = inf1 || inf2; bool zeroP = zero1 || zero2; if ((inf1 && zero2) || (zero1 && inf2) || (infA && infP && signA != signP)) @@ -2765,8 +2800,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -2841,21 +2878,18 @@ namespace ARMeilleure.Instructions } else if (Math.Abs(value) < Math.Pow(2d, -1024)) { - bool overflowToInf; - - switch (fpcr.GetRoundingMode()) + var overflowToInf = fpcr.GetRoundingMode() switch { - default: - case FPRoundingMode.ToNearest: overflowToInf = true; break; - case FPRoundingMode.TowardsPlusInfinity: overflowToInf = !sign; break; - case FPRoundingMode.TowardsMinusInfinity: overflowToInf = sign; break; - case FPRoundingMode.TowardsZero: overflowToInf = false; break; - } - + FPRoundingMode.ToNearest => true, + FPRoundingMode.TowardsPlusInfinity => !sign, + FPRoundingMode.TowardsMinusInfinity => sign, + FPRoundingMode.TowardsZero => false, + _ => throw new ArgumentException($"Invalid rounding mode \"{fpcr.GetRoundingMode()}\"."), + }; result = overflowToInf ? FPInfinity(sign) : FPMaxNormal(sign); SoftFloat.FPProcessException(FPException.Overflow, context, fpcr); - SoftFloat.FPProcessException(FPException.Inexact, context, fpcr); + SoftFloat.FPProcessException(FPException.Inexact, context, fpcr); } else if ((fpcr & FPCR.Fz) != 0 && (Math.Abs(value) >= Math.Pow(2d, 1022))) { @@ -2911,15 +2945,17 @@ namespace ARMeilleure.Instructions ExecutionContext context = NativeInterface.GetContext(); FPCR fpcr = context.StandardFpcrValue; - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out ulong op1, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out ulong op2, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out _, out ulong op1, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out _, out ulong op2, context, fpcr); double result = FPProcessNaNs(type1, type2, op1, op2, out bool done, context, fpcr); if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; double product; @@ -2952,8 +2988,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -3084,8 +3122,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if (inf1 && inf2 && sign1 == sign2) { @@ -3126,15 +3166,17 @@ namespace ARMeilleure.Instructions ExecutionContext context = NativeInterface.GetContext(); FPCR fpcr = context.StandardFpcrValue; - value1 = value1.FPUnpack(out FPType type1, out bool sign1, out ulong op1, context, fpcr); - value2 = value2.FPUnpack(out FPType type2, out bool sign2, out ulong op2, context, fpcr); + value1 = value1.FPUnpack(out FPType type1, out _, out ulong op1, context, fpcr); + value2 = value2.FPUnpack(out FPType type2, out _, out ulong op2, context, fpcr); double result = FPProcessNaNs(type1, type2, op1, op2, out bool done, context, fpcr); if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; double product; @@ -3167,8 +3209,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if ((inf1 && zero2) || (zero1 && inf2)) { @@ -3253,8 +3297,10 @@ namespace ARMeilleure.Instructions if (!done) { - bool inf1 = type1 == FPType.Infinity; bool zero1 = type1 == FPType.Zero; - bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; + bool inf1 = type1 == FPType.Infinity; + bool zero1 = type1 == FPType.Zero; + bool inf2 = type2 == FPType.Infinity; + bool zero2 = type2 == FPType.Zero; if (inf1 && inf2 && sign1 == sign2) { @@ -3351,7 +3397,7 @@ namespace ARMeilleure.Instructions { if ((valueBits & 0x000FFFFFFFFFFFFFul) == 0ul || (fpcr & FPCR.Fz) != 0) { - type = FPType.Zero; + type = FPType.Zero; value = FPZero(sign); if ((valueBits & 0x000FFFFFFFFFFFFFul) != 0ul) @@ -3372,7 +3418,7 @@ namespace ARMeilleure.Instructions } else { - type = (~valueBits & 0x0008000000000000ul) == 0ul ? FPType.QNaN : FPType.SNaN; + type = (~valueBits & 0x0008000000000000ul) == 0ul ? FPType.QNaN : FPType.SNaN; value = FPZero(sign); } } diff --git a/src/ARMeilleure/IntermediateRepresentation/BasicBlock.cs b/src/ARMeilleure/IntermediateRepresentation/BasicBlock.cs index 07bd8b672..810461d7c 100644 --- a/src/ARMeilleure/IntermediateRepresentation/BasicBlock.cs +++ b/src/ARMeilleure/IntermediateRepresentation/BasicBlock.cs @@ -10,7 +10,7 @@ namespace ARMeilleure.IntermediateRepresentation private int _succCount; private BasicBlock _succ0; - private BasicBlock _succ1; + private readonly BasicBlock _succ1; private HashSet _domFrontiers; public int Index { get; set; } @@ -27,10 +27,7 @@ namespace ARMeilleure.IntermediateRepresentation { get { - if (_domFrontiers == null) - { - _domFrontiers = new HashSet(); - } + _domFrontiers ??= new HashSet(); return _domFrontiers; } @@ -108,7 +105,7 @@ namespace ARMeilleure.IntermediateRepresentation oldBlock.Predecessors.Remove(this); block.Predecessors.Add(this); - + oldBlock = block; } @@ -156,4 +153,4 @@ namespace ARMeilleure.IntermediateRepresentation return base.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/BasicBlockFrequency.cs b/src/ARMeilleure/IntermediateRepresentation/BasicBlockFrequency.cs index 96cfee35a..74aaea6b1 100644 --- a/src/ARMeilleure/IntermediateRepresentation/BasicBlockFrequency.cs +++ b/src/ARMeilleure/IntermediateRepresentation/BasicBlockFrequency.cs @@ -3,6 +3,6 @@ enum BasicBlockFrequency { Default, - Cold + Cold, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/Comparison.cs b/src/ARMeilleure/IntermediateRepresentation/Comparison.cs index 628ce1051..e3a68b49d 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Comparison.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Comparison.cs @@ -2,16 +2,16 @@ { enum Comparison { - Equal = 0, - NotEqual = 1, - Greater = 2, - LessOrEqual = 3, - GreaterUI = 4, - LessOrEqualUI = 5, - GreaterOrEqual = 6, - Less = 7, - GreaterOrEqualUI = 8, - LessUI = 9 + Equal = 0, + NotEqual = 1, + Greater = 2, + LessOrEqual = 3, + GreaterUI = 4, + LessOrEqualUI = 5, + GreaterOrEqual = 6, + Less = 7, + GreaterOrEqualUI = 8, + LessUI = 9, } static class ComparisonExtensions diff --git a/src/ARMeilleure/IntermediateRepresentation/Instruction.cs b/src/ARMeilleure/IntermediateRepresentation/Instruction.cs index b55fe1dac..9bae8d1fb 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Instruction.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Instruction.cs @@ -67,6 +67,6 @@ namespace ARMeilleure.IntermediateRepresentation Phi, Spill, SpillArg, - StoreToContext + StoreToContext, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/Intrinsic.cs b/src/ARMeilleure/IntermediateRepresentation/Intrinsic.cs index f5a776fa2..b9cab6674 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Intrinsic.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Intrinsic.cs @@ -1,5 +1,10 @@ +using System; +using System.Diagnostics.CodeAnalysis; + namespace ARMeilleure.IntermediateRepresentation { + [Flags] + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] enum Intrinsic : ushort { // X86 (SSE and AVX) @@ -631,6 +636,6 @@ namespace ARMeilleure.IntermediateRepresentation Arm64VByte = 0 << Arm64VSizeShift, Arm64VHWord = 1 << Arm64VSizeShift, Arm64VWord = 2 << Arm64VSizeShift, - Arm64VDWord = 3 << Arm64VSizeShift + Arm64VDWord = 3 << Arm64VSizeShift, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/MemoryOperand.cs b/src/ARMeilleure/IntermediateRepresentation/MemoryOperand.cs index 07d2633b4..9b3df8ca4 100644 --- a/src/ARMeilleure/IntermediateRepresentation/MemoryOperand.cs +++ b/src/ARMeilleure/IntermediateRepresentation/MemoryOperand.cs @@ -4,11 +4,11 @@ using System.Runtime.CompilerServices; namespace ARMeilleure.IntermediateRepresentation { - unsafe struct MemoryOperand + readonly unsafe struct MemoryOperand { private struct Data { -#pragma warning disable CS0649 +#pragma warning disable CS0649 // Field is never assigned to public byte Kind; public byte Type; #pragma warning restore CS0649 @@ -18,7 +18,7 @@ namespace ARMeilleure.IntermediateRepresentation public int Displacement; } - private Data* _data; + private readonly Data* _data; public MemoryOperand(Operand operand) { @@ -30,13 +30,13 @@ namespace ARMeilleure.IntermediateRepresentation public Operand BaseAddress { get => _data->BaseAddress; - set => _data->BaseAddress = value; + set => _data->BaseAddress = value; } public Operand Index { get => _data->Index; - set => _data->Index = value; + set => _data->Index = value; } public Multiplier Scale @@ -51,4 +51,4 @@ namespace ARMeilleure.IntermediateRepresentation set => _data->Displacement = value; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/Multiplier.cs b/src/ARMeilleure/IntermediateRepresentation/Multiplier.cs index d6bc7d994..6bcdda014 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Multiplier.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Multiplier.cs @@ -6,6 +6,6 @@ namespace ARMeilleure.IntermediateRepresentation x2 = 1, x4 = 2, x8 = 3, - x16 = 4 + x16 = 4, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/Operand.cs b/src/ARMeilleure/IntermediateRepresentation/Operand.cs index 9e8de3ba4..89aefacb1 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Operand.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Operand.cs @@ -27,25 +27,25 @@ namespace ARMeilleure.IntermediateRepresentation private Data* _data; - public OperandKind Kind + public readonly OperandKind Kind { get => (OperandKind)_data->Kind; private set => _data->Kind = (byte)value; } - public OperandType Type + public readonly OperandType Type { get => (OperandType)_data->Type; private set => _data->Type = (byte)value; } - public ulong Value + public readonly ulong Value { get => _data->Value; private set => _data->Value = value; } - public Symbol Symbol + public readonly Symbol Symbol { get { @@ -69,7 +69,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public ReadOnlySpan Assignments + public readonly ReadOnlySpan Assignments { get { @@ -79,7 +79,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public ReadOnlySpan Uses + public readonly ReadOnlySpan Uses { get { @@ -89,13 +89,13 @@ namespace ARMeilleure.IntermediateRepresentation } } - public int UsesCount => (int)_data->UsesCount; - public int AssignmentsCount => _data->AssignmentsCount; + public readonly int UsesCount => (int)_data->UsesCount; + public readonly int AssignmentsCount => _data->AssignmentsCount; - public bool Relocatable => Symbol.Type != SymbolType.None; + public readonly bool Relocatable => Symbol.Type != SymbolType.None; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Register GetRegister() + public readonly Register GetRegister() { Debug.Assert(Kind == OperandKind.Register); @@ -103,52 +103,52 @@ namespace ARMeilleure.IntermediateRepresentation } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public MemoryOperand GetMemory() + public readonly MemoryOperand GetMemory() { Debug.Assert(Kind == OperandKind.Memory); return new MemoryOperand(this); } - public int GetLocalNumber() + public readonly int GetLocalNumber() { Debug.Assert(Kind == OperandKind.LocalVariable); return (int)Value; } - public byte AsByte() + public readonly byte AsByte() { return (byte)Value; } - public short AsInt16() + public readonly short AsInt16() { return (short)Value; } - public int AsInt32() + public readonly int AsInt32() { return (int)Value; } - public long AsInt64() + public readonly long AsInt64() { return (long)Value; } - public float AsFloat() + public readonly float AsFloat() { return BitConverter.Int32BitsToSingle((int)Value); } - public double AsDouble() + public readonly double AsDouble() { return BitConverter.Int64BitsToDouble((long)Value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ref ulong GetValueUnsafe() + internal readonly ref ulong GetValueUnsafe() { return ref _data->Value; } @@ -163,7 +163,7 @@ namespace ARMeilleure.IntermediateRepresentation Value = (ulong)number; } - public void AddAssignment(Operation operation) + public readonly void AddAssignment(Operation operation) { if (Kind == OperandKind.LocalVariable) { @@ -187,7 +187,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void RemoveAssignment(Operation operation) + public readonly void RemoveAssignment(Operation operation) { if (Kind == OperandKind.LocalVariable) { @@ -211,7 +211,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void AddUse(Operation operation) + public readonly void AddUse(Operation operation) { if (Kind == OperandKind.LocalVariable) { @@ -235,7 +235,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void RemoveUse(Operation operation) + public readonly void RemoveUse(Operation operation) { if (Kind == OperandKind.LocalVariable) { @@ -259,7 +259,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public Span GetUses(ref Span buffer) + public readonly Span GetUses(ref Span buffer) { ReadOnlySpan uses = Uses; @@ -270,7 +270,7 @@ namespace ARMeilleure.IntermediateRepresentation uses.CopyTo(buffer); - return buffer.Slice(0, uses.Length); + return buffer[..uses.Length]; } private static void New(ref T* data, ref ushort count, ref ushort capacity, ushort initialCapacity) where T : unmanaged @@ -360,7 +360,7 @@ namespace ARMeilleure.IntermediateRepresentation { if (i + 1 < count) { - span.Slice(i + 1).CopyTo(span.Slice(i)); + span[(i + 1)..].CopyTo(span[i..]); } count--; @@ -380,7 +380,7 @@ namespace ARMeilleure.IntermediateRepresentation { if (i + 1 < count) { - span.Slice(i + 1).CopyTo(span.Slice(i)); + span[(i + 1)..].CopyTo(span[i..]); } count--; @@ -390,17 +390,17 @@ namespace ARMeilleure.IntermediateRepresentation } } - public override int GetHashCode() + public readonly override int GetHashCode() { return ((ulong)_data).GetHashCode(); } - public bool Equals(Operand operand) + public readonly bool Equals(Operand operand) { return operand._data == _data; } - public override bool Equals(object obj) + public readonly override bool Equals(object obj) { return obj is Operand operand && Equals(operand); } @@ -453,8 +453,10 @@ namespace ARMeilleure.IntermediateRepresentation // Look in the next InternTableProbeLength slots for a match. for (uint i = 0; i < InternTableProbeLength; i++) { - Operand interned = new(); - interned._data = &InternTable[(hash + i) % InternTableSize]; + Operand interned = new() + { + _data = &InternTable[(hash + i) % InternTableSize], + }; // If slot matches the allocation request then return that slot. if (interned.Kind == kind && interned.Type == type && interned.Value == value && interned.Symbol == symbol) @@ -479,11 +481,13 @@ namespace ARMeilleure.IntermediateRepresentation *data = default; - Operand result = new(); - result._data = data; - result.Value = value; - result.Kind = kind; - result.Type = type; + Operand result = new() + { + _data = data, + Value = value, + Kind = kind, + Type = type, + }; if (kind != OperandKind.Memory) { @@ -591,4 +595,4 @@ namespace ARMeilleure.IntermediateRepresentation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/OperandKind.cs b/src/ARMeilleure/IntermediateRepresentation/OperandKind.cs index adb835614..2b973f006 100644 --- a/src/ARMeilleure/IntermediateRepresentation/OperandKind.cs +++ b/src/ARMeilleure/IntermediateRepresentation/OperandKind.cs @@ -8,6 +8,6 @@ namespace ARMeilleure.IntermediateRepresentation LocalVariable, Memory, Register, - Undefined + Undefined, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/OperandType.cs b/src/ARMeilleure/IntermediateRepresentation/OperandType.cs index 81b22cf56..67ebdcde4 100644 --- a/src/ARMeilleure/IntermediateRepresentation/OperandType.cs +++ b/src/ARMeilleure/IntermediateRepresentation/OperandType.cs @@ -9,7 +9,7 @@ namespace ARMeilleure.IntermediateRepresentation I64, FP32, FP64, - V128 + V128, } static class OperandTypeExtensions @@ -22,44 +22,41 @@ namespace ARMeilleure.IntermediateRepresentation public static RegisterType ToRegisterType(this OperandType type) { - switch (type) + return type switch { - case OperandType.FP32: return RegisterType.Vector; - case OperandType.FP64: return RegisterType.Vector; - case OperandType.I32: return RegisterType.Integer; - case OperandType.I64: return RegisterType.Integer; - case OperandType.V128: return RegisterType.Vector; - } - - throw new InvalidOperationException($"Invalid operand type \"{type}\"."); + OperandType.FP32 => RegisterType.Vector, + OperandType.FP64 => RegisterType.Vector, + OperandType.I32 => RegisterType.Integer, + OperandType.I64 => RegisterType.Integer, + OperandType.V128 => RegisterType.Vector, + _ => throw new InvalidOperationException($"Invalid operand type \"{type}\"."), + }; } public static int GetSizeInBytes(this OperandType type) { - switch (type) + return type switch { - case OperandType.FP32: return 4; - case OperandType.FP64: return 8; - case OperandType.I32: return 4; - case OperandType.I64: return 8; - case OperandType.V128: return 16; - } - - throw new InvalidOperationException($"Invalid operand type \"{type}\"."); + OperandType.FP32 => 4, + OperandType.FP64 => 8, + OperandType.I32 => 4, + OperandType.I64 => 8, + OperandType.V128 => 16, + _ => throw new InvalidOperationException($"Invalid operand type \"{type}\"."), + }; } public static int GetSizeInBytesLog2(this OperandType type) { - switch (type) + return type switch { - case OperandType.FP32: return 2; - case OperandType.FP64: return 3; - case OperandType.I32: return 2; - case OperandType.I64: return 3; - case OperandType.V128: return 4; - } - - throw new InvalidOperationException($"Invalid operand type \"{type}\"."); + OperandType.FP32 => 2, + OperandType.FP64 => 3, + OperandType.I32 => 2, + OperandType.I64 => 3, + OperandType.V128 => 4, + _ => throw new InvalidOperationException($"Invalid operand type \"{type}\"."), + }; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/Operation.cs b/src/ARMeilleure/IntermediateRepresentation/Operation.cs index c71e143c3..bc3a71b31 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Operation.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Operation.cs @@ -20,60 +20,60 @@ namespace ARMeilleure.IntermediateRepresentation private Data* _data; - public Instruction Instruction + public readonly Instruction Instruction { get => (Instruction)_data->Instruction; private set => _data->Instruction = (ushort)value; } - public Intrinsic Intrinsic + public readonly Intrinsic Intrinsic { get => (Intrinsic)_data->Intrinsic; private set => _data->Intrinsic = (ushort)value; } - public Operation ListPrevious + public readonly Operation ListPrevious { get => _data->ListPrevious; set => _data->ListPrevious = value; } - public Operation ListNext + public readonly Operation ListNext { get => _data->ListNext; set => _data->ListNext = value; } - public Operand Destination + public readonly Operand Destination { get => _data->DestinationsCount != 0 ? GetDestination(0) : default; set => SetDestination(value); } - public int DestinationsCount => _data->DestinationsCount; - public int SourcesCount => _data->SourcesCount; + public readonly int DestinationsCount => _data->DestinationsCount; + public readonly int SourcesCount => _data->SourcesCount; - internal Span DestinationsUnsafe => new(_data->Destinations, _data->DestinationsCount); - internal Span SourcesUnsafe => new(_data->Sources, _data->SourcesCount); + internal readonly Span DestinationsUnsafe => new(_data->Destinations, _data->DestinationsCount); + internal readonly Span SourcesUnsafe => new(_data->Sources, _data->SourcesCount); - public PhiOperation AsPhi() + public readonly PhiOperation AsPhi() { Debug.Assert(Instruction == Instruction.Phi); return new PhiOperation(this); } - public Operand GetDestination(int index) + public readonly Operand GetDestination(int index) { return DestinationsUnsafe[index]; } - public Operand GetSource(int index) + public readonly Operand GetSource(int index) { return SourcesUnsafe[index]; } - public void SetDestination(int index, Operand dest) + public readonly void SetDestination(int index, Operand dest) { ref Operand curDest = ref DestinationsUnsafe[index]; @@ -83,7 +83,7 @@ namespace ARMeilleure.IntermediateRepresentation curDest = dest; } - public void SetSource(int index, Operand src) + public readonly void SetSource(int index, Operand src) { ref Operand curSrc = ref SourcesUnsafe[index]; @@ -93,7 +93,7 @@ namespace ARMeilleure.IntermediateRepresentation curSrc = src; } - private void RemoveOldDestinations() + private readonly void RemoveOldDestinations() { for (int i = 0; i < _data->DestinationsCount; i++) { @@ -101,7 +101,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void SetDestination(Operand dest) + public readonly void SetDestination(Operand dest) { RemoveOldDestinations(); @@ -119,7 +119,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void SetDestinations(Operand[] dests) + public readonly void SetDestinations(Operand[] dests) { RemoveOldDestinations(); @@ -135,7 +135,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - private void RemoveOldSources() + private readonly void RemoveOldSources() { for (int index = 0; index < _data->SourcesCount; index++) { @@ -143,7 +143,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void SetSource(Operand src) + public readonly void SetSource(Operand src) { RemoveOldSources(); @@ -161,7 +161,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - public void SetSources(Operand[] srcs) + public readonly void SetSources(Operand[] srcs) { RemoveOldSources(); @@ -184,7 +184,7 @@ namespace ARMeilleure.IntermediateRepresentation SetSource(source); } - private void AddAssignment(Operand op) + private readonly void AddAssignment(Operand op) { if (op != default) { @@ -192,7 +192,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - private void RemoveAssignment(Operand op) + private readonly void RemoveAssignment(Operand op) { if (op != default) { @@ -200,7 +200,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - private void AddUse(Operand op) + private readonly void AddUse(Operand op) { if (op != default) { @@ -208,7 +208,7 @@ namespace ARMeilleure.IntermediateRepresentation } } - private void RemoveUse(Operand op) + private readonly void RemoveUse(Operand op) { if (op != default) { @@ -216,17 +216,17 @@ namespace ARMeilleure.IntermediateRepresentation } } - public bool Equals(Operation operation) + public readonly bool Equals(Operation operation) { return operation._data == _data; } - public override bool Equals(object obj) + public readonly override bool Equals(object obj) { return obj is Operation operation && Equals(operation); } - public override int GetHashCode() + public readonly override int GetHashCode() { return HashCode.Combine((IntPtr)_data); } @@ -267,9 +267,11 @@ namespace ARMeilleure.IntermediateRepresentation Data* data = Allocators.Operations.Allocate(); *data = default; - Operation result = new(); - result._data = data; - result.Instruction = inst; + Operation result = new() + { + _data = data, + Instruction = inst, + }; EnsureCapacity(ref result._data->Destinations, ref result._data->DestinationsCount, destCount); EnsureCapacity(ref result._data->Sources, ref result._data->SourcesCount, srcCount); @@ -373,4 +375,4 @@ namespace ARMeilleure.IntermediateRepresentation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/Register.cs b/src/ARMeilleure/IntermediateRepresentation/Register.cs index 241e4d13d..208f94be1 100644 --- a/src/ARMeilleure/IntermediateRepresentation/Register.cs +++ b/src/ARMeilleure/IntermediateRepresentation/Register.cs @@ -11,7 +11,7 @@ namespace ARMeilleure.IntermediateRepresentation public Register(int index, RegisterType type) { Index = index; - Type = type; + Type = type; } public override int GetHashCode() @@ -37,7 +37,7 @@ namespace ARMeilleure.IntermediateRepresentation public bool Equals(Register other) { return other.Index == Index && - other.Type == Type; + other.Type == Type; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/IntermediateRepresentation/RegisterType.cs b/src/ARMeilleure/IntermediateRepresentation/RegisterType.cs index 88ac6c124..2b4c9068c 100644 --- a/src/ARMeilleure/IntermediateRepresentation/RegisterType.cs +++ b/src/ARMeilleure/IntermediateRepresentation/RegisterType.cs @@ -5,6 +5,6 @@ namespace ARMeilleure.IntermediateRepresentation Integer, Vector, Flag, - FpFlag + FpFlag, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Memory/IJitMemoryBlock.cs b/src/ARMeilleure/Memory/IJitMemoryBlock.cs index 670f2862d..e94b0a60d 100644 --- a/src/ARMeilleure/Memory/IJitMemoryBlock.cs +++ b/src/ARMeilleure/Memory/IJitMemoryBlock.cs @@ -6,7 +6,7 @@ namespace ARMeilleure.Memory { IntPtr Pointer { get; } - bool Commit(ulong offset, ulong size); + void Commit(ulong offset, ulong size); void MapAsRx(ulong offset, ulong size); void MapAsRwx(ulong offset, ulong size); diff --git a/src/ARMeilleure/Memory/IMemoryManager.cs b/src/ARMeilleure/Memory/IMemoryManager.cs index 5eb1fadd6..ec5b81ebe 100644 --- a/src/ARMeilleure/Memory/IMemoryManager.cs +++ b/src/ARMeilleure/Memory/IMemoryManager.cs @@ -74,4 +74,4 @@ namespace ARMeilleure.Memory /// Optional ID of the handles that should not be signalled void SignalMemoryTracking(ulong va, ulong size, bool write, bool precise = false, int? exemptId = null); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Memory/MemoryManagerType.cs b/src/ARMeilleure/Memory/MemoryManagerType.cs index ce84ccaf3..e897a038f 100644 --- a/src/ARMeilleure/Memory/MemoryManagerType.cs +++ b/src/ARMeilleure/Memory/MemoryManagerType.cs @@ -28,7 +28,7 @@ /// Same as the host mapped memory manager type, but without masking the address within the address space. /// Allows invalid access from JIT code to the rest of the program, but is faster. /// - HostMappedUnsafe + HostMappedUnsafe, } static class MemoryManagerTypeExtensions diff --git a/src/ARMeilleure/Native/JitSupportDarwin.cs b/src/ARMeilleure/Native/JitSupportDarwin.cs index 7d6a8634a..ed347b9cf 100644 --- a/src/ARMeilleure/Native/JitSupportDarwin.cs +++ b/src/ARMeilleure/Native/JitSupportDarwin.cs @@ -5,7 +5,7 @@ using System.Runtime.Versioning; namespace ARMeilleure.Native { [SupportedOSPlatform("macos")] - public static partial class JitSupportDarwin + internal static partial class JitSupportDarwin { [LibraryImport("libarmeilleure-jitsupport", EntryPoint = "armeilleure_jit_memcpy")] public static partial void Copy(IntPtr dst, IntPtr src, ulong n); diff --git a/src/ARMeilleure/Optimizations.cs b/src/ARMeilleure/Optimizations.cs index a84a4dc4f..8fe478e47 100644 --- a/src/ARMeilleure/Optimizations.cs +++ b/src/ARMeilleure/Optimizations.cs @@ -1,5 +1,3 @@ -using System.Runtime.Intrinsics.Arm; - namespace ARMeilleure { using Arm64HardwareCapabilities = ARMeilleure.CodeGen.Arm64.HardwareCapabilities; @@ -9,30 +7,31 @@ namespace ARMeilleure { public static bool FastFP { get; set; } = true; - public static bool AllowLcqInFunctionTable { get; set; } = true; + public static bool AllowLcqInFunctionTable { get; set; } = true; public static bool UseUnmanagedDispatchLoop { get; set; } = true; - public static bool UseAdvSimdIfAvailable { get; set; } = true; + public static bool UseAdvSimdIfAvailable { get; set; } = true; + public static bool UseArm64AesIfAvailable { get; set; } = true; public static bool UseArm64PmullIfAvailable { get; set; } = true; - public static bool UseSseIfAvailable { get; set; } = true; - public static bool UseSse2IfAvailable { get; set; } = true; - public static bool UseSse3IfAvailable { get; set; } = true; - public static bool UseSsse3IfAvailable { get; set; } = true; - public static bool UseSse41IfAvailable { get; set; } = true; - public static bool UseSse42IfAvailable { get; set; } = true; - public static bool UsePopCntIfAvailable { get; set; } = true; - public static bool UseAvxIfAvailable { get; set; } = true; - public static bool UseAvx512FIfAvailable { get; set; } = true; - public static bool UseAvx512VlIfAvailable { get; set; } = true; - public static bool UseAvx512BwIfAvailable { get; set; } = true; - public static bool UseAvx512DqIfAvailable { get; set; } = true; - public static bool UseF16cIfAvailable { get; set; } = true; - public static bool UseFmaIfAvailable { get; set; } = true; - public static bool UseAesniIfAvailable { get; set; } = true; + public static bool UseSseIfAvailable { get; set; } = true; + public static bool UseSse2IfAvailable { get; set; } = true; + public static bool UseSse3IfAvailable { get; set; } = true; + public static bool UseSsse3IfAvailable { get; set; } = true; + public static bool UseSse41IfAvailable { get; set; } = true; + public static bool UseSse42IfAvailable { get; set; } = true; + public static bool UsePopCntIfAvailable { get; set; } = true; + public static bool UseAvxIfAvailable { get; set; } = true; + public static bool UseAvx512FIfAvailable { get; set; } = true; + public static bool UseAvx512VlIfAvailable { get; set; } = true; + public static bool UseAvx512BwIfAvailable { get; set; } = true; + public static bool UseAvx512DqIfAvailable { get; set; } = true; + public static bool UseF16cIfAvailable { get; set; } = true; + public static bool UseFmaIfAvailable { get; set; } = true; + public static bool UseAesniIfAvailable { get; set; } = true; public static bool UsePclmulqdqIfAvailable { get; set; } = true; - public static bool UseShaIfAvailable { get; set; } = true; - public static bool UseGfniIfAvailable { get; set; } = true; + public static bool UseShaIfAvailable { get; set; } = true; + public static bool UseGfniIfAvailable { get; set; } = true; public static bool ForceLegacySse { @@ -40,7 +39,9 @@ namespace ARMeilleure set => X86HardwareCapabilities.ForceLegacySse = value; } +#pragma warning disable IDE0055 // Disable formatting internal static bool UseAdvSimd => UseAdvSimdIfAvailable && Arm64HardwareCapabilities.SupportsAdvSimd; + internal static bool UseArm64Aes => UseArm64AesIfAvailable && Arm64HardwareCapabilities.SupportsAes; internal static bool UseArm64Pmull => UseArm64PmullIfAvailable && Arm64HardwareCapabilities.SupportsPmull; internal static bool UseSse => UseSseIfAvailable && X86HardwareCapabilities.SupportsSse; @@ -61,6 +62,7 @@ namespace ARMeilleure internal static bool UsePclmulqdq => UsePclmulqdqIfAvailable && X86HardwareCapabilities.SupportsPclmulqdq; internal static bool UseSha => UseShaIfAvailable && X86HardwareCapabilities.SupportsSha; internal static bool UseGfni => UseGfniIfAvailable && X86HardwareCapabilities.SupportsGfni; +#pragma warning restore IDE0055 internal static bool UseAvx512Ortho => UseAvx512F && UseAvx512Vl; internal static bool UseAvx512OrthoFloat => UseAvx512Ortho && UseAvx512Dq; diff --git a/src/ARMeilleure/Signal/NativeSignalHandler.cs b/src/ARMeilleure/Signal/NativeSignalHandler.cs index cddeb8174..3f0e9e4bf 100644 --- a/src/ARMeilleure/Signal/NativeSignalHandler.cs +++ b/src/ARMeilleure/Signal/NativeSignalHandler.cs @@ -5,7 +5,6 @@ using ARMeilleure.Translation.Cache; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - using static ARMeilleure.IntermediateRepresentation.Operand.Factory; namespace ARMeilleure.Signal @@ -74,11 +73,11 @@ namespace ARMeilleure.Signal private static ulong _pageSize; private static ulong _pageMask; - private static IntPtr _handlerConfig; + private static readonly IntPtr _handlerConfig; private static IntPtr _signalHandlerPtr; private static IntPtr _signalHandlerHandle; - private static readonly object _lock = new object(); + private static readonly object _lock = new(); private static bool _initialized; static NativeSignalHandler() @@ -96,11 +95,17 @@ namespace ARMeilleure.Signal public static void InitializeSignalHandler(ulong pageSize, Func customSignalHandlerFactory = null) { - if (_initialized) return; + if (_initialized) + { + return; + } lock (_lock) { - if (_initialized) return; + if (_initialized) + { + return; + } _pageSize = pageSize; _pageMask = pageSize - 1; @@ -255,20 +260,20 @@ namespace ARMeilleure.Signal { if (OperatingSystem.IsMacOS()) { - const ulong mcontextOffset = 48; // uc_mcontext - Operand ctxPtr = context.Load(OperandType.I64, context.Add(ucontextPtr, Const(mcontextOffset))); + const ulong McontextOffset = 48; // uc_mcontext + Operand ctxPtr = context.Load(OperandType.I64, context.Add(ucontextPtr, Const(McontextOffset))); if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64) { - const ulong esrOffset = 8; // __es.__esr - Operand esr = context.Load(OperandType.I64, context.Add(ctxPtr, Const(esrOffset))); + const ulong EsrOffset = 8; // __es.__esr + Operand esr = context.Load(OperandType.I64, context.Add(ctxPtr, Const(EsrOffset))); return context.BitwiseAnd(esr, Const(0x40ul)); } if (RuntimeInformation.ProcessArchitecture == Architecture.X64) { - const ulong errOffset = 4; // __es.__err - Operand err = context.Load(OperandType.I64, context.Add(ctxPtr, Const(errOffset))); + const ulong ErrOffset = 4; // __es.__err + Operand err = context.Load(OperandType.I64, context.Add(ctxPtr, Const(ErrOffset))); return context.BitwiseAnd(err, Const(2ul)); } } @@ -281,10 +286,10 @@ namespace ARMeilleure.Signal Operand loopLabel = Label(); Operand successLabel = Label(); - const ulong auxOffset = 464; // uc_mcontext.__reserved - const uint esrMagic = 0x45535201; + const ulong AuxOffset = 464; // uc_mcontext.__reserved + const uint EsrMagic = 0x45535201; - context.Copy(auxPtr, context.Add(ucontextPtr, Const(auxOffset))); + context.Copy(auxPtr, context.Add(ucontextPtr, Const(AuxOffset))); context.MarkLabel(loopLabel); @@ -293,7 +298,7 @@ namespace ARMeilleure.Signal // _aarch64_ctx::size Operand size = context.Load(OperandType.I32, context.Add(auxPtr, Const(4ul))); - context.BranchIf(successLabel, magic, Const(esrMagic), Comparison.Equal); + context.BranchIf(successLabel, magic, Const(EsrMagic), Comparison.Equal); context.Copy(auxPtr, context.Add(auxPtr, context.ZeroExtend32(OperandType.I64, size))); @@ -308,8 +313,8 @@ namespace ARMeilleure.Signal if (RuntimeInformation.ProcessArchitecture == Architecture.X64) { - const int errOffset = 192; // uc_mcontext.gregs[REG_ERR] - Operand err = context.Load(OperandType.I64, context.Add(ucontextPtr, Const(errOffset))); + const int ErrOffset = 192; // uc_mcontext.gregs[REG_ERR] + Operand err = context.Load(OperandType.I64, context.Add(ucontextPtr, Const(ErrOffset))); return context.BitwiseAnd(err, Const(2ul)); } } @@ -319,7 +324,7 @@ namespace ARMeilleure.Signal private static UnixExceptionHandler GenerateUnixSignalHandler(IntPtr signalStructPtr) { - EmitterContext context = new EmitterContext(); + EmitterContext context = new(); // (int sig, SigInfo* sigInfo, void* ucontext) Operand sigInfoPtr = context.LoadArgument(OperandType.I64, 1); @@ -367,7 +372,7 @@ namespace ARMeilleure.Signal private static VectoredExceptionHandler GenerateWindowsSignalHandler(IntPtr signalStructPtr) { - EmitterContext context = new EmitterContext(); + EmitterContext context = new(); // (ExceptionPointers* exceptionInfo) Operand exceptionInfoPtr = context.LoadArgument(OperandType.I64, 0); diff --git a/src/ARMeilleure/Signal/TestMethods.cs b/src/ARMeilleure/Signal/TestMethods.cs index e2ecad242..ec228c850 100644 --- a/src/ARMeilleure/Signal/TestMethods.cs +++ b/src/ARMeilleure/Signal/TestMethods.cs @@ -20,7 +20,7 @@ namespace ARMeilleure.Signal public static DebugPartialUnmap GenerateDebugPartialUnmap() { - EmitterContext context = new EmitterContext(); + EmitterContext context = new(); var result = WindowsPartialUnmapHandler.EmitRetryFromAccessViolation(context); @@ -37,7 +37,7 @@ namespace ARMeilleure.Signal public static DebugThreadLocalMapGetOrReserve GenerateDebugThreadLocalMapGetOrReserve(IntPtr structPtr) { - EmitterContext context = new EmitterContext(); + EmitterContext context = new(); var result = WindowsPartialUnmapHandler.EmitThreadLocalMapIntGetOrReserve(context, structPtr, context.LoadArgument(OperandType.I32, 0), context.LoadArgument(OperandType.I32, 1)); @@ -54,7 +54,7 @@ namespace ARMeilleure.Signal public static DebugNativeWriteLoop GenerateDebugNativeWriteLoop() { - EmitterContext context = new EmitterContext(); + EmitterContext context = new(); // Loop a write to the target address until "running" is false. diff --git a/src/ARMeilleure/Signal/UnixSignalHandlerRegistration.cs b/src/ARMeilleure/Signal/UnixSignalHandlerRegistration.cs index 22009240b..79a8f803d 100644 --- a/src/ARMeilleure/Signal/UnixSignalHandlerRegistration.cs +++ b/src/ARMeilleure/Signal/UnixSignalHandlerRegistration.cs @@ -47,10 +47,10 @@ namespace ARMeilleure.Signal public static SigAction RegisterExceptionHandler(IntPtr action) { - SigAction sig = new SigAction + SigAction sig = new() { sa_handler = action, - sa_flags = SA_SIGINFO + sa_flags = SA_SIGINFO, }; sigemptyset(ref sig.sa_mask); diff --git a/src/ARMeilleure/Signal/WindowsPartialUnmapHandler.cs b/src/ARMeilleure/Signal/WindowsPartialUnmapHandler.cs index 941e36e58..4da1b32dc 100644 --- a/src/ARMeilleure/Signal/WindowsPartialUnmapHandler.cs +++ b/src/ARMeilleure/Signal/WindowsPartialUnmapHandler.cs @@ -137,6 +137,7 @@ namespace ARMeilleure.Signal return context.Add(structsPtr, context.SignExtend32(OperandType.I64, offset)); } +#pragma warning disable IDE0051 // Remove unused private member private static void EmitThreadLocalMapIntRelease(EmitterContext context, IntPtr threadLocalMapPtr, Operand threadId, Operand index) { Operand offset = context.Multiply(index, Const(sizeof(int))); @@ -145,6 +146,7 @@ namespace ARMeilleure.Signal context.CompareAndSwap(idPtr, threadId, Const(0)); } +#pragma warning restore IDE0051 private static void EmitAtomicAddI32(EmitterContext context, Operand ptr, Operand additive) { diff --git a/src/ARMeilleure/State/Aarch32Mode.cs b/src/ARMeilleure/State/Aarch32Mode.cs index 395e288aa..add1cd26f 100644 --- a/src/ARMeilleure/State/Aarch32Mode.cs +++ b/src/ARMeilleure/State/Aarch32Mode.cs @@ -2,14 +2,14 @@ namespace ARMeilleure.State { enum Aarch32Mode { - User = 0b10000, - Fiq = 0b10001, - Irq = 0b10010, + User = 0b10000, + Fiq = 0b10001, + Irq = 0b10010, Supervisor = 0b10011, - Monitor = 0b10110, - Abort = 0b10111, + Monitor = 0b10110, + Abort = 0b10111, Hypervisor = 0b11010, - Undefined = 0b11011, - System = 0b11111 + Undefined = 0b11011, + System = 0b11111, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/ExceptionCallback.cs b/src/ARMeilleure/State/ExceptionCallback.cs index 38d6eef78..2a4e9656a 100644 --- a/src/ARMeilleure/State/ExceptionCallback.cs +++ b/src/ARMeilleure/State/ExceptionCallback.cs @@ -2,4 +2,4 @@ namespace ARMeilleure.State { public delegate void ExceptionCallbackNoArgs(ExecutionContext context); public delegate void ExceptionCallback(ExecutionContext context, ulong address, int id); -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/ExecutionContext.cs b/src/ARMeilleure/State/ExecutionContext.cs index 859fb3a5d..ce10a591c 100644 --- a/src/ARMeilleure/State/ExecutionContext.cs +++ b/src/ARMeilleure/State/ExecutionContext.cs @@ -7,7 +7,7 @@ namespace ARMeilleure.State { private const int MinCountForCheck = 4000; - private NativeContext _nativeContext; + private readonly NativeContext _nativeContext; internal IntPtr NativeContextPtr => _nativeContext.BasePtr; @@ -17,8 +17,10 @@ namespace ARMeilleure.State public ulong Pc => _nativeContext.GetPc(); +#pragma warning disable CA1822 // Mark member as static public uint CtrEl0 => 0x8444c004; public uint DczidEl0 => 0x00000004; +#pragma warning restore CA1822 public ulong CntfrqEl0 => _counter.Frequency; public ulong CntpctEl0 => _counter.Counter; @@ -170,4 +172,4 @@ namespace ARMeilleure.State _nativeContext.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/ExecutionMode.cs b/src/ARMeilleure/State/ExecutionMode.cs index 29154a255..e1fb722bd 100644 --- a/src/ARMeilleure/State/ExecutionMode.cs +++ b/src/ARMeilleure/State/ExecutionMode.cs @@ -1,9 +1,9 @@ namespace ARMeilleure.State { - enum ExecutionMode : int + enum ExecutionMode { Aarch32Arm = 0, Aarch32Thumb = 1, - Aarch64 = 2 + Aarch64 = 2, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/FPCR.cs b/src/ARMeilleure/State/FPCR.cs index 6f707de7d..427300add 100644 --- a/src/ARMeilleure/State/FPCR.cs +++ b/src/ARMeilleure/State/FPCR.cs @@ -13,10 +13,10 @@ namespace ARMeilleure.State Ide = 1u << 15, RMode0 = 1u << 22, RMode1 = 1u << 23, - Fz = 1u << 24, - Dn = 1u << 25, + Fz = 1u << 24, + Dn = 1u << 25, Ahp = 1u << 26, - Mask = Ahp | Dn | Fz | RMode1 | RMode0 | Ide | Ixe | Ufe | Ofe | Dze | Ioe // 0x07C09F00u + Mask = Ahp | Dn | Fz | RMode1 | RMode0 | Ide | Ixe | Ufe | Ofe | Dze | Ioe, // 0x07C09F00u } } diff --git a/src/ARMeilleure/State/FPException.cs b/src/ARMeilleure/State/FPException.cs index e24e07af1..5b13659ab 100644 --- a/src/ARMeilleure/State/FPException.cs +++ b/src/ARMeilleure/State/FPException.cs @@ -2,11 +2,11 @@ namespace ARMeilleure.State { enum FPException { - InvalidOp = 0, + InvalidOp = 0, DivideByZero = 1, - Overflow = 2, - Underflow = 3, - Inexact = 4, - InputDenorm = 7 + Overflow = 2, + Underflow = 3, + Inexact = 4, + InputDenorm = 7, } } diff --git a/src/ARMeilleure/State/FPRoundingMode.cs b/src/ARMeilleure/State/FPRoundingMode.cs index 8d757a151..0913175e7 100644 --- a/src/ARMeilleure/State/FPRoundingMode.cs +++ b/src/ARMeilleure/State/FPRoundingMode.cs @@ -2,10 +2,10 @@ namespace ARMeilleure.State { public enum FPRoundingMode { - ToNearest = 0, // With ties to even. - TowardsPlusInfinity = 1, + ToNearest = 0, // With ties to even. + TowardsPlusInfinity = 1, TowardsMinusInfinity = 2, - TowardsZero = 3, - ToNearestAway = 4 // With ties to away. + TowardsZero = 3, + ToNearestAway = 4, // With ties to away. } } diff --git a/src/ARMeilleure/State/FPSCR.cs b/src/ARMeilleure/State/FPSCR.cs index d6d2fc26a..65a060ebd 100644 --- a/src/ARMeilleure/State/FPSCR.cs +++ b/src/ARMeilleure/State/FPSCR.cs @@ -10,6 +10,6 @@ namespace ARMeilleure.State Z = 1u << 30, N = 1u << 31, - Mask = N | Z | C | V | FPSR.Mask | FPCR.Mask // 0xFFC09F9Fu + Mask = N | Z | C | V | FPSR.Mask | FPCR.Mask, // 0xFFC09F9Fu } } diff --git a/src/ARMeilleure/State/FPSR.cs b/src/ARMeilleure/State/FPSR.cs index 5e66d5ce1..915b2fb31 100644 --- a/src/ARMeilleure/State/FPSR.cs +++ b/src/ARMeilleure/State/FPSR.cs @@ -13,6 +13,6 @@ namespace ARMeilleure.State Idc = 1u << 7, Qc = 1u << 27, - Mask = Qc | Idc | Ixc | Ufc | Ofc | Dzc | Ioc // 0x0800009Fu + Mask = Qc | Idc | Ixc | Ufc | Ofc | Dzc | Ioc, // 0x0800009Fu } } diff --git a/src/ARMeilleure/State/FPState.cs b/src/ARMeilleure/State/FPState.cs index fa6ab9d46..027272eee 100644 --- a/src/ARMeilleure/State/FPState.cs +++ b/src/ARMeilleure/State/FPState.cs @@ -26,6 +26,6 @@ RMode1Flag = 23, FzFlag = 24, DnFlag = 25, - AhpFlag = 26 + AhpFlag = 26, } } diff --git a/src/ARMeilleure/State/FPType.cs b/src/ARMeilleure/State/FPType.cs index 84e0db8da..367082ffc 100644 --- a/src/ARMeilleure/State/FPType.cs +++ b/src/ARMeilleure/State/FPType.cs @@ -6,6 +6,6 @@ namespace ARMeilleure.State Zero, Infinity, QNaN, - SNaN + SNaN, } } diff --git a/src/ARMeilleure/State/ICounter.cs b/src/ARMeilleure/State/ICounter.cs index 93e721ea3..7aa1cce73 100644 --- a/src/ARMeilleure/State/ICounter.cs +++ b/src/ARMeilleure/State/ICounter.cs @@ -15,4 +15,4 @@ namespace ARMeilleure.State /// ulong Counter { get; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/NativeContext.cs b/src/ARMeilleure/State/NativeContext.cs index 3189bdd8a..5403042ea 100644 --- a/src/ARMeilleure/State/NativeContext.cs +++ b/src/ARMeilleure/State/NativeContext.cs @@ -23,7 +23,7 @@ namespace ARMeilleure.State public int Running; } - private static NativeCtxStorage _dummyStorage = new NativeCtxStorage(); + private static NativeCtxStorage _dummyStorage = new(); private readonly IJitMemoryBlock _block; @@ -266,4 +266,4 @@ namespace ARMeilleure.State public void Dispose() => _block.Dispose(); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/PState.cs b/src/ARMeilleure/State/PState.cs index 9a80bc570..d4ddc8656 100644 --- a/src/ARMeilleure/State/PState.cs +++ b/src/ARMeilleure/State/PState.cs @@ -12,6 +12,6 @@ namespace ARMeilleure.State VFlag = 28, CFlag = 29, ZFlag = 30, - NFlag = 31 + NFlag = 31, } } diff --git a/src/ARMeilleure/State/RegisterAlias.cs b/src/ARMeilleure/State/RegisterAlias.cs index 7ebfa2753..a95740891 100644 --- a/src/ARMeilleure/State/RegisterAlias.cs +++ b/src/ARMeilleure/State/RegisterAlias.cs @@ -2,13 +2,13 @@ namespace ARMeilleure.State { static class RegisterAlias { - public const int R8Usr = 8; - public const int R9Usr = 9; + public const int R8Usr = 8; + public const int R9Usr = 9; public const int R10Usr = 10; public const int R11Usr = 11; public const int R12Usr = 12; - public const int SpUsr = 13; - public const int LrUsr = 14; + public const int SpUsr = 13; + public const int LrUsr = 14; public const int SpHyp = 15; @@ -24,13 +24,13 @@ namespace ARMeilleure.State public const int LrUnd = 22; public const int SpUnd = 23; - public const int R8Fiq = 24; - public const int R9Fiq = 25; + public const int R8Fiq = 24; + public const int R9Fiq = 25; public const int R10Fiq = 26; public const int R11Fiq = 27; public const int R12Fiq = 28; - public const int SpFiq = 29; - public const int LrFiq = 30; + public const int SpFiq = 29; + public const int LrFiq = 30; public const int Aarch32Sp = 13; public const int Aarch32Lr = 14; @@ -39,4 +39,4 @@ namespace ARMeilleure.State public const int Lr = 30; public const int Zr = 31; } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/RegisterConsts.cs b/src/ARMeilleure/State/RegisterConsts.cs index d62940808..b43f8d646 100644 --- a/src/ARMeilleure/State/RegisterConsts.cs +++ b/src/ARMeilleure/State/RegisterConsts.cs @@ -2,14 +2,14 @@ namespace ARMeilleure.State { static class RegisterConsts { - public const int IntRegsCount = 32; - public const int VecRegsCount = 32; - public const int FlagsCount = 32; - public const int FpFlagsCount = 32; + public const int IntRegsCount = 32; + public const int VecRegsCount = 32; + public const int FlagsCount = 32; + public const int FpFlagsCount = 32; public const int IntAndVecRegsCount = IntRegsCount + VecRegsCount; - public const int FpFlagsOffset = IntRegsCount + VecRegsCount + FlagsCount; - public const int TotalCount = IntRegsCount + VecRegsCount + FlagsCount + FpFlagsCount; + public const int FpFlagsOffset = IntRegsCount + VecRegsCount + FlagsCount; + public const int TotalCount = IntRegsCount + VecRegsCount + FlagsCount + FpFlagsCount; public const int ZeroIndex = 31; } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/State/V128.cs b/src/ARMeilleure/State/V128.cs index 3fa9f9a99..cbcaddfc2 100644 --- a/src/ARMeilleure/State/V128.cs +++ b/src/ARMeilleure/State/V128.cs @@ -13,13 +13,13 @@ namespace ARMeilleure.State // _e0 & _e1 could be marked as readonly, however they are not readonly because we modify them through the Unsafe // APIs. This also means that one should be careful when changing the layout of this struct. - private ulong _e0; - private ulong _e1; + private readonly ulong _e0; + private readonly ulong _e1; /// /// Gets a new with all bits set to zero. /// - public static V128 Zero => new V128(0, 0); + public static V128 Zero => new(0, 0); /// /// Initializes a new instance of the struct with the specified value @@ -55,9 +55,9 @@ namespace ARMeilleure.State /// Element 3 public V128(float e0, float e1, float e2, float e3) { - _e0 = (ulong)(uint)BitConverter.SingleToInt32Bits(e0) << 0; + _e0 = (ulong)(uint)BitConverter.SingleToInt32Bits(e0) << 0; _e0 |= (ulong)(uint)BitConverter.SingleToInt32Bits(e1) << 32; - _e1 = (ulong)(uint)BitConverter.SingleToInt32Bits(e2) << 0; + _e1 = (ulong)(uint)BitConverter.SingleToInt32Bits(e2) << 0; _e1 |= (ulong)(uint)BitConverter.SingleToInt32Bits(e3) << 32; } @@ -98,9 +98,9 @@ namespace ARMeilleure.State /// Element 3 public V128(uint e0, uint e1, uint e2, uint e3) { - _e0 = (ulong)e0 << 0; + _e0 = (ulong)e0 << 0; _e0 |= (ulong)e1 << 32; - _e1 = (ulong)e2 << 0; + _e1 = (ulong)e2 << 0; _e1 |= (ulong)e3 << 32; } @@ -137,7 +137,9 @@ namespace ARMeilleure.State public T Extract(int index) where T : unmanaged { if ((uint)index >= GetElementCount()) + { ThrowIndexOutOfRange(); + } // Performs: // return *((*T)this + index); @@ -156,7 +158,9 @@ namespace ARMeilleure.State public void Insert(int index, T value) where T : unmanaged { if ((uint)index >= GetElementCount()) + { ThrowIndexOutOfRange(); + } // Performs: // *((*T)this + index) = value; @@ -167,13 +171,13 @@ namespace ARMeilleure.State /// Returns a new array which represents the . /// /// A new array which represents the - public byte[] ToArray() + public readonly byte[] ToArray() { - byte[] data = new byte[16]; + byte[] data = new byte[16]; Span span = data; BitConverter.TryWriteBytes(span, _e0); - BitConverter.TryWriteBytes(span.Slice(8), _e1); + BitConverter.TryWriteBytes(span[8..], _e1); return data; } @@ -225,7 +229,7 @@ namespace ARMeilleure.State /// /// Target /// Result of not operation - public static V128 operator ~(V128 x) => new V128(~x._e0, ~x._e1); + public static V128 operator ~(V128 x) => new(~x._e0, ~x._e1); /// /// Performs a bitwise and on the specified instances. @@ -233,7 +237,7 @@ namespace ARMeilleure.State /// First instance /// Second instance /// Result of and operation - public static V128 operator &(V128 x, V128 y) => new V128(x._e0 & y._e0, x._e1 & y._e1); + public static V128 operator &(V128 x, V128 y) => new(x._e0 & y._e0, x._e1 & y._e1); /// /// Performs a bitwise or on the specified instances. @@ -241,7 +245,7 @@ namespace ARMeilleure.State /// First instance /// Second instance /// Result of or operation - public static V128 operator |(V128 x, V128 y) => new V128(x._e0 | y._e0, x._e1 | y._e1); + public static V128 operator |(V128 x, V128 y) => new(x._e0 | y._e0, x._e1 | y._e1); /// /// Performs a bitwise exlusive or on the specified instances. @@ -249,7 +253,7 @@ namespace ARMeilleure.State /// First instance /// Second instance /// Result of exclusive or operation - public static V128 operator ^(V128 x, V128 y) => new V128(x._e0 ^ y._e0, x._e1 ^ y._e1); + public static V128 operator ^(V128 x, V128 y) => new(x._e0 ^ y._e0, x._e1 ^ y._e1); /// /// Determines if the specified instances are equal. @@ -272,7 +276,7 @@ namespace ARMeilleure.State /// /// Other instance /// true if equal; otherwise false - public bool Equals(V128 other) + public readonly bool Equals(V128 other) { return other._e0 == _e0 && other._e1 == _e1; } @@ -282,24 +286,24 @@ namespace ARMeilleure.State /// /// Other instance /// true if equal; otherwise false - public override bool Equals(object obj) + public readonly override bool Equals(object obj) { return obj is V128 vector && Equals(vector); } /// - public override int GetHashCode() + public readonly override int GetHashCode() { return HashCode.Combine(_e0, _e1); } /// - public override string ToString() + public readonly override string ToString() { return $"0x{_e1:X16}{_e0:X16}"; } - private uint GetElementCount() where T : unmanaged + private static uint GetElementCount() where T : unmanaged { return (uint)(Unsafe.SizeOf() / Unsafe.SizeOf()); } @@ -309,4 +313,4 @@ namespace ARMeilleure.State throw new ArgumentOutOfRangeException("index"); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Statistics.cs b/src/ARMeilleure/Statistics.cs index fbc647082..2f873bcfa 100644 --- a/src/ARMeilleure/Statistics.cs +++ b/src/ARMeilleure/Statistics.cs @@ -1,4 +1,6 @@ +#if M_PROFILE using System; +#endif using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; @@ -11,12 +13,12 @@ namespace ARMeilleure { private const int ReportMaxFunctions = 100; -#pragma warning disable CS0169 +#if M_PROFILE [ThreadStatic] private static Stopwatch _executionTimer; -#pragma warning restore CS0169 +#endif - private static ConcurrentDictionary _ticksPerFunction; + private static readonly ConcurrentDictionary _ticksPerFunction; static Statistics() { @@ -47,7 +49,7 @@ namespace ARMeilleure long ticks = _executionTimer.ElapsedTicks; - _ticksPerFunction.AddOrUpdate(funcAddr, ticks, (key, oldTicks) => oldTicks + ticks); + TicksPerFunction.AddOrUpdate(funcAddr, ticks, (key, oldTicks) => oldTicks + ticks); #endif } @@ -69,7 +71,7 @@ namespace ARMeilleure { int count = 0; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine(" Function address | Time"); sb.AppendLine("--------------------------"); @@ -91,4 +93,4 @@ namespace ARMeilleure return sb.ToString(); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/ArmEmitterContext.cs b/src/ARMeilleure/Translation/ArmEmitterContext.cs index 565d2aada..e24074739 100644 --- a/src/ARMeilleure/Translation/ArmEmitterContext.cs +++ b/src/ARMeilleure/Translation/ArmEmitterContext.cs @@ -55,7 +55,7 @@ namespace ARMeilleure.Translation public Aarch32Mode Mode { get; } private int _ifThenBlockStateIndex = 0; - private Condition[] _ifThenBlockState = { }; + private Condition[] _ifThenBlockState = Array.Empty(); public bool IsInIfThenBlock => _ifThenBlockStateIndex < _ifThenBlockState.Length; public Condition CurrentIfThenBlockCond => _ifThenBlockState[_ifThenBlockStateIndex]; @@ -96,7 +96,7 @@ namespace ARMeilleure.Translation OperandType returnType = GetOperandType(info.ReturnType); - Symbol symbol = new Symbol(SymbolType.DelegateTable, (ulong)index); + Symbol symbol = new(SymbolType.DelegateTable, (ulong)index); Symbols.Add((ulong)funcPtr.ToInt64(), info.Name); @@ -219,6 +219,7 @@ namespace ARMeilleure.Translation { switch (condition) { +#pragma warning disable IDE0055 // Disable formatting case Condition.Eq: return ICompareEqual (n, m); case Condition.Ne: return ICompareNotEqual (n, m); case Condition.GeUn: return ICompareGreaterOrEqualUI(n, m); @@ -229,6 +230,7 @@ namespace ARMeilleure.Translation case Condition.Lt: return ICompareLess (n, m); case Condition.Gt: return ICompareGreater (n, m); case Condition.Le: return ICompareLessOrEqual (n, m); +#pragma warning restore IDE0055 } } else if (cmpName == InstName.Adds && _optOpLastCompare is IOpCodeAluImm op) @@ -253,12 +255,14 @@ namespace ARMeilleure.Translation switch (condition) { +#pragma warning disable IDE0055 // Disable formatting case Condition.Eq: return ICompareEqual (n, m); case Condition.Ne: return ICompareNotEqual (n, m); case Condition.Ge: return ICompareGreaterOrEqual(n, m); case Condition.Lt: return ICompareLess (n, m); case Condition.Gt: return ICompareGreater (n, m); case Condition.Le: return ICompareLessOrEqual (n, m); +#pragma warning restore IDE0055 } } @@ -279,4 +283,4 @@ namespace ARMeilleure.Translation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/Cache/CacheEntry.cs b/src/ARMeilleure/Translation/Cache/CacheEntry.cs index dc5503b18..25b06f781 100644 --- a/src/ARMeilleure/Translation/Cache/CacheEntry.cs +++ b/src/ARMeilleure/Translation/Cache/CacheEntry.cs @@ -7,14 +7,14 @@ namespace ARMeilleure.Translation.Cache readonly struct CacheEntry : IComparable { public int Offset { get; } - public int Size { get; } + public int Size { get; } public UnwindInfo UnwindInfo { get; } public CacheEntry(int offset, int size, UnwindInfo unwindInfo) { - Offset = offset; - Size = size; + Offset = offset; + Size = size; UnwindInfo = unwindInfo; } @@ -23,4 +23,4 @@ namespace ARMeilleure.Translation.Cache return Offset.CompareTo(other.Offset); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/Cache/CacheMemoryAllocator.cs b/src/ARMeilleure/Translation/Cache/CacheMemoryAllocator.cs index 4c22de40e..dd67e4201 100644 --- a/src/ARMeilleure/Translation/Cache/CacheMemoryAllocator.cs +++ b/src/ARMeilleure/Translation/Cache/CacheMemoryAllocator.cs @@ -23,7 +23,7 @@ namespace ARMeilleure.Translation.Cache } } - private readonly List _blocks = new List(); + private readonly List _blocks = new(); public CacheMemoryAllocator(int capacity) { diff --git a/src/ARMeilleure/Translation/Cache/JitCache.cs b/src/ARMeilleure/Translation/Cache/JitCache.cs index daa2eeac2..91a054123 100644 --- a/src/ARMeilleure/Translation/Cache/JitCache.cs +++ b/src/ARMeilleure/Translation/Cache/JitCache.cs @@ -2,6 +2,7 @@ using ARMeilleure.CodeGen; using ARMeilleure.CodeGen.Unwinding; using ARMeilleure.Memory; using ARMeilleure.Native; +using Ryujinx.Memory; using System; using System.Collections.Generic; using System.Diagnostics; @@ -12,8 +13,8 @@ namespace ARMeilleure.Translation.Cache { static partial class JitCache { - private const int PageSize = 4 * 1024; - private const int PageMask = PageSize - 1; + private static readonly int _pageSize = (int)MemoryBlock.GetPageSize(); + private static readonly int _pageMask = _pageSize - 1; private const int CodeAlignment = 4; // Bytes. private const int CacheSize = 2047 * 1024 * 1024; @@ -23,9 +24,9 @@ namespace ARMeilleure.Translation.Cache private static CacheMemoryAllocator _cacheAllocator; - private static readonly List _cacheEntries = new List(); + private static readonly List _cacheEntries = new(); - private static readonly object _lock = new object(); + private static readonly object _lock = new(); private static bool _initialized; [SupportedOSPlatform("windows")] @@ -34,11 +35,17 @@ namespace ARMeilleure.Translation.Cache public static void Initialize(IJitMemoryAllocator allocator) { - if (_initialized) return; + if (_initialized) + { + return; + } lock (_lock) { - if (_initialized) return; + if (_initialized) + { + return; + } _jitRegion = new ReservedRegion(allocator, CacheSize); @@ -51,7 +58,7 @@ namespace ARMeilleure.Translation.Cache if (OperatingSystem.IsWindows()) { - JitUnwindWindows.InstallFunctionTableHandler(_jitRegion.Pointer, CacheSize, _jitRegion.Pointer + Allocate(PageSize)); + JitUnwindWindows.InstallFunctionTableHandler(_jitRegion.Pointer, CacheSize, _jitRegion.Pointer + Allocate(_pageSize)); } _initialized = true; @@ -74,7 +81,7 @@ namespace ARMeilleure.Translation.Cache { unsafe { - fixed (byte *codePtr = code) + fixed (byte* codePtr = code) { JitSupportDarwin.Copy(funcPtr, (IntPtr)codePtr, (ulong)code.Length); } @@ -123,8 +130,8 @@ namespace ARMeilleure.Translation.Cache { int endOffs = offset + size; - int regionStart = offset & ~PageMask; - int regionEnd = (endOffs + PageMask) & ~PageMask; + int regionStart = offset & ~_pageMask; + int regionEnd = (endOffs + _pageMask) & ~_pageMask; _jitRegion.Block.MapAsRwx((ulong)regionStart, (ulong)(regionEnd - regionStart)); } @@ -133,8 +140,8 @@ namespace ARMeilleure.Translation.Cache { int endOffs = offset + size; - int regionStart = offset & ~PageMask; - int regionEnd = (endOffs + PageMask) & ~PageMask; + int regionStart = offset & ~_pageMask; + int regionEnd = (endOffs + _pageMask) & ~_pageMask; _jitRegion.Block.MapAsRx((ulong)regionStart, (ulong)(regionEnd - regionStart)); } @@ -162,7 +169,7 @@ namespace ARMeilleure.Translation.Cache private static void Add(int offset, int size, UnwindInfo unwindInfo) { - CacheEntry entry = new CacheEntry(offset, size, unwindInfo); + CacheEntry entry = new(offset, size, unwindInfo); int index = _cacheEntries.BinarySearch(entry); @@ -211,4 +218,4 @@ namespace ARMeilleure.Translation.Cache return false; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/Cache/JitCacheInvalidation.cs b/src/ARMeilleure/Translation/Cache/JitCacheInvalidation.cs index 57f7bf121..3aa2e19f1 100644 --- a/src/ARMeilleure/Translation/Cache/JitCacheInvalidation.cs +++ b/src/ARMeilleure/Translation/Cache/JitCacheInvalidation.cs @@ -6,7 +6,7 @@ namespace ARMeilleure.Translation.Cache { class JitCacheInvalidation { - private static int[] _invalidationCode = new int[] + private static readonly int[] _invalidationCode = new int[] { unchecked((int)0xd53b0022), // mrs x2, ctr_el0 unchecked((int)0xd3504c44), // ubfx x4, x2, #16, #4 @@ -40,8 +40,8 @@ namespace ARMeilleure.Translation.Cache private delegate void InvalidateCache(ulong start, ulong end); - private InvalidateCache _invalidateCache; - private ReservedRegion _invalidateCacheCodeRegion; + private readonly InvalidateCache _invalidateCache; + private readonly ReservedRegion _invalidateCacheCodeRegion; private readonly bool _needsInvalidation; @@ -76,4 +76,4 @@ namespace ARMeilleure.Translation.Cache } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs b/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs index 77727bf16..91fd19c25 100644 --- a/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs +++ b/src/ARMeilleure/Translation/Cache/JitUnwindWindows.cs @@ -29,15 +29,15 @@ namespace ARMeilleure.Translation.Cache private enum UnwindOp { - PushNonvol = 0, - AllocLarge = 1, - AllocSmall = 2, - SetFpreg = 3, - SaveNonvol = 4, + PushNonvol = 0, + AllocLarge = 1, + AllocSmall = 2, + SetFpreg = 3, + SaveNonvol = 4, SaveNonvolFar = 5, - SaveXmm128 = 8, + SaveXmm128 = 8, SaveXmm128Far = 9, - PushMachframe = 10 + PushMachframe = 10, } private unsafe delegate RuntimeFunction* GetRuntimeFunctionCallback(ulong controlPc, IntPtr context); @@ -111,72 +111,73 @@ namespace ARMeilleure.Translation.Cache switch (entry.PseudoOp) { case UnwindPseudoOp.SaveXmm128: - { - int stackOffset = entry.StackOffsetOrAllocSize; - - Debug.Assert(stackOffset % 16 == 0); - - if (stackOffset <= 0xFFFF0) { - _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.SaveXmm128, entry.PrologOffset, entry.RegIndex); - _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(stackOffset / 16); - } - else - { - _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.SaveXmm128Far, entry.PrologOffset, entry.RegIndex); - _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(stackOffset >> 0); - _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(stackOffset >> 16); - } + int stackOffset = entry.StackOffsetOrAllocSize; - break; - } + Debug.Assert(stackOffset % 16 == 0); + + if (stackOffset <= 0xFFFF0) + { + _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.SaveXmm128, entry.PrologOffset, entry.RegIndex); + _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(stackOffset / 16); + } + else + { + _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.SaveXmm128Far, entry.PrologOffset, entry.RegIndex); + _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(stackOffset >> 0); + _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(stackOffset >> 16); + } + + break; + } case UnwindPseudoOp.AllocStack: - { - int allocSize = entry.StackOffsetOrAllocSize; - - Debug.Assert(allocSize % 8 == 0); - - if (allocSize <= 128) { - _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.AllocSmall, entry.PrologOffset, (allocSize / 8) - 1); - } - else if (allocSize <= 0x7FFF8) - { - _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.AllocLarge, entry.PrologOffset, 0); - _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(allocSize / 8); - } - else - { - _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.AllocLarge, entry.PrologOffset, 1); - _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(allocSize >> 0); - _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(allocSize >> 16); - } + int allocSize = entry.StackOffsetOrAllocSize; - break; - } + Debug.Assert(allocSize % 8 == 0); + + if (allocSize <= 128) + { + _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.AllocSmall, entry.PrologOffset, (allocSize / 8) - 1); + } + else if (allocSize <= 0x7FFF8) + { + _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.AllocLarge, entry.PrologOffset, 0); + _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(allocSize / 8); + } + else + { + _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.AllocLarge, entry.PrologOffset, 1); + _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(allocSize >> 0); + _unwindInfo->UnwindCodes[codeIndex++] = (ushort)(allocSize >> 16); + } + + break; + } case UnwindPseudoOp.PushReg: - { - _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.PushNonvol, entry.PrologOffset, entry.RegIndex); + { + _unwindInfo->UnwindCodes[codeIndex++] = PackUnwindOp(UnwindOp.PushNonvol, entry.PrologOffset, entry.RegIndex); - break; - } + break; + } - default: throw new NotImplementedException($"({nameof(entry.PseudoOp)} = {entry.PseudoOp})"); + default: + throw new NotImplementedException($"({nameof(entry.PseudoOp)} = {entry.PseudoOp})"); } } Debug.Assert(codeIndex <= MaxUnwindCodesArraySize); - _unwindInfo->VersionAndFlags = 1; // Flags: The function has no handler. - _unwindInfo->SizeOfProlog = (byte)unwindInfo.PrologSize; + _unwindInfo->VersionAndFlags = 1; // Flags: The function has no handler. + _unwindInfo->SizeOfProlog = (byte)unwindInfo.PrologSize; _unwindInfo->CountOfUnwindCodes = (byte)codeIndex; - _unwindInfo->FrameRegister = 0; + _unwindInfo->FrameRegister = 0; _runtimeFunction->BeginAddress = (uint)funcEntry.Offset; - _runtimeFunction->EndAddress = (uint)(funcEntry.Offset + funcEntry.Size); - _runtimeFunction->UnwindData = (uint)_sizeOfRuntimeFunction; + _runtimeFunction->EndAddress = (uint)(funcEntry.Offset + funcEntry.Size); + _runtimeFunction->UnwindData = (uint)_sizeOfRuntimeFunction; return _runtimeFunction; } @@ -186,4 +187,4 @@ namespace ARMeilleure.Translation.Cache return (ushort)(prologOffset | ((int)op << 8) | (opInfo << 12)); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/Compiler.cs b/src/ARMeilleure/Translation/Compiler.cs index d4aa5cd96..293e63496 100644 --- a/src/ARMeilleure/Translation/Compiler.cs +++ b/src/ARMeilleure/Translation/Compiler.cs @@ -11,10 +11,10 @@ namespace ARMeilleure.Translation { public static CompiledFunction Compile( ControlFlowGraph cfg, - OperandType[] argTypes, - OperandType retType, - CompilerOptions options, - Architecture target) + OperandType[] argTypes, + OperandType retType, + CompilerOptions options, + Architecture target) { CompilerContext cctx = new(cfg, argTypes, retType, options); @@ -65,4 +65,4 @@ namespace ARMeilleure.Translation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/CompilerContext.cs b/src/ARMeilleure/Translation/CompilerContext.cs index 510dec58f..5b10686b3 100644 --- a/src/ARMeilleure/Translation/CompilerContext.cs +++ b/src/ARMeilleure/Translation/CompilerContext.cs @@ -6,21 +6,21 @@ namespace ARMeilleure.Translation { public ControlFlowGraph Cfg { get; } - public OperandType[] FuncArgTypes { get; } - public OperandType FuncReturnType { get; } + public OperandType[] FuncArgTypes { get; } + public OperandType FuncReturnType { get; } public CompilerOptions Options { get; } public CompilerContext( ControlFlowGraph cfg, - OperandType[] funcArgTypes, - OperandType funcReturnType, - CompilerOptions options) + OperandType[] funcArgTypes, + OperandType funcReturnType, + CompilerOptions options) { - Cfg = cfg; - FuncArgTypes = funcArgTypes; + Cfg = cfg; + FuncArgTypes = funcArgTypes; FuncReturnType = funcReturnType; - Options = options; + Options = options; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/CompilerOptions.cs b/src/ARMeilleure/Translation/CompilerOptions.cs index 0a07ed4ab..d454de7f2 100644 --- a/src/ARMeilleure/Translation/CompilerOptions.cs +++ b/src/ARMeilleure/Translation/CompilerOptions.cs @@ -5,13 +5,13 @@ namespace ARMeilleure.Translation [Flags] enum CompilerOptions { - None = 0, - SsaForm = 1 << 0, - Optimize = 1 << 1, - Lsra = 1 << 2, + None = 0, + SsaForm = 1 << 0, + Optimize = 1 << 1, + Lsra = 1 << 2, Relocatable = 1 << 3, MediumCq = SsaForm | Optimize, - HighCq = SsaForm | Optimize | Lsra + HighCq = SsaForm | Optimize | Lsra, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/ControlFlowGraph.cs b/src/ARMeilleure/Translation/ControlFlowGraph.cs index c935f1521..3ead49c93 100644 --- a/src/ARMeilleure/Translation/ControlFlowGraph.cs +++ b/src/ARMeilleure/Translation/ControlFlowGraph.cs @@ -130,7 +130,7 @@ namespace ARMeilleure.Translation public BasicBlock SplitEdge(BasicBlock predecessor, BasicBlock successor) { - BasicBlock splitBlock = new BasicBlock(Blocks.Count); + BasicBlock splitBlock = new(Blocks.Count); for (int i = 0; i < predecessor.SuccessorsCount; i++) { @@ -152,4 +152,4 @@ namespace ARMeilleure.Translation return splitBlock; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/DelegateInfo.cs b/src/ARMeilleure/Translation/DelegateInfo.cs index 36320ac31..27479a003 100644 --- a/src/ARMeilleure/Translation/DelegateInfo.cs +++ b/src/ARMeilleure/Translation/DelegateInfo.cs @@ -5,7 +5,9 @@ namespace ARMeilleure.Translation { class DelegateInfo { +#pragma warning disable IDE0052 // Remove unread private member private readonly Delegate _dlg; // Ensure that this delegate will not be garbage collected. +#pragma warning restore IDE0052 public IntPtr FuncPtr { get; } diff --git a/src/ARMeilleure/Translation/Dominance.cs b/src/ARMeilleure/Translation/Dominance.cs index b9b961d15..e2185bd85 100644 --- a/src/ARMeilleure/Translation/Dominance.cs +++ b/src/ARMeilleure/Translation/Dominance.cs @@ -29,7 +29,7 @@ namespace ARMeilleure.Translation cfg.Entry.ImmediateDominator = cfg.Entry; - Debug.Assert(cfg.Entry == cfg.PostOrderBlocks[cfg.PostOrderBlocks.Length - 1]); + Debug.Assert(cfg.Entry == cfg.PostOrderBlocks[^1]); bool modified; @@ -92,4 +92,4 @@ namespace ARMeilleure.Translation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/EmitterContext.cs b/src/ARMeilleure/Translation/EmitterContext.cs index 8fcb4deec..88bfe1335 100644 --- a/src/ARMeilleure/Translation/EmitterContext.cs +++ b/src/ARMeilleure/Translation/EmitterContext.cs @@ -108,9 +108,9 @@ namespace ARMeilleure.Translation protected static OperandType GetOperandType(Type type) { - if (type == typeof(bool) || type == typeof(byte) || - type == typeof(char) || type == typeof(short) || - type == typeof(int) || type == typeof(sbyte) || + if (type == typeof(bool) || type == typeof(byte) || + type == typeof(char) || type == typeof(short) || + type == typeof(int) || type == typeof(sbyte) || type == typeof(ushort) || type == typeof(uint)) { return OperandType.I32; @@ -635,7 +635,7 @@ namespace ARMeilleure.Translation private void NewNextBlock() { - BasicBlock block = new BasicBlock(_irBlocks.Count); + BasicBlock block = new(_irBlocks.Count); _irBlocks.AddLast(block); diff --git a/src/ARMeilleure/Translation/GuestFunction.cs b/src/ARMeilleure/Translation/GuestFunction.cs index ac131a0d1..6414d6bd0 100644 --- a/src/ARMeilleure/Translation/GuestFunction.cs +++ b/src/ARMeilleure/Translation/GuestFunction.cs @@ -3,4 +3,4 @@ using System; namespace ARMeilleure.Translation { delegate ulong GuestFunction(IntPtr nativeContextPtr); -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/IntervalTree.cs b/src/ARMeilleure/Translation/IntervalTree.cs index 9af01bea0..afd89b930 100644 --- a/src/ARMeilleure/Translation/IntervalTree.cs +++ b/src/ARMeilleure/Translation/IntervalTree.cs @@ -6,15 +6,15 @@ namespace ARMeilleure.Translation /// /// An Augmented Interval Tree based off of the "TreeDictionary"'s Red-Black Tree. Allows fast overlap checking of ranges. /// - /// Key - /// Value - class IntervalTree where K : IComparable + /// Key + /// Value + class IntervalTree where TK : IComparable { private const int ArrayGrowthSize = 32; private const bool Black = true; private const bool Red = false; - private IntervalTreeNode _root = null; + private IntervalTreeNode _root = null; private int _count = 0; public int Count => _count; @@ -27,9 +27,9 @@ namespace ARMeilleure.Translation /// Key of the node value to get /// Value with the given /// True if the key is on the dictionary, false otherwise - public bool TryGet(K key, out V value) + public bool TryGet(TK key, out TV value) { - IntervalTreeNode node = GetNode(key); + IntervalTreeNode node = GetNode(key); if (node == null) { @@ -49,7 +49,7 @@ namespace ARMeilleure.Translation /// Overlaps array to place results in /// Index to start writing results into the array. Defaults to 0 /// Number of intervals found - public int Get(K start, K end, ref K[] overlaps, int overlapCount = 0) + public int Get(TK start, TK end, ref TK[] overlaps, int overlapCount = 0) { GetKeys(_root, start, end, ref overlaps, ref overlapCount); @@ -65,11 +65,11 @@ namespace ARMeilleure.Translation /// Optional factory used to create a new value if is already on the tree /// is null /// True if the value was added, false if the start key was already in the dictionary - public bool AddOrUpdate(K start, K end, V value, Func updateFactoryCallback) + public bool AddOrUpdate(TK start, TK end, TV value, Func updateFactoryCallback) { ArgumentNullException.ThrowIfNull(value); - return BSTInsert(start, end, value, updateFactoryCallback, out IntervalTreeNode node); + return BSTInsert(start, end, value, updateFactoryCallback, out _); } /// @@ -80,11 +80,11 @@ namespace ARMeilleure.Translation /// Value to add /// is null /// if is not yet on the tree, or the existing value otherwise - public V GetOrAdd(K start, K end, V value) + public TV GetOrAdd(TK start, TK end, TV value) { ArgumentNullException.ThrowIfNull(value); - BSTInsert(start, end, value, null, out IntervalTreeNode node); + BSTInsert(start, end, value, null, out IntervalTreeNode node); return node.Value; } @@ -93,7 +93,7 @@ namespace ARMeilleure.Translation /// /// Key of the node to remove /// Number of deleted values - public int Remove(K key) + public int Remove(TK key) { int removed = Delete(key); @@ -106,9 +106,9 @@ namespace ARMeilleure.Translation /// Adds all the nodes in the dictionary into . /// /// A list of all values sorted by Key Order - public List AsList() + public List AsList() { - List list = new List(); + List list = new(); AddToList(_root, list); @@ -124,7 +124,7 @@ namespace ARMeilleure.Translation /// /// The node to search for values within /// The list to add values to - private void AddToList(IntervalTreeNode node, List list) + private void AddToList(IntervalTreeNode node, List list) { if (node == null) { @@ -144,11 +144,11 @@ namespace ARMeilleure.Translation /// Key of the node to get /// is null /// Node reference in the tree - private IntervalTreeNode GetNode(K key) + private IntervalTreeNode GetNode(TK key) { ArgumentNullException.ThrowIfNull(key); - IntervalTreeNode node = _root; + IntervalTreeNode node = _root; while (node != null) { int cmp = key.CompareTo(node.Start); @@ -175,7 +175,7 @@ namespace ARMeilleure.Translation /// End of the range /// Overlaps array to place results in /// Overlaps count to update - private void GetKeys(IntervalTreeNode node, K start, K end, ref K[] overlaps, ref int overlapCount) + private void GetKeys(IntervalTreeNode node, TK start, TK end, ref TK[] overlaps, ref int overlapCount) { if (node == null || start.CompareTo(node.Max) >= 0) { @@ -206,10 +206,10 @@ namespace ARMeilleure.Translation /// This should only be called if the max increases - not for rebalancing or removals. /// /// The node to start propagating from - private void PropagateIncrease(IntervalTreeNode node) + private static void PropagateIncrease(IntervalTreeNode node) { - K max = node.Max; - IntervalTreeNode ptr = node; + TK max = node.Max; + IntervalTreeNode ptr = node; while ((ptr = ptr.Parent) != null) { @@ -229,13 +229,13 @@ namespace ARMeilleure.Translation /// This fully recalculates the max value from all children when there is potential for it to decrease. /// /// The node to start propagating from - private void PropagateFull(IntervalTreeNode node) + private static void PropagateFull(IntervalTreeNode node) { - IntervalTreeNode ptr = node; + IntervalTreeNode ptr = node; do { - K max = ptr.End; + TK max = ptr.End; if (ptr.Left != null && ptr.Left.Max.CompareTo(max) > 0) { @@ -263,10 +263,10 @@ namespace ARMeilleure.Translation /// Optional factory used to create a new value if is already on the tree /// Node that was inserted or modified /// True if was not yet on the tree, false otherwise - private bool BSTInsert(K start, K end, V value, Func updateFactoryCallback, out IntervalTreeNode outNode) + private bool BSTInsert(TK start, TK end, TV value, Func updateFactoryCallback, out IntervalTreeNode outNode) { - IntervalTreeNode parent = null; - IntervalTreeNode node = _root; + IntervalTreeNode parent = null; + IntervalTreeNode node = _root; while (node != null) { @@ -311,7 +311,7 @@ namespace ARMeilleure.Translation return false; } } - IntervalTreeNode newNode = new IntervalTreeNode(start, end, value, parent); + IntervalTreeNode newNode = new(start, end, value, parent); if (newNode.Parent == null) { _root = newNode; @@ -337,16 +337,16 @@ namespace ARMeilleure.Translation /// /// Key to search for /// Number of deleted values - private int Delete(K key) + private int Delete(TK key) { - IntervalTreeNode nodeToDelete = GetNode(key); + IntervalTreeNode nodeToDelete = GetNode(key); if (nodeToDelete == null) { return 0; } - IntervalTreeNode replacementNode; + IntervalTreeNode replacementNode; if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null) { @@ -357,7 +357,7 @@ namespace ARMeilleure.Translation replacementNode = PredecessorOf(nodeToDelete); } - IntervalTreeNode tmp = LeftOf(replacementNode) ?? RightOf(replacementNode); + IntervalTreeNode tmp = LeftOf(replacementNode) ?? RightOf(replacementNode); if (tmp != null) { @@ -400,9 +400,9 @@ namespace ARMeilleure.Translation /// /// Root Node /// Node with the maximum key in the tree of - private static IntervalTreeNode Maximum(IntervalTreeNode node) + private static IntervalTreeNode Maximum(IntervalTreeNode node) { - IntervalTreeNode tmp = node; + IntervalTreeNode tmp = node; while (tmp.Right != null) { tmp = tmp.Right; @@ -416,13 +416,13 @@ namespace ARMeilleure.Translation /// /// Node to find the predecessor of /// Predecessor of - private static IntervalTreeNode PredecessorOf(IntervalTreeNode node) + private static IntervalTreeNode PredecessorOf(IntervalTreeNode node) { if (node.Left != null) { return Maximum(node.Left); } - IntervalTreeNode parent = node.Parent; + IntervalTreeNode parent = node.Parent; while (parent != null && node == parent.Left) { node = parent; @@ -435,15 +435,15 @@ namespace ARMeilleure.Translation #region Private Methods (RBL) - private void RestoreBalanceAfterRemoval(IntervalTreeNode balanceNode) + private void RestoreBalanceAfterRemoval(IntervalTreeNode balanceNode) { - IntervalTreeNode ptr = balanceNode; + IntervalTreeNode ptr = balanceNode; while (ptr != _root && ColorOf(ptr) == Black) { if (ptr == LeftOf(ParentOf(ptr))) { - IntervalTreeNode sibling = RightOf(ParentOf(ptr)); + IntervalTreeNode sibling = RightOf(ParentOf(ptr)); if (ColorOf(sibling) == Red) { @@ -475,7 +475,7 @@ namespace ARMeilleure.Translation } else { - IntervalTreeNode sibling = LeftOf(ParentOf(ptr)); + IntervalTreeNode sibling = LeftOf(ParentOf(ptr)); if (ColorOf(sibling) == Red) { @@ -509,14 +509,14 @@ namespace ARMeilleure.Translation SetColor(ptr, Black); } - private void RestoreBalanceAfterInsertion(IntervalTreeNode balanceNode) + private void RestoreBalanceAfterInsertion(IntervalTreeNode balanceNode) { SetColor(balanceNode, Red); while (balanceNode != null && balanceNode != _root && ColorOf(ParentOf(balanceNode)) == Red) { if (ParentOf(balanceNode) == LeftOf(ParentOf(ParentOf(balanceNode)))) { - IntervalTreeNode sibling = RightOf(ParentOf(ParentOf(balanceNode))); + IntervalTreeNode sibling = RightOf(ParentOf(ParentOf(balanceNode))); if (ColorOf(sibling) == Red) { @@ -539,7 +539,7 @@ namespace ARMeilleure.Translation } else { - IntervalTreeNode sibling = LeftOf(ParentOf(ParentOf(balanceNode))); + IntervalTreeNode sibling = LeftOf(ParentOf(ParentOf(balanceNode))); if (ColorOf(sibling) == Red) { @@ -564,17 +564,17 @@ namespace ARMeilleure.Translation SetColor(_root, Black); } - private void RotateLeft(IntervalTreeNode node) + private void RotateLeft(IntervalTreeNode node) { if (node != null) { - IntervalTreeNode right = RightOf(node); + IntervalTreeNode right = RightOf(node); node.Right = LeftOf(right); if (node.Right != null) { node.Right.Parent = node; } - IntervalTreeNode nodeParent = ParentOf(node); + IntervalTreeNode nodeParent = ParentOf(node); right.Parent = nodeParent; if (nodeParent == null) { @@ -595,17 +595,17 @@ namespace ARMeilleure.Translation } } - private void RotateRight(IntervalTreeNode node) + private void RotateRight(IntervalTreeNode node) { if (node != null) { - IntervalTreeNode left = LeftOf(node); + IntervalTreeNode left = LeftOf(node); node.Left = RightOf(left); if (node.Left != null) { node.Left.Parent = node; } - IntervalTreeNode nodeParent = ParentOf(node); + IntervalTreeNode nodeParent = ParentOf(node); left.Parent = nodeParent; if (nodeParent == null) { @@ -637,7 +637,7 @@ namespace ARMeilleure.Translation /// /// Node /// The boolean color of , or black if null - private static bool ColorOf(IntervalTreeNode node) + private static bool ColorOf(IntervalTreeNode node) { return node == null || node.Color; } @@ -649,7 +649,7 @@ namespace ARMeilleure.Translation /// /// Node to set the color of /// Color (Boolean) - private static void SetColor(IntervalTreeNode node, bool color) + private static void SetColor(IntervalTreeNode node, bool color) { if (node != null) { @@ -662,7 +662,7 @@ namespace ARMeilleure.Translation /// /// Node to retrieve the left child from /// Left child of - private static IntervalTreeNode LeftOf(IntervalTreeNode node) + private static IntervalTreeNode LeftOf(IntervalTreeNode node) { return node?.Left; } @@ -672,7 +672,7 @@ namespace ARMeilleure.Translation /// /// Node to retrieve the right child from /// Right child of - private static IntervalTreeNode RightOf(IntervalTreeNode node) + private static IntervalTreeNode RightOf(IntervalTreeNode node) { return node?.Right; } @@ -682,14 +682,14 @@ namespace ARMeilleure.Translation /// /// Node to retrieve the parent from /// Parent of - private static IntervalTreeNode ParentOf(IntervalTreeNode node) + private static IntervalTreeNode ParentOf(IntervalTreeNode node) { return node?.Parent; } #endregion - public bool ContainsKey(K key) + public bool ContainsKey(TK key) { return GetNode(key) != null; } @@ -704,36 +704,36 @@ namespace ARMeilleure.Translation /// /// Represents a node in the IntervalTree which contains start and end keys of type K, and a value of generic type V. /// - /// Key type of the node - /// Value type of the node - class IntervalTreeNode + /// Key type of the node + /// Value type of the node + class IntervalTreeNode { public bool Color = true; - public IntervalTreeNode Left = null; - public IntervalTreeNode Right = null; - public IntervalTreeNode Parent = null; + public IntervalTreeNode Left = null; + public IntervalTreeNode Right = null; + public IntervalTreeNode Parent = null; /// /// The start of the range. /// - public K Start; + public TK Start; /// /// The end of the range. /// - public K End; + public TK End; /// /// The maximum end value of this node and all its children. /// - public K Max; + public TK Max; /// /// Value stored on this node. /// - public V Value; + public TV Value; - public IntervalTreeNode(K start, K end, V value, IntervalTreeNode parent) + public IntervalTreeNode(TK start, TK end, TV value, IntervalTreeNode parent) { Start = start; End = end; diff --git a/src/ARMeilleure/Translation/PTC/EncodingCache.cs b/src/ARMeilleure/Translation/PTC/EncodingCache.cs index 90d40c475..d9b38ace7 100644 --- a/src/ARMeilleure/Translation/PTC/EncodingCache.cs +++ b/src/ARMeilleure/Translation/PTC/EncodingCache.cs @@ -6,4 +6,4 @@ namespace ARMeilleure.Translation.PTC { public static readonly Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/PTC/IPtcLoadState.cs b/src/ARMeilleure/Translation/PTC/IPtcLoadState.cs index 1b11ac0b5..efff45a9f 100644 --- a/src/ARMeilleure/Translation/PTC/IPtcLoadState.cs +++ b/src/ARMeilleure/Translation/PTC/IPtcLoadState.cs @@ -7,4 +7,4 @@ namespace ARMeilleure.Translation.PTC event Action PtcStateChanged; void Continue(); } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/PTC/Ptc.cs b/src/ARMeilleure/Translation/PTC/Ptc.cs index ea4e715b5..ce653383e 100644 --- a/src/ARMeilleure/Translation/PTC/Ptc.cs +++ b/src/ARMeilleure/Translation/PTC/Ptc.cs @@ -17,20 +17,19 @@ using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; - using static ARMeilleure.Translation.PTC.PtcFormatter; namespace ARMeilleure.Translation.PTC { - using Arm64HardwareCapabilities = ARMeilleure.CodeGen.Arm64.HardwareCapabilities; - using X86HardwareCapabilities = ARMeilleure.CodeGen.X86.HardwareCapabilities; + using Arm64HardwareCapabilities = CodeGen.Arm64.HardwareCapabilities; + using X86HardwareCapabilities = CodeGen.X86.HardwareCapabilities; class Ptc : IPtcLoadState { private const string OuterHeaderMagicString = "PTCohd\0\0"; private const string InnerHeaderMagicString = "PTCihd\0\0"; - private const uint InternalVersion = 4661; //! To be incremented manually for each change to the ARMeilleure project. + private const uint InternalVersion = 5502; //! To be incremented manually for each change to the ARMeilleure project. private const string ActualDir = "0"; private const string BackupDir = "1"; @@ -187,8 +186,8 @@ namespace ARMeilleure.Translation.PTC string fileNameActual = $"{CachePathActual}.cache"; string fileNameBackup = $"{CachePathBackup}.cache"; - FileInfo fileInfoActual = new FileInfo(fileNameActual); - FileInfo fileInfoBackup = new FileInfo(fileNameBackup); + FileInfo fileInfoActual = new(fileNameActual); + FileInfo fileInfoBackup = new(fileNameBackup); if (fileInfoActual.Exists && fileInfoActual.Length != 0L) { @@ -275,104 +274,102 @@ namespace ARMeilleure.Translation.PTC { intPtr = Marshal.AllocHGlobal(new IntPtr(outerHeader.UncompressedStreamSize)); - using (UnmanagedMemoryStream stream = new((byte*)intPtr.ToPointer(), outerHeader.UncompressedStreamSize, outerHeader.UncompressedStreamSize, FileAccess.ReadWrite)) + using UnmanagedMemoryStream stream = new((byte*)intPtr.ToPointer(), outerHeader.UncompressedStreamSize, outerHeader.UncompressedStreamSize, FileAccess.ReadWrite); + try { - try - { - deflateStream.CopyTo(stream); - } - catch - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - Debug.Assert(stream.Position == stream.Length); - - stream.Seek(0L, SeekOrigin.Begin); - - InnerHeader innerHeader = DeserializeStructure(stream); - - if (!innerHeader.IsHeaderValid()) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - if (innerHeader.Magic != _innerHeaderMagic) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - ReadOnlySpan infosBytes = new(stream.PositionPointer, innerHeader.InfosLength); - stream.Seek(innerHeader.InfosLength, SeekOrigin.Current); - - Hash128 infosHash = XXHash128.ComputeHash(infosBytes); - - if (innerHeader.InfosHash != infosHash) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - ReadOnlySpan codesBytes = (int)innerHeader.CodesLength > 0 ? new(stream.PositionPointer, (int)innerHeader.CodesLength) : ReadOnlySpan.Empty; - stream.Seek(innerHeader.CodesLength, SeekOrigin.Current); - - Hash128 codesHash = XXHash128.ComputeHash(codesBytes); - - if (innerHeader.CodesHash != codesHash) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - ReadOnlySpan relocsBytes = new(stream.PositionPointer, innerHeader.RelocsLength); - stream.Seek(innerHeader.RelocsLength, SeekOrigin.Current); - - Hash128 relocsHash = XXHash128.ComputeHash(relocsBytes); - - if (innerHeader.RelocsHash != relocsHash) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - ReadOnlySpan unwindInfosBytes = new(stream.PositionPointer, innerHeader.UnwindInfosLength); - stream.Seek(innerHeader.UnwindInfosLength, SeekOrigin.Current); - - Hash128 unwindInfosHash = XXHash128.ComputeHash(unwindInfosBytes); - - if (innerHeader.UnwindInfosHash != unwindInfosHash) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - Debug.Assert(stream.Position == stream.Length); - - stream.Seek((long)Unsafe.SizeOf(), SeekOrigin.Begin); - - _infosStream.Write(infosBytes); - stream.Seek(innerHeader.InfosLength, SeekOrigin.Current); - - _codesList.ReadFrom(stream); - - _relocsStream.Write(relocsBytes); - stream.Seek(innerHeader.RelocsLength, SeekOrigin.Current); - - _unwindInfosStream.Write(unwindInfosBytes); - stream.Seek(innerHeader.UnwindInfosLength, SeekOrigin.Current); - - Debug.Assert(stream.Position == stream.Length); + deflateStream.CopyTo(stream); } + catch + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + Debug.Assert(stream.Position == stream.Length); + + stream.Seek(0L, SeekOrigin.Begin); + + InnerHeader innerHeader = DeserializeStructure(stream); + + if (!innerHeader.IsHeaderValid()) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + if (innerHeader.Magic != _innerHeaderMagic) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + ReadOnlySpan infosBytes = new(stream.PositionPointer, innerHeader.InfosLength); + stream.Seek(innerHeader.InfosLength, SeekOrigin.Current); + + Hash128 infosHash = XXHash128.ComputeHash(infosBytes); + + if (innerHeader.InfosHash != infosHash) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + ReadOnlySpan codesBytes = (int)innerHeader.CodesLength > 0 ? new(stream.PositionPointer, (int)innerHeader.CodesLength) : ReadOnlySpan.Empty; + stream.Seek(innerHeader.CodesLength, SeekOrigin.Current); + + Hash128 codesHash = XXHash128.ComputeHash(codesBytes); + + if (innerHeader.CodesHash != codesHash) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + ReadOnlySpan relocsBytes = new(stream.PositionPointer, innerHeader.RelocsLength); + stream.Seek(innerHeader.RelocsLength, SeekOrigin.Current); + + Hash128 relocsHash = XXHash128.ComputeHash(relocsBytes); + + if (innerHeader.RelocsHash != relocsHash) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + ReadOnlySpan unwindInfosBytes = new(stream.PositionPointer, innerHeader.UnwindInfosLength); + stream.Seek(innerHeader.UnwindInfosLength, SeekOrigin.Current); + + Hash128 unwindInfosHash = XXHash128.ComputeHash(unwindInfosBytes); + + if (innerHeader.UnwindInfosHash != unwindInfosHash) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + Debug.Assert(stream.Position == stream.Length); + + stream.Seek((long)Unsafe.SizeOf(), SeekOrigin.Begin); + + _infosStream.Write(infosBytes); + stream.Seek(innerHeader.InfosLength, SeekOrigin.Current); + + _codesList.ReadFrom(stream); + + _relocsStream.Write(relocsBytes); + stream.Seek(innerHeader.RelocsLength, SeekOrigin.Current); + + _unwindInfosStream.Write(unwindInfosBytes); + stream.Seek(innerHeader.UnwindInfosLength, SeekOrigin.Current); + + Debug.Assert(stream.Position == stream.Length); } finally { @@ -390,7 +387,7 @@ namespace ARMeilleure.Translation.PTC return true; } - private void InvalidateCompressedStream(FileStream compressedStream) + private static void InvalidateCompressedStream(FileStream compressedStream) { compressedStream.SetLength(0L); } @@ -404,7 +401,7 @@ namespace ARMeilleure.Translation.PTC string fileNameActual = $"{CachePathActual}.cache"; string fileNameBackup = $"{CachePathBackup}.cache"; - FileInfo fileInfoActual = new FileInfo(fileNameActual); + FileInfo fileInfoActual = new(fileNameActual); if (fileInfoActual.Exists && fileInfoActual.Length != 0L) { @@ -427,32 +424,34 @@ namespace ARMeilleure.Translation.PTC { int translatedFuncsCount; - InnerHeader innerHeader = new InnerHeader(); + InnerHeader innerHeader = new() + { + Magic = _innerHeaderMagic, - innerHeader.Magic = _innerHeaderMagic; + InfosLength = (int)_infosStream.Length, + CodesLength = _codesList.Length(), + RelocsLength = (int)_relocsStream.Length, + UnwindInfosLength = (int)_unwindInfosStream.Length, + }; - innerHeader.InfosLength = (int)_infosStream.Length; - innerHeader.CodesLength = _codesList.Length(); - innerHeader.RelocsLength = (int)_relocsStream.Length; - innerHeader.UnwindInfosLength = (int)_unwindInfosStream.Length; + OuterHeader outerHeader = new() + { + Magic = _outerHeaderMagic, - OuterHeader outerHeader = new OuterHeader(); + CacheFileVersion = InternalVersion, + Endianness = GetEndianness(), + FeatureInfo = GetFeatureInfo(), + MemoryManagerMode = GetMemoryManagerMode(), + OSPlatform = GetOSPlatform(), + Architecture = (uint)RuntimeInformation.ProcessArchitecture, - outerHeader.Magic = _outerHeaderMagic; - - outerHeader.CacheFileVersion = InternalVersion; - outerHeader.Endianness = GetEndianness(); - outerHeader.FeatureInfo = GetFeatureInfo(); - outerHeader.MemoryManagerMode = GetMemoryManagerMode(); - outerHeader.OSPlatform = GetOSPlatform(); - outerHeader.Architecture = (uint)RuntimeInformation.ProcessArchitecture; - - outerHeader.UncompressedStreamSize = + UncompressedStreamSize = (long)Unsafe.SizeOf() + innerHeader.InfosLength + innerHeader.CodesLength + innerHeader.RelocsLength + - innerHeader.UnwindInfosLength; + innerHeader.UnwindInfosLength, + }; outerHeader.SetHeaderHash(); @@ -462,58 +461,54 @@ namespace ARMeilleure.Translation.PTC { intPtr = Marshal.AllocHGlobal(new IntPtr(outerHeader.UncompressedStreamSize)); - using (UnmanagedMemoryStream stream = new((byte*)intPtr.ToPointer(), outerHeader.UncompressedStreamSize, outerHeader.UncompressedStreamSize, FileAccess.ReadWrite)) + using UnmanagedMemoryStream stream = new((byte*)intPtr.ToPointer(), outerHeader.UncompressedStreamSize, outerHeader.UncompressedStreamSize, FileAccess.ReadWrite); + stream.Seek((long)Unsafe.SizeOf(), SeekOrigin.Begin); + + ReadOnlySpan infosBytes = new(stream.PositionPointer, innerHeader.InfosLength); + _infosStream.WriteTo(stream); + + ReadOnlySpan codesBytes = (int)innerHeader.CodesLength > 0 ? new(stream.PositionPointer, (int)innerHeader.CodesLength) : ReadOnlySpan.Empty; + _codesList.WriteTo(stream); + + ReadOnlySpan relocsBytes = new(stream.PositionPointer, innerHeader.RelocsLength); + _relocsStream.WriteTo(stream); + + ReadOnlySpan unwindInfosBytes = new(stream.PositionPointer, innerHeader.UnwindInfosLength); + _unwindInfosStream.WriteTo(stream); + + Debug.Assert(stream.Position == stream.Length); + + innerHeader.InfosHash = XXHash128.ComputeHash(infosBytes); + innerHeader.CodesHash = XXHash128.ComputeHash(codesBytes); + innerHeader.RelocsHash = XXHash128.ComputeHash(relocsBytes); + innerHeader.UnwindInfosHash = XXHash128.ComputeHash(unwindInfosBytes); + + innerHeader.SetHeaderHash(); + + stream.Seek(0L, SeekOrigin.Begin); + SerializeStructure(stream, innerHeader); + + translatedFuncsCount = GetEntriesCount(); + + ResetCarriersIfNeeded(); + + using FileStream compressedStream = new(fileName, FileMode.OpenOrCreate); + using DeflateStream deflateStream = new(compressedStream, SaveCompressionLevel, true); + try { - stream.Seek((long)Unsafe.SizeOf(), SeekOrigin.Begin); - - ReadOnlySpan infosBytes = new(stream.PositionPointer, innerHeader.InfosLength); - _infosStream.WriteTo(stream); - - ReadOnlySpan codesBytes = (int)innerHeader.CodesLength > 0 ? new(stream.PositionPointer, (int)innerHeader.CodesLength) : ReadOnlySpan.Empty; - _codesList.WriteTo(stream); - - ReadOnlySpan relocsBytes = new(stream.PositionPointer, innerHeader.RelocsLength); - _relocsStream.WriteTo(stream); - - ReadOnlySpan unwindInfosBytes = new(stream.PositionPointer, innerHeader.UnwindInfosLength); - _unwindInfosStream.WriteTo(stream); - - Debug.Assert(stream.Position == stream.Length); - - innerHeader.InfosHash = XXHash128.ComputeHash(infosBytes); - innerHeader.CodesHash = XXHash128.ComputeHash(codesBytes); - innerHeader.RelocsHash = XXHash128.ComputeHash(relocsBytes); - innerHeader.UnwindInfosHash = XXHash128.ComputeHash(unwindInfosBytes); - - innerHeader.SetHeaderHash(); + SerializeStructure(compressedStream, outerHeader); stream.Seek(0L, SeekOrigin.Begin); - SerializeStructure(stream, innerHeader); + stream.CopyTo(deflateStream); + } + catch + { + compressedStream.Position = 0L; + } - translatedFuncsCount = GetEntriesCount(); - - ResetCarriersIfNeeded(); - - using (FileStream compressedStream = new(fileName, FileMode.OpenOrCreate)) - using (DeflateStream deflateStream = new(compressedStream, SaveCompressionLevel, true)) - { - try - { - SerializeStructure(compressedStream, outerHeader); - - stream.Seek(0L, SeekOrigin.Begin); - stream.CopyTo(deflateStream); - } - catch - { - compressedStream.Position = 0L; - } - - if (compressedStream.Position < compressedStream.Length) - { - compressedStream.SetLength(compressedStream.Position); - } - } + if (compressedStream.Position < compressedStream.Length) + { + compressedStream.SetLength(compressedStream.Position); } } finally @@ -647,7 +642,7 @@ namespace ARMeilleure.Translation.PTC return _codesList[index]; } - private RelocEntry[] GetRelocEntries(BinaryReader relocsReader, int relocEntriesCount) + private static RelocEntry[] GetRelocEntries(BinaryReader relocsReader, int relocEntriesCount) { RelocEntry[] relocEntries = new RelocEntry[relocEntriesCount]; @@ -663,7 +658,7 @@ namespace ARMeilleure.Translation.PTC return relocEntries; } - private void PatchCode(Translator translator, Span code, RelocEntry[] relocEntries, out Counter callCounter) + private static void PatchCode(Translator translator, Span code, RelocEntry[] relocEntries, out Counter callCounter) { callCounter = null; @@ -678,7 +673,10 @@ namespace ARMeilleure.Translation.PTC if (translator.FunctionTable.IsValid(guestAddress)) { - unsafe { imm = (IntPtr)Unsafe.AsPointer(ref translator.FunctionTable.GetValue(guestAddress)); } + unsafe + { + imm = (IntPtr)Unsafe.AsPointer(ref translator.FunctionTable.GetValue(guestAddress)); + } } } else if (symbol.Type == SymbolType.DelegateTable) @@ -696,12 +694,12 @@ namespace ARMeilleure.Translation.PTC } else if (symbol == CountTableSymbol) { - if (callCounter == null) - { - callCounter = new Counter(translator.CountTable); - } + callCounter ??= new Counter(translator.CountTable); - unsafe { imm = (IntPtr)Unsafe.AsPointer(ref callCounter.Value); } + unsafe + { + imm = (IntPtr)Unsafe.AsPointer(ref callCounter.Value); + } } else if (symbol == DispatchStubSymbol) { @@ -717,7 +715,7 @@ namespace ARMeilleure.Translation.PTC } } - private UnwindInfo ReadUnwindInfo(BinaryReader unwindInfosReader) + private static UnwindInfo ReadUnwindInfo(BinaryReader unwindInfosReader) { int pushEntriesLength = unwindInfosReader.ReadInt32(); @@ -738,7 +736,7 @@ namespace ARMeilleure.Translation.PTC return new UnwindInfo(pushEntries, prologueSize); } - private TranslatedFunction FastTranslate( + private static TranslatedFunction FastTranslate( byte[] code, Counter callCounter, ulong guestSize, @@ -809,13 +807,13 @@ namespace ARMeilleure.Translation.PTC PtcStateChanged?.Invoke(PtcLoadingState.Start, _translateCount, _translateTotalCount); - using AutoResetEvent progressReportEvent = new AutoResetEvent(false); + using AutoResetEvent progressReportEvent = new(false); - Thread progressReportThread = new Thread(ReportProgress) + Thread progressReportThread = new(ReportProgress) { Name = "Ptc.ProgressReporter", Priority = ThreadPriority.Lowest, - IsBackground = true + IsBackground = true, }; progressReportThread.Start(progressReportEvent); @@ -845,12 +843,14 @@ namespace ARMeilleure.Translation.PTC } } - List threads = new List(); + List threads = new(); for (int i = 0; i < degreeOfParallelism; i++) { - Thread thread = new Thread(TranslateFuncs); - thread.IsBackground = true; + Thread thread = new(TranslateFuncs) + { + IsBackground = true, + }; threads.Add(thread); } @@ -871,14 +871,16 @@ namespace ARMeilleure.Translation.PTC Logger.Info?.Print(LogClass.Ptc, $"{_translateCount} of {_translateTotalCount} functions translated | Thread count: {degreeOfParallelism} in {sw.Elapsed.TotalSeconds} s"); - Thread preSaveThread = new Thread(PreSave); - preSaveThread.IsBackground = true; + Thread preSaveThread = new(PreSave) + { + IsBackground = true, + }; preSaveThread.Start(); } private void ReportProgress(object state) { - const int refreshRate = 50; // ms. + const int RefreshRate = 50; // ms. AutoResetEvent endEvent = (AutoResetEvent)state; @@ -894,7 +896,7 @@ namespace ARMeilleure.Translation.PTC count = newCount; } } - while (!endEvent.WaitOne(refreshRate)); + while (!endEvent.WaitOne(RefreshRate)); } public static Hash128 ComputeHash(IMemoryManager memory, ulong address, ulong guestSize) @@ -910,15 +912,16 @@ namespace ARMeilleure.Translation.PTC RelocInfo relocInfo = compiledFunc.RelocInfo; UnwindInfo unwindInfo = compiledFunc.UnwindInfo; - InfoEntry infoEntry = new InfoEntry(); - - infoEntry.Address = address; - infoEntry.GuestSize = guestSize; - infoEntry.Hash = hash; - infoEntry.HighCq = highCq; - infoEntry.Stubbed = false; - infoEntry.CodeLength = code.Length; - infoEntry.RelocEntriesCount = relocInfo.Entries.Length; + InfoEntry infoEntry = new() + { + Address = address, + GuestSize = guestSize, + Hash = hash, + HighCq = highCq, + Stubbed = false, + CodeLength = code.Length, + RelocEntriesCount = relocInfo.Entries.Length, + }; SerializeStructure(_infosStream, infoEntry); @@ -996,10 +999,12 @@ namespace ARMeilleure.Translation.PTC { uint osPlatform = 0u; +#pragma warning disable IDE0055 // Disable formatting osPlatform |= (OperatingSystem.IsFreeBSD() ? 1u : 0u) << 0; osPlatform |= (OperatingSystem.IsLinux() ? 1u : 0u) << 1; osPlatform |= (OperatingSystem.IsMacOS() ? 1u : 0u) << 2; osPlatform |= (OperatingSystem.IsWindows() ? 1u : 0u) << 3; +#pragma warning restore IDE0055 return osPlatform; } @@ -1025,14 +1030,14 @@ namespace ARMeilleure.Translation.PTC { Span spanHeader = MemoryMarshal.CreateSpan(ref this, 1); - HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf() - Unsafe.SizeOf())); + HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader)[..(Unsafe.SizeOf() - Unsafe.SizeOf())]); } public bool IsHeaderValid() { Span spanHeader = MemoryMarshal.CreateSpan(ref this, 1); - return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf() - Unsafe.SizeOf())) == HeaderHash; + return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader)[..(Unsafe.SizeOf() - Unsafe.SizeOf())]) == HeaderHash; } } @@ -1060,14 +1065,14 @@ namespace ARMeilleure.Translation.PTC { Span spanHeader = MemoryMarshal.CreateSpan(ref this, 1); - HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf() - Unsafe.SizeOf())); + HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader)[..(Unsafe.SizeOf() - Unsafe.SizeOf())]); } public bool IsHeaderValid() { Span spanHeader = MemoryMarshal.CreateSpan(ref this, 1); - return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf() - Unsafe.SizeOf())) == HeaderHash; + return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader)[..(Unsafe.SizeOf() - Unsafe.SizeOf())]) == HeaderHash; } } diff --git a/src/ARMeilleure/Translation/PTC/PtcFormatter.cs b/src/ARMeilleure/Translation/PTC/PtcFormatter.cs index 2f7a9c21f..ddac31338 100644 --- a/src/ARMeilleure/Translation/PTC/PtcFormatter.cs +++ b/src/ARMeilleure/Translation/PTC/PtcFormatter.cs @@ -47,7 +47,7 @@ namespace ARMeilleure.Translation.PTC [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T DeserializeStructure(Stream stream) where T : struct { - T structure = default(T); + T structure = default; Span spanT = MemoryMarshal.CreateSpan(ref structure, 1); int bytesCount = stream.Read(MemoryMarshal.AsBytes(spanT)); @@ -176,4 +176,4 @@ namespace ARMeilleure.Translation.PTC } #endregion } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/PTC/PtcLoadingState.cs b/src/ARMeilleure/Translation/PTC/PtcLoadingState.cs index 526cf91fb..587be7939 100644 --- a/src/ARMeilleure/Translation/PTC/PtcLoadingState.cs +++ b/src/ARMeilleure/Translation/PTC/PtcLoadingState.cs @@ -4,6 +4,6 @@ namespace ARMeilleure.Translation.PTC { Start, Loading, - Loaded + Loaded, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/PTC/PtcProfiler.cs b/src/ARMeilleure/Translation/PTC/PtcProfiler.cs index 391e29c76..3a4bfcec6 100644 --- a/src/ARMeilleure/Translation/PTC/PtcProfiler.cs +++ b/src/ARMeilleure/Translation/PTC/PtcProfiler.cs @@ -12,7 +12,6 @@ using System.IO.Compression; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; - using static ARMeilleure.Translation.PTC.PtcFormatter; namespace ARMeilleure.Translation.PTC @@ -46,7 +45,7 @@ namespace ARMeilleure.Translation.PTC public bool Enabled { get; private set; } public ulong StaticCodeStart { get; set; } - public ulong StaticCodeSize { get; set; } + public ulong StaticCodeSize { get; set; } public PtcProfiler(Ptc ptc) { @@ -129,8 +128,8 @@ namespace ARMeilleure.Translation.PTC string fileNameActual = $"{_ptc.CachePathActual}.info"; string fileNameBackup = $"{_ptc.CachePathBackup}.info"; - FileInfo fileInfoActual = new FileInfo(fileNameActual); - FileInfo fileInfoBackup = new FileInfo(fileNameBackup); + FileInfo fileInfoActual = new(fileNameActual); + FileInfo fileInfoBackup = new(fileNameBackup); if (fileInfoActual.Exists && fileInfoActual.Length != 0L) { @@ -183,42 +182,40 @@ namespace ARMeilleure.Translation.PTC return false; } - using (MemoryStream stream = MemoryStreamManager.Shared.GetStream()) + using MemoryStream stream = MemoryStreamManager.Shared.GetStream(); + Debug.Assert(stream.Seek(0L, SeekOrigin.Begin) == 0L && stream.Length == 0L); + + try { - Debug.Assert(stream.Seek(0L, SeekOrigin.Begin) == 0L && stream.Length == 0L); - - try - { - deflateStream.CopyTo(stream); - } - catch - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - Debug.Assert(stream.Position == stream.Length); - - stream.Seek(0L, SeekOrigin.Begin); - - Hash128 expectedHash = DeserializeStructure(stream); - - Hash128 actualHash = XXHash128.ComputeHash(GetReadOnlySpan(stream)); - - if (actualHash != expectedHash) - { - InvalidateCompressedStream(compressedStream); - - return false; - } - - ProfiledFuncs = Deserialize(stream); - - Debug.Assert(stream.Position == stream.Length); - - _lastHash = actualHash; + deflateStream.CopyTo(stream); } + catch + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + Debug.Assert(stream.Position == stream.Length); + + stream.Seek(0L, SeekOrigin.Begin); + + Hash128 expectedHash = DeserializeStructure(stream); + + Hash128 actualHash = XXHash128.ComputeHash(GetReadOnlySpan(stream)); + + if (actualHash != expectedHash) + { + InvalidateCompressedStream(compressedStream); + + return false; + } + + ProfiledFuncs = Deserialize(stream); + + Debug.Assert(stream.Position == stream.Length); + + _lastHash = actualHash; } long fileSize = new FileInfo(fileName).Length; @@ -233,12 +230,12 @@ namespace ARMeilleure.Translation.PTC return DeserializeDictionary(stream, (stream) => DeserializeStructure(stream)); } - private ReadOnlySpan GetReadOnlySpan(MemoryStream memoryStream) + private static ReadOnlySpan GetReadOnlySpan(MemoryStream memoryStream) { return new(memoryStream.GetBuffer(), (int)memoryStream.Position, (int)memoryStream.Length - (int)memoryStream.Position); } - private void InvalidateCompressedStream(FileStream compressedStream) + private static void InvalidateCompressedStream(FileStream compressedStream) { compressedStream.SetLength(0L); } @@ -250,7 +247,7 @@ namespace ARMeilleure.Translation.PTC string fileNameActual = $"{_ptc.CachePathActual}.info"; string fileNameBackup = $"{_ptc.CachePathBackup}.info"; - FileInfo fileInfoActual = new FileInfo(fileNameActual); + FileInfo fileInfoActual = new(fileNameActual); if (fileInfoActual.Exists && fileInfoActual.Length != 0L) { @@ -266,12 +263,13 @@ namespace ARMeilleure.Translation.PTC { int profiledFuncsCount; - OuterHeader outerHeader = new OuterHeader(); + OuterHeader outerHeader = new() + { + Magic = _outerHeaderMagic, - outerHeader.Magic = _outerHeaderMagic; - - outerHeader.InfoFileVersion = InternalVersion; - outerHeader.Endianness = Ptc.GetEndianness(); + InfoFileVersion = InternalVersion, + Endianness = Ptc.GetEndianness(), + }; outerHeader.SetHeaderHash(); @@ -301,28 +299,26 @@ namespace ARMeilleure.Translation.PTC return; } - using (FileStream compressedStream = new(fileName, FileMode.OpenOrCreate)) - using (DeflateStream deflateStream = new(compressedStream, SaveCompressionLevel, true)) + using FileStream compressedStream = new(fileName, FileMode.OpenOrCreate); + using DeflateStream deflateStream = new(compressedStream, SaveCompressionLevel, true); + try { - try - { - SerializeStructure(compressedStream, outerHeader); + SerializeStructure(compressedStream, outerHeader); - stream.WriteTo(deflateStream); + stream.WriteTo(deflateStream); - _lastHash = hash; - } - catch - { - compressedStream.Position = 0L; + _lastHash = hash; + } + catch + { + compressedStream.Position = 0L; - _lastHash = default; - } + _lastHash = default; + } - if (compressedStream.Position < compressedStream.Length) - { - compressedStream.SetLength(compressedStream.Position); - } + if (compressedStream.Position < compressedStream.Length) + { + compressedStream.SetLength(compressedStream.Position); } } @@ -334,7 +330,7 @@ namespace ARMeilleure.Translation.PTC } } - private void Serialize(Stream stream, Dictionary profiledFuncs) + private static void Serialize(Stream stream, Dictionary profiledFuncs) { SerializeDictionary(stream, profiledFuncs, (stream, structure) => SerializeStructure(stream, structure)); } @@ -354,14 +350,14 @@ namespace ARMeilleure.Translation.PTC { Span spanHeader = MemoryMarshal.CreateSpan(ref this, 1); - HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf() - Unsafe.SizeOf())); + HeaderHash = XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader)[..(Unsafe.SizeOf() - Unsafe.SizeOf())]); } public bool IsHeaderValid() { Span spanHeader = MemoryMarshal.CreateSpan(ref this, 1); - return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader).Slice(0, Unsafe.SizeOf() - Unsafe.SizeOf())) == HeaderHash; + return XXHash128.ComputeHash(MemoryMarshal.AsBytes(spanHeader)[..(Unsafe.SizeOf() - Unsafe.SizeOf())]) == HeaderHash; } } @@ -418,4 +414,4 @@ namespace ARMeilleure.Translation.PTC } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/PTC/PtcState.cs b/src/ARMeilleure/Translation/PTC/PtcState.cs index ca4f41080..f6692e870 100644 --- a/src/ARMeilleure/Translation/PTC/PtcState.cs +++ b/src/ARMeilleure/Translation/PTC/PtcState.cs @@ -5,6 +5,6 @@ namespace ARMeilleure.Translation.PTC Enabled, Continuing, Closing, - Disabled + Disabled, } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/RegisterToLocal.cs b/src/ARMeilleure/Translation/RegisterToLocal.cs index abb9b373c..91372eb00 100644 --- a/src/ARMeilleure/Translation/RegisterToLocal.cs +++ b/src/ARMeilleure/Translation/RegisterToLocal.cs @@ -9,7 +9,7 @@ namespace ARMeilleure.Translation { public static void Rename(ControlFlowGraph cfg) { - Dictionary registerToLocalMap = new Dictionary(); + Dictionary registerToLocalMap = new(); Operand GetLocal(Operand op) { @@ -49,4 +49,4 @@ namespace ARMeilleure.Translation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/RegisterUsage.cs b/src/ARMeilleure/Translation/RegisterUsage.cs index 3ec0a7b4f..c8c250626 100644 --- a/src/ARMeilleure/Translation/RegisterUsage.cs +++ b/src/ARMeilleure/Translation/RegisterUsage.cs @@ -12,7 +12,7 @@ namespace ARMeilleure.Translation static class RegisterUsage { private const int RegsCount = 32; - private const int RegsMask = RegsCount - 1; + private const int RegsMask = RegsCount - 1; private readonly struct RegisterMask : IEquatable { @@ -90,7 +90,7 @@ namespace ARMeilleure.Translation public static void RunPass(ControlFlowGraph cfg, ExecutionMode mode) { // Compute local register inputs and outputs used inside blocks. - RegisterMask[] localInputs = new RegisterMask[cfg.Blocks.Count]; + RegisterMask[] localInputs = new RegisterMask[cfg.Blocks.Count]; RegisterMask[] localOutputs = new RegisterMask[cfg.Blocks.Count]; for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext) @@ -119,7 +119,7 @@ namespace ARMeilleure.Translation // Compute global register inputs and outputs used across blocks. RegisterMask[] globalCmnOutputs = new RegisterMask[cfg.Blocks.Count]; - RegisterMask[] globalInputs = new RegisterMask[cfg.Blocks.Count]; + RegisterMask[] globalInputs = new RegisterMask[cfg.Blocks.Count]; RegisterMask[] globalOutputs = new RegisterMask[cfg.Blocks.Count]; bool modified; @@ -286,10 +286,12 @@ namespace ARMeilleure.Translation switch (register.Type) { +#pragma warning disable IDE0055 // Disable formatting case RegisterType.Flag: intMask = (1L << RegsCount) << register.Index; break; case RegisterType.Integer: intMask = 1L << register.Index; break; case RegisterType.FpFlag: vecMask = (1L << RegsCount) << register.Index; break; case RegisterType.Vector: vecMask = 1L << register.Index; break; +#pragma warning restore IDE0055 } return new RegisterMask(intMask, vecMask); @@ -373,15 +375,14 @@ namespace ARMeilleure.Translation private static OperandType GetOperandType(RegisterType type, ExecutionMode mode) { - switch (type) + return type switch { - case RegisterType.Flag: return OperandType.I32; - case RegisterType.FpFlag: return OperandType.I32; - case RegisterType.Integer: return (mode == ExecutionMode.Aarch64) ? OperandType.I64 : OperandType.I32; - case RegisterType.Vector: return OperandType.V128; - } - - throw new ArgumentException($"Invalid register type \"{type}\"."); + RegisterType.Flag => OperandType.I32, + RegisterType.FpFlag => OperandType.I32, + RegisterType.Integer => (mode == ExecutionMode.Aarch64) ? OperandType.I64 : OperandType.I32, + RegisterType.Vector => OperandType.V128, + _ => throw new ArgumentException($"Invalid register type \"{type}\"."), + }; } private static bool EndsWithReturn(BasicBlock block) @@ -391,4 +392,4 @@ namespace ARMeilleure.Translation return last != default && last.Instruction == Instruction.Return; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/SsaConstruction.cs b/src/ARMeilleure/Translation/SsaConstruction.cs index 2b6efc113..cddcfcd4f 100644 --- a/src/ARMeilleure/Translation/SsaConstruction.cs +++ b/src/ARMeilleure/Translation/SsaConstruction.cs @@ -180,7 +180,7 @@ namespace ARMeilleure.Translation } previous = current; - current = current.ImmediateDominator; + current = current.ImmediateDominator; } while (previous != current); @@ -286,4 +286,4 @@ namespace ARMeilleure.Translation return key; } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/SsaDeconstruction.cs b/src/ARMeilleure/Translation/SsaDeconstruction.cs index cd6bcca1f..68af54e5d 100644 --- a/src/ARMeilleure/Translation/SsaDeconstruction.cs +++ b/src/ARMeilleure/Translation/SsaDeconstruction.cs @@ -45,4 +45,4 @@ namespace ARMeilleure.Translation } } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/TranslatedFunction.cs b/src/ARMeilleure/Translation/TranslatedFunction.cs index f007883ef..1446c254a 100644 --- a/src/ARMeilleure/Translation/TranslatedFunction.cs +++ b/src/ARMeilleure/Translation/TranslatedFunction.cs @@ -31,4 +31,4 @@ namespace ARMeilleure.Translation return dispatcher(context.NativeContextPtr, (ulong)FuncPointer); } } -} \ No newline at end of file +} diff --git a/src/ARMeilleure/Translation/Translator.cs b/src/ARMeilleure/Translation/Translator.cs index 234be2ac7..dc18038ba 100644 --- a/src/ARMeilleure/Translation/Translator.cs +++ b/src/ARMeilleure/Translation/Translator.cs @@ -22,24 +22,24 @@ namespace ARMeilleure.Translation { public class Translator { - private static readonly AddressTable.Level[] Levels64Bit = + private static readonly AddressTable.Level[] _levels64Bit = new AddressTable.Level[] { new(31, 17), new(23, 8), new(15, 8), new( 7, 8), - new( 2, 5) + new( 2, 5), }; - private static readonly AddressTable.Level[] Levels32Bit = + private static readonly AddressTable.Level[] _levels32Bit = new AddressTable.Level[] { new(31, 17), new(23, 8), new(15, 8), new( 7, 8), - new( 1, 6) + new( 1, 6), }; private readonly IJitMemoryAllocator _allocator; @@ -75,7 +75,7 @@ namespace ARMeilleure.Translation CountTable = new EntryTable(); Functions = new TranslatorCache(); - FunctionTable = new AddressTable(for64Bits ? Levels64Bit : Levels32Bit); + FunctionTable = new AddressTable(for64Bits ? _levels64Bit : _levels32Bit); Stubs = new TranslatorStubs(this); FunctionTable.Fill = (ulong)Stubs.SlowDispatchStub; @@ -126,7 +126,7 @@ namespace ARMeilleure.Translation // TODO: Use physical cores rather than logical. This only really makes sense for processors with // hyperthreading. Requires OS specific code. int unboundedThreadCount = Math.Max(1, (Environment.ProcessorCount - 6) / 3); - int threadCount = Math.Min(4, unboundedThreadCount); + int threadCount = Math.Min(4, unboundedThreadCount); Thread[] backgroundTranslationThreads = new Thread[threadCount]; @@ -134,10 +134,10 @@ namespace ARMeilleure.Translation { bool last = i != 0 && i == unboundedThreadCount - 1; - backgroundTranslationThreads[i] = new Thread(BackgroundTranslate) + backgroundTranslationThreads[i] = new(BackgroundTranslate) { Name = "CPU.BackgroundTranslatorThread." + i, - Priority = last ? ThreadPriority.Lowest : ThreadPriority.Normal + Priority = last ? ThreadPriority.Lowest : ThreadPriority.Normal, }; backgroundTranslationThreads[i].Start(); diff --git a/src/ARMeilleure/Translation/TranslatorStubs.cs b/src/ARMeilleure/Translation/TranslatorStubs.cs index 69648df44..eceb1b742 100644 --- a/src/ARMeilleure/Translation/TranslatorStubs.cs +++ b/src/ARMeilleure/Translation/TranslatorStubs.cs @@ -224,7 +224,7 @@ namespace ARMeilleure.Translation /// Emitter context for the method /// Pointer to the native context /// True if entering guest code, false otherwise - private void EmitSyncFpContext(EmitterContext context, Operand nativeContext, bool enter) + private static void EmitSyncFpContext(EmitterContext context, Operand nativeContext, bool enter) { if (enter) { diff --git a/src/ARMeilleure/Translation/TranslatorTestMethods.cs b/src/ARMeilleure/Translation/TranslatorTestMethods.cs index ab96019a6..35cd8dc56 100644 --- a/src/ARMeilleure/Translation/TranslatorTestMethods.cs +++ b/src/ARMeilleure/Translation/TranslatorTestMethods.cs @@ -1,7 +1,6 @@ using ARMeilleure.CodeGen.X86; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; -using ARMeilleure.Translation; using System; using System.Runtime.InteropServices; using static ARMeilleure.IntermediateRepresentation.Operand.Factory; @@ -62,7 +61,7 @@ namespace ARMeilleure.Translation public static FpFlagsPInvokeTest GenerateFpFlagsPInvokeTest() { - EmitterContext context = new EmitterContext(); + EmitterContext context = new(); Operand methodAddress = context.Copy(context.LoadArgument(OperandType.I64, 0)); @@ -110,7 +109,7 @@ namespace ARMeilleure.Translation context.MarkLabel(correct2Label); - // Call a managed method. This method should not change Fz state. + // Call a managed method. This method should not change Fz state. context.Call(methodAddress, OperandType.None); diff --git a/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs b/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs index 0c793f248..86a2efa40 100644 --- a/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceDriver.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Backends.OpenAL private readonly ManualResetEvent _pauseEvent; private readonly ConcurrentDictionary _sessions; private bool _stillRunning; - private Thread _updaterThread; + private readonly Thread _updaterThread; public OpenALHardwareDeviceDriver() { @@ -31,7 +31,7 @@ namespace Ryujinx.Audio.Backends.OpenAL _stillRunning = true; _updaterThread = new Thread(Update) { - Name = "HardwareDeviceDriver.OpenAL" + Name = "HardwareDeviceDriver.OpenAL", }; _updaterThread.Start(); @@ -73,7 +73,7 @@ namespace Ryujinx.Audio.Backends.OpenAL throw new ArgumentException($"{channelCount}"); } - OpenALHardwareDeviceSession session = new OpenALHardwareDeviceSession(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); + OpenALHardwareDeviceSession session = new(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); _sessions.TryAdd(session, 0); @@ -123,6 +123,7 @@ namespace Ryujinx.Audio.Backends.OpenAL public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } diff --git a/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceSession.cs b/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceSession.cs index ac3319e0d..ee177c311 100644 --- a/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceSession.cs +++ b/src/Ryujinx.Audio.Backends.OpenAL/OpenALHardwareDeviceSession.cs @@ -10,14 +10,14 @@ namespace Ryujinx.Audio.Backends.OpenAL { class OpenALHardwareDeviceSession : HardwareDeviceSessionOutputBase { - private OpenALHardwareDeviceDriver _driver; - private int _sourceId; - private ALFormat _targetFormat; + private readonly OpenALHardwareDeviceDriver _driver; + private readonly int _sourceId; + private readonly ALFormat _targetFormat; private bool _isActive; - private Queue _queuedBuffers; + private readonly Queue _queuedBuffers; private ulong _playedSampleCount; - private object _lock = new object(); + private readonly object _lock = new(); public OpenALHardwareDeviceSession(OpenALHardwareDeviceDriver driver, IVirtualMemoryManager memoryManager, SampleFormat requestedSampleFormat, uint requestedSampleRate, uint requestedChannelCount, float requestedVolume) : base(memoryManager, requestedSampleFormat, requestedSampleRate, requestedChannelCount) { @@ -32,23 +32,17 @@ namespace Ryujinx.Audio.Backends.OpenAL private ALFormat GetALFormat() { - switch (RequestedSampleFormat) + return RequestedSampleFormat switch { - case SampleFormat.PcmInt16: - switch (RequestedChannelCount) - { - case 1: - return ALFormat.Mono16; - case 2: - return ALFormat.Stereo16; - case 6: - return ALFormat.Multi51Chn16Ext; - default: - throw new NotImplementedException($"Unsupported channel config {RequestedChannelCount}"); - } - default: - throw new NotImplementedException($"Unsupported sample format {RequestedSampleFormat}"); - } + SampleFormat.PcmInt16 => RequestedChannelCount switch + { + 1 => ALFormat.Mono16, + 2 => ALFormat.Stereo16, + 6 => ALFormat.Multi51Chn16Ext, + _ => throw new NotImplementedException($"Unsupported channel config {RequestedChannelCount}"), + }, + _ => throw new NotImplementedException($"Unsupported sample format {RequestedSampleFormat}"), + }; } public override void PrepareToClose() { } @@ -69,11 +63,11 @@ namespace Ryujinx.Audio.Backends.OpenAL { lock (_lock) { - OpenALAudioBuffer driverBuffer = new OpenALAudioBuffer + OpenALAudioBuffer driverBuffer = new() { DriverIdentifier = buffer.DataPointer, BufferId = AL.GenBuffer(), - SampleCount = GetSampleCount(buffer) + SampleCount = GetSampleCount(buffer), }; AL.BufferData(driverBuffer.BufferId, _targetFormat, buffer.Data, (int)RequestedSampleRate); diff --git a/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs b/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs index 7bfff5f9b..f1de42b01 100644 --- a/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceDriver.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Threading; - using static Ryujinx.Audio.Integration.IHardwareDeviceDriver; using static SDL2.SDL; @@ -19,12 +18,14 @@ namespace Ryujinx.Audio.Backends.SDL2 private readonly ManualResetEvent _pauseEvent; private readonly ConcurrentDictionary _sessions; - private bool _supportSurroundConfiguration; + private readonly bool _supportSurroundConfiguration; // TODO: Add this to SDL2-CS // NOTE: We use a DllImport here because of marshaling issue for spec. +#pragma warning disable SYSLIB1054 [DllImport("SDL2")] private static extern int SDL_GetDefaultAudioInfo(IntPtr name, out SDL_AudioSpec spec, int isCapture); +#pragma warning restore SYSLIB1054 public SDL2HardwareDeviceDriver() { @@ -90,7 +91,7 @@ namespace Ryujinx.Audio.Backends.SDL2 throw new NotImplementedException("Input direction is currently not implemented on SDL2 backend!"); } - SDL2HardwareDeviceSession session = new SDL2HardwareDeviceSession(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); + SDL2HardwareDeviceSession session = new(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); _sessions.TryAdd(session, 0); @@ -109,7 +110,7 @@ namespace Ryujinx.Audio.Backends.SDL2 channels = (byte)requestedChannelCount, format = GetSDL2Format(requestedSampleFormat), freq = (int)requestedSampleRate, - samples = (ushort)sampleCount + samples = (ushort)sampleCount, }; } @@ -135,8 +136,7 @@ namespace Ryujinx.Audio.Backends.SDL2 if (device == 0) { - Logger.Error?.Print(LogClass.Application, - $"SDL2 open audio device initialization failed with error \"{SDL_GetError()}\""); + Logger.Error?.Print(LogClass.Application, $"SDL2 open audio device initialization failed with error \"{SDL_GetError()}\""); return 0; } @@ -156,6 +156,7 @@ namespace Ryujinx.Audio.Backends.SDL2 public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } diff --git a/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceSession.cs b/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceSession.cs index 14310b934..0bd73f3c7 100644 --- a/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceSession.cs +++ b/src/Ryujinx.Audio.Backends.SDL2/SDL2HardwareDeviceSession.cs @@ -12,19 +12,19 @@ namespace Ryujinx.Audio.Backends.SDL2 { class SDL2HardwareDeviceSession : HardwareDeviceSessionOutputBase { - private SDL2HardwareDeviceDriver _driver; - private ConcurrentQueue _queuedBuffers; - private DynamicRingBuffer _ringBuffer; + private readonly SDL2HardwareDeviceDriver _driver; + private readonly ConcurrentQueue _queuedBuffers; + private readonly DynamicRingBuffer _ringBuffer; private ulong _playedSampleCount; - private ManualResetEvent _updateRequiredEvent; + private readonly ManualResetEvent _updateRequiredEvent; private uint _outputStream; private bool _hasSetupError; - private SDL_AudioCallback _callbackDelegate; - private int _bytesPerFrame; + private readonly SDL_AudioCallback _callbackDelegate; + private readonly int _bytesPerFrame; private uint _sampleCount; private bool _started; private float _volume; - private ushort _nativeSampleFormat; + private readonly ushort _nativeSampleFormat; public SDL2HardwareDeviceSession(SDL2HardwareDeviceDriver driver, IVirtualMemoryManager memoryManager, SampleFormat requestedSampleFormat, uint requestedSampleRate, uint requestedChannelCount, float requestedVolume) : base(memoryManager, requestedSampleFormat, requestedSampleRate, requestedChannelCount) { @@ -72,7 +72,7 @@ namespace Ryujinx.Audio.Backends.SDL2 private unsafe void Update(IntPtr userdata, IntPtr stream, int streamLength) { - Span streamSpan = new Span((void*)stream, streamLength); + Span streamSpan = new((void*)stream, streamLength); int maxFrameCount = (int)GetSampleCount(streamLength); int bufferedFrames = _ringBuffer.Length / _bytesPerFrame; @@ -82,7 +82,7 @@ namespace Ryujinx.Audio.Backends.SDL2 if (frameCount == 0) { // SDL2 left the responsibility to the user to clear the buffer. - streamSpan.Fill(0); + streamSpan.Clear(); return; } @@ -96,7 +96,7 @@ namespace Ryujinx.Audio.Backends.SDL2 IntPtr pStreamSrc = (IntPtr)p; // Zero the dest buffer - streamSpan.Fill(0); + streamSpan.Clear(); // Apply volume to written data SDL_MixAudioFormat(stream, pStreamSrc, _nativeSampleFormat, (uint)samples.Length, (int)(_volume * SDL_MIX_MAXVOLUME)); @@ -151,7 +151,7 @@ namespace Ryujinx.Audio.Backends.SDL2 if (_outputStream != 0) { - SDL2AudioBuffer driverBuffer = new SDL2AudioBuffer(buffer.DataPointer, GetSampleCount(buffer)); + SDL2AudioBuffer driverBuffer = new(buffer.DataPointer, GetSampleCount(buffer)); _ringBuffer.Write(buffer.Data, 0, buffer.Data.Length); diff --git a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIo.cs b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIo.cs index 9c3e686df..31af3e9d3 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIo.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIo.cs @@ -10,19 +10,19 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native private const string LibraryName = "libsoundio"; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public unsafe delegate void OnDeviceChangeNativeDelegate(IntPtr ctx); + public delegate void OnDeviceChangeNativeDelegate(IntPtr ctx); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public unsafe delegate void OnBackendDisconnectedDelegate(IntPtr ctx, SoundIoError err); + public delegate void OnBackendDisconnectedDelegate(IntPtr ctx, SoundIoError err); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public unsafe delegate void OnEventsSignalDelegate(IntPtr ctx); + public delegate void OnEventsSignalDelegate(IntPtr ctx); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public unsafe delegate void EmitRtPrioWarningDelegate(); + public delegate void EmitRtPrioWarningDelegate(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public unsafe delegate void JackCallbackDelegate(IntPtr msg); + public delegate void JackCallbackDelegate(IntPtr msg); [StructLayout(LayoutKind.Sequential)] public struct SoundIoStruct @@ -110,69 +110,69 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native } [LibraryImport(LibraryName)] - public static partial IntPtr soundio_create(); + internal static partial IntPtr soundio_create(); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_connect(IntPtr ctx); + internal static partial SoundIoError soundio_connect(IntPtr ctx); [LibraryImport(LibraryName)] - public static partial void soundio_disconnect(IntPtr ctx); + internal static partial void soundio_disconnect(IntPtr ctx); [LibraryImport(LibraryName)] - public static partial void soundio_flush_events(IntPtr ctx); + internal static partial void soundio_flush_events(IntPtr ctx); [LibraryImport(LibraryName)] - public static partial int soundio_output_device_count(IntPtr ctx); + internal static partial int soundio_output_device_count(IntPtr ctx); [LibraryImport(LibraryName)] - public static partial int soundio_default_output_device_index(IntPtr ctx); + internal static partial int soundio_default_output_device_index(IntPtr ctx); [LibraryImport(LibraryName)] - public static partial IntPtr soundio_get_output_device(IntPtr ctx, int index); + internal static partial IntPtr soundio_get_output_device(IntPtr ctx, int index); [LibraryImport(LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool soundio_device_supports_format(IntPtr devCtx, SoundIoFormat format); + internal static partial bool soundio_device_supports_format(IntPtr devCtx, SoundIoFormat format); [LibraryImport(LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool soundio_device_supports_layout(IntPtr devCtx, IntPtr layout); + internal static partial bool soundio_device_supports_layout(IntPtr devCtx, IntPtr layout); [LibraryImport(LibraryName)] [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool soundio_device_supports_sample_rate(IntPtr devCtx, int sampleRate); + internal static partial bool soundio_device_supports_sample_rate(IntPtr devCtx, int sampleRate); [LibraryImport(LibraryName)] - public static partial IntPtr soundio_outstream_create(IntPtr devCtx); + internal static partial IntPtr soundio_outstream_create(IntPtr devCtx); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_outstream_open(IntPtr outStreamCtx); + internal static partial SoundIoError soundio_outstream_open(IntPtr outStreamCtx); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_outstream_start(IntPtr outStreamCtx); + internal static partial SoundIoError soundio_outstream_start(IntPtr outStreamCtx); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_outstream_begin_write(IntPtr outStreamCtx, IntPtr areas, IntPtr frameCount); + internal static partial SoundIoError soundio_outstream_begin_write(IntPtr outStreamCtx, IntPtr areas, IntPtr frameCount); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_outstream_end_write(IntPtr outStreamCtx); + internal static partial SoundIoError soundio_outstream_end_write(IntPtr outStreamCtx); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_outstream_pause(IntPtr devCtx, [MarshalAs(UnmanagedType.Bool)] bool pause); + internal static partial SoundIoError soundio_outstream_pause(IntPtr devCtx, [MarshalAs(UnmanagedType.Bool)] bool pause); [LibraryImport(LibraryName)] - public static partial SoundIoError soundio_outstream_set_volume(IntPtr devCtx, double volume); + internal static partial SoundIoError soundio_outstream_set_volume(IntPtr devCtx, double volume); [LibraryImport(LibraryName)] - public static partial void soundio_outstream_destroy(IntPtr streamCtx); + internal static partial void soundio_outstream_destroy(IntPtr streamCtx); [LibraryImport(LibraryName)] - public static partial void soundio_destroy(IntPtr ctx); + internal static partial void soundio_destroy(IntPtr ctx); [LibraryImport(LibraryName)] - public static partial IntPtr soundio_channel_layout_get_default(int channelCount); + internal static partial IntPtr soundio_channel_layout_get_default(int channelCount); [LibraryImport(LibraryName)] - public static partial IntPtr soundio_strerror(SoundIoError err); + internal static partial IntPtr soundio_strerror(SoundIoError err); } } diff --git a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoBackend.cs b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoBackend.cs index 92f8ea375..7094b7d5b 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoBackend.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoBackend.cs @@ -1,6 +1,6 @@ namespace Ryujinx.Audio.Backends.SoundIo.Native { - public enum SoundIoBackend : int + public enum SoundIoBackend { None = 0, Jack = 1, @@ -8,6 +8,6 @@ Alsa = 3, CoreAudio = 4, Wasapi = 5, - Dummy = 6 + Dummy = 6, } } diff --git a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoContext.cs b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoContext.cs index 3744c2e64..afa86befa 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoContext.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoContext.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; diff --git a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoDeviceAim.cs b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoDeviceAim.cs index a0689d6d6..a1943810d 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoDeviceAim.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/Native/SoundIoDeviceAim.cs @@ -3,6 +3,6 @@ public enum SoundIoDeviceAim { SoundIoDeviceAimInput = 0, - SoundIoDeviceAimOutput = 1 + SoundIoDeviceAimOutput = 1, } } diff --git a/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceDriver.cs b/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceDriver.cs index 02da27769..9dac0992c 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceDriver.cs @@ -141,7 +141,7 @@ namespace Ryujinx.Audio.Backends.SoundIo throw new NotImplementedException("Input direction is currently not implemented on SoundIO backend!"); } - SoundIoHardwareDeviceSession session = new SoundIoHardwareDeviceSession(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); + SoundIoHardwareDeviceSession session = new(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); _sessions.TryAdd(session, 0); @@ -162,7 +162,7 @@ namespace Ryujinx.Audio.Backends.SoundIo SampleFormat.PcmInt24 => SoundIoFormat.S24LE, SampleFormat.PcmInt32 => SoundIoFormat.S32LE, SampleFormat.PcmFloat => SoundIoFormat.Float32LE, - _ => throw new ArgumentException ($"Unsupported sample format {format}"), + _ => throw new ArgumentException($"Unsupported sample format {format}"), }; } @@ -202,6 +202,8 @@ namespace Ryujinx.Audio.Backends.SoundIo public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); diff --git a/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceSession.cs b/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceSession.cs index 96d9ce970..0aa13e7ed 100644 --- a/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceSession.cs +++ b/src/Ryujinx.Audio.Backends.SoundIo/SoundIoHardwareDeviceSession.cs @@ -12,12 +12,12 @@ namespace Ryujinx.Audio.Backends.SoundIo { class SoundIoHardwareDeviceSession : HardwareDeviceSessionOutputBase { - private SoundIoHardwareDeviceDriver _driver; - private ConcurrentQueue _queuedBuffers; + private readonly SoundIoHardwareDeviceDriver _driver; + private readonly ConcurrentQueue _queuedBuffers; private SoundIoOutStreamContext _outputStream; - private DynamicRingBuffer _ringBuffer; + private readonly DynamicRingBuffer _ringBuffer; private ulong _playedSampleCount; - private ManualResetEvent _updateRequiredEvent; + private readonly ManualResetEvent _updateRequiredEvent; private int _disposeState; public SoundIoHardwareDeviceSession(SoundIoHardwareDeviceDriver driver, IVirtualMemoryManager memoryManager, SampleFormat requestedSampleFormat, uint requestedSampleRate, uint requestedChannelCount, float requestedVolume) : base(memoryManager, requestedSampleFormat, requestedSampleRate, requestedChannelCount) @@ -54,7 +54,7 @@ namespace Ryujinx.Audio.Backends.SoundIo public override void QueueBuffer(AudioBuffer buffer) { - SoundIoAudioBuffer driverBuffer = new SoundIoAudioBuffer(buffer.DataPointer, GetSampleCount(buffer)); + SoundIoAudioBuffer driverBuffer = new(buffer.DataPointer, GetSampleCount(buffer)); _ringBuffer.Write(buffer.Data, 0, buffer.Data.Length); @@ -81,7 +81,7 @@ namespace Ryujinx.Audio.Backends.SoundIo _driver.FlushContextEvents(); } - public override void UnregisterBuffer(AudioBuffer buffer) {} + public override void UnregisterBuffer(AudioBuffer buffer) { } public override bool WasBufferFullyConsumed(AudioBuffer buffer) { diff --git a/src/Ryujinx.Audio/AudioManager.cs b/src/Ryujinx.Audio/AudioManager.cs index c37ca4a3d..370d3d098 100644 --- a/src/Ryujinx.Audio/AudioManager.cs +++ b/src/Ryujinx.Audio/AudioManager.cs @@ -11,22 +11,22 @@ namespace Ryujinx.Audio /// /// Lock used to control the waiters registration. /// - private object _lock = new object(); + private readonly object _lock = new(); /// /// Events signaled when the driver played audio buffers. /// - private ManualResetEvent[] _updateRequiredEvents; + private readonly ManualResetEvent[] _updateRequiredEvents; /// /// Action to execute when the driver played audio buffers. /// - private Action[] _actions; + private readonly Action[] _actions; /// /// The worker thread in charge of handling sessions update. /// - private Thread _workerThread; + private readonly Thread _workerThread; private bool _isRunning; @@ -44,7 +44,7 @@ namespace Ryujinx.Audio _workerThread = new Thread(Update) { - Name = "AudioManager.Worker" + Name = "AudioManager.Worker", }; } @@ -115,6 +115,7 @@ namespace Ryujinx.Audio public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -129,4 +130,4 @@ namespace Ryujinx.Audio } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs b/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs index 30db340fa..124d8364f 100644 --- a/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs +++ b/src/Ryujinx.Audio/Backends/Common/BackendHelper.cs @@ -23,4 +23,4 @@ namespace Ryujinx.Audio.Backends.Common return bufferSize / GetSampleSize(format) / channelCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs b/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs index 9bf20d4b5..05dd2162a 100644 --- a/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs +++ b/src/Ryujinx.Audio/Backends/Common/DynamicRingBuffer.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Audio.Backends.Common { private const int RingBufferAlignment = 2048; - private object _lock = new object(); + private readonly object _lock = new(); private byte[] _buffer; private int _size; @@ -163,4 +163,4 @@ namespace Ryujinx.Audio.Backends.Common } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs b/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs index 6fb3bee02..5599c0827 100644 --- a/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs +++ b/src/Ryujinx.Audio/Backends/Common/HardwareDeviceSessionOutputBase.cs @@ -66,14 +66,11 @@ namespace Ryujinx.Audio.Backends.Common return false; } - if (buffer.Data == null) - { - buffer.Data = samples; - } + buffer.Data ??= samples; return true; } public virtual void UnregisterBuffer(AudioBuffer buffer) { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs index 22919f1e1..3f3806c3e 100644 --- a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceDriver.cs @@ -6,14 +6,13 @@ using Ryujinx.Common.Logging; using Ryujinx.Memory; using System; using System.Threading; - using static Ryujinx.Audio.Integration.IHardwareDeviceDriver; namespace Ryujinx.Audio.Backends.CompatLayer { public class CompatLayerHardwareDeviceDriver : IHardwareDeviceDriver { - private IHardwareDeviceDriver _realDriver; + private readonly IHardwareDeviceDriver _realDriver; public static bool IsSupported => true; @@ -24,6 +23,7 @@ namespace Ryujinx.Audio.Backends.CompatLayer public void Dispose() { + GC.SuppressFinalize(this); _realDriver.Dispose(); } @@ -49,7 +49,7 @@ namespace Ryujinx.Audio.Backends.CompatLayer 6 => SelectHardwareChannelCount(2), 2 => SelectHardwareChannelCount(1), 1 => throw new ArgumentException("No valid channel configuration found!"), - _ => throw new ArgumentException($"Invalid targetChannelCount {targetChannelCount}") + _ => throw new ArgumentException($"Invalid targetChannelCount {targetChannelCount}"), }; } @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Backends.CompatLayer { Logger.Warning?.Print(LogClass.Audio, "The selected audio backend doesn't support audio input, fallback to dummy..."); - return new DummyHardwareDeviceSessionInput(this, memoryManager, sampleFormat, sampleRate, channelCount); + return new DummyHardwareDeviceSessionInput(this, memoryManager); } throw new NotImplementedException(); @@ -138,12 +138,12 @@ namespace Ryujinx.Audio.Backends.CompatLayer if (direction == Direction.Input) { - Logger.Warning?.Print(LogClass.Audio, $"The selected audio backend doesn't support the requested audio input configuration, fallback to dummy..."); + Logger.Warning?.Print(LogClass.Audio, "The selected audio backend doesn't support the requested audio input configuration, fallback to dummy..."); // TODO: We currently don't support audio input upsampling/downsampling, implement this. realSession.Dispose(); - return new DummyHardwareDeviceSessionInput(this, memoryManager, sampleFormat, sampleRate, channelCount); + return new DummyHardwareDeviceSessionInput(this, memoryManager); } // It must be a HardwareDeviceSessionOutputBase. @@ -183,4 +183,4 @@ namespace Ryujinx.Audio.Backends.CompatLayer return direction == Direction.Input || direction == Direction.Output; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs index f22a7a690..a9acabec9 100644 --- a/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs +++ b/src/Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs @@ -8,9 +8,9 @@ namespace Ryujinx.Audio.Backends.CompatLayer { class CompatLayerHardwareDeviceSession : HardwareDeviceSessionOutputBase { - private HardwareDeviceSessionOutputBase _realSession; - private SampleFormat _userSampleFormat; - private uint _userChannelCount; + private readonly HardwareDeviceSessionOutputBase _realSession; + private readonly SampleFormat _userSampleFormat; + private readonly uint _userChannelCount; public CompatLayerHardwareDeviceSession(HardwareDeviceSessionOutputBase realSession, SampleFormat userSampleFormat, uint userChannelCount) : base(realSession.MemoryManager, realSession.RequestedSampleFormat, realSession.RequestedSampleRate, userChannelCount) { @@ -116,11 +116,11 @@ namespace Ryujinx.Audio.Backends.CompatLayer samples = MemoryMarshal.Cast(samplesPCM16).ToArray(); } - AudioBuffer fakeBuffer = new AudioBuffer + AudioBuffer fakeBuffer = new() { BufferTag = buffer.BufferTag, DataPointer = buffer.DataPointer, - DataSize = (ulong)samples.Length + DataSize = (ulong)samples.Length, }; bool result = _realSession.RegisterBuffer(fakeBuffer, samples); @@ -159,4 +159,4 @@ namespace Ryujinx.Audio.Backends.CompatLayer return _realSession.WasBufferFullyConsumed(buffer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs b/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs index 6959c1588..ffd427a5e 100644 --- a/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs +++ b/src/Ryujinx.Audio/Backends/CompatLayer/Downmixing.cs @@ -31,18 +31,18 @@ namespace Ryujinx.Audio.Backends.CompatLayer private const int Minus6dBInQ15 = (int)(0.501f * RawQ15One); private const int Minus12dBInQ15 = (int)(0.251f * RawQ15One); - private static readonly int[] DefaultSurroundToStereoCoefficients = new int[4] + private static readonly int[] _defaultSurroundToStereoCoefficients = new int[4] { RawQ15One, Minus3dBInQ15, Minus12dBInQ15, - Minus3dBInQ15 + Minus3dBInQ15, }; - private static readonly int[] DefaultStereoToMonoCoefficients = new int[2] + private static readonly int[] _defaultStereoToMonoCoefficients = new int[2] { Minus6dBInQ15, - Minus6dBInQ15 + Minus6dBInQ15, }; private const int SurroundChannelCount = 6; @@ -114,12 +114,12 @@ namespace Ryujinx.Audio.Backends.CompatLayer public static short[] DownMixStereoToMono(ReadOnlySpan data) { - return DownMixStereoToMono(DefaultStereoToMonoCoefficients, data); + return DownMixStereoToMono(_defaultStereoToMonoCoefficients, data); } public static short[] DownMixSurroundToStereo(ReadOnlySpan data) { - return DownMixSurroundToStereo(DefaultSurroundToStereoCoefficients, data); + return DownMixSurroundToStereo(_defaultSurroundToStereoCoefficients, data); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs index 641640f0e..bac21c448 100644 --- a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceDriver.cs @@ -1,16 +1,16 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Integration; using Ryujinx.Memory; +using System; using System.Threading; - using static Ryujinx.Audio.Integration.IHardwareDeviceDriver; namespace Ryujinx.Audio.Backends.Dummy { public class DummyHardwareDeviceDriver : IHardwareDeviceDriver { - private ManualResetEvent _updateRequiredEvent; - private ManualResetEvent _pauseEvent; + private readonly ManualResetEvent _updateRequiredEvent; + private readonly ManualResetEvent _pauseEvent; public static bool IsSupported => true; @@ -36,10 +36,8 @@ namespace Ryujinx.Audio.Backends.Dummy { return new DummyHardwareDeviceSessionOutput(this, memoryManager, sampleFormat, sampleRate, channelCount, volume); } - else - { - return new DummyHardwareDeviceSessionInput(this, memoryManager, sampleFormat, sampleRate, channelCount); - } + + return new DummyHardwareDeviceSessionInput(this, memoryManager); } public ManualResetEvent GetUpdateRequiredEvent() @@ -54,6 +52,7 @@ namespace Ryujinx.Audio.Backends.Dummy public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -86,4 +85,4 @@ namespace Ryujinx.Audio.Backends.Dummy return channelCount == 1 || channelCount == 2 || channelCount == 6; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs index 845713a19..f51a63393 100644 --- a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs +++ b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionInput.cs @@ -8,10 +8,10 @@ namespace Ryujinx.Audio.Backends.Dummy class DummyHardwareDeviceSessionInput : IHardwareDeviceSession { private float _volume; - private IHardwareDeviceDriver _manager; - private IVirtualMemoryManager _memoryManager; + private readonly IHardwareDeviceDriver _manager; + private readonly IVirtualMemoryManager _memoryManager; - public DummyHardwareDeviceSessionInput(IHardwareDeviceDriver manager, IVirtualMemoryManager memoryManager, SampleFormat requestedSampleFormat, uint requestedSampleRate, uint requestedChannelCount) + public DummyHardwareDeviceSessionInput(IHardwareDeviceDriver manager, IVirtualMemoryManager memoryManager) { _volume = 1.0f; _manager = manager; @@ -64,4 +64,4 @@ namespace Ryujinx.Audio.Backends.Dummy return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs index 8e2c949ec..1c248faaa 100644 --- a/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs +++ b/src/Ryujinx.Audio/Backends/Dummy/DummyHardwareDeviceSessionOutput.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Audio.Backends.Dummy internal class DummyHardwareDeviceSessionOutput : HardwareDeviceSessionOutputBase { private float _volume; - private IHardwareDeviceDriver _manager; + private readonly IHardwareDeviceDriver _manager; private ulong _playedSampleCount; @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Backends.Dummy return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioBuffer.cs b/src/Ryujinx.Audio/Common/AudioBuffer.cs index b79401b77..87a7d5f32 100644 --- a/src/Ryujinx.Audio/Common/AudioBuffer.cs +++ b/src/Ryujinx.Audio/Common/AudioBuffer.cs @@ -34,4 +34,4 @@ namespace Ryujinx.Audio.Common /// public byte[] Data; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioDeviceSession.cs b/src/Ryujinx.Audio/Common/AudioDeviceSession.cs index 0191f7ccd..a0e04c80d 100644 --- a/src/Ryujinx.Audio/Common/AudioDeviceSession.cs +++ b/src/Ryujinx.Audio/Common/AudioDeviceSession.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Audio.Common /// /// Array of all buffers currently used or released. /// - private AudioBuffer[] _buffers; + private readonly AudioBuffer[] _buffers; /// /// The server index inside (appended but not queued to device driver). @@ -58,17 +58,17 @@ namespace Ryujinx.Audio.Common /// /// The released buffer event. /// - private IWritableEvent _bufferEvent; + private readonly IWritableEvent _bufferEvent; /// /// The session on the device driver. /// - private IHardwareDeviceSession _hardwareDeviceSession; + private readonly IHardwareDeviceSession _hardwareDeviceSession; /// /// Max number of buffers that can be registered to the device driver at a time. /// - private uint _bufferRegisteredLimit; + private readonly uint _bufferRegisteredLimit; /// /// Create a new . @@ -311,9 +311,9 @@ namespace Ryujinx.Audio.Common return false; } - public bool AppendUacBuffer(AudioBuffer buffer, uint handle) + public static bool AppendUacBuffer(AudioBuffer buffer, uint handle) { - // NOTE: On hardware, there is another RegisterBuffer method taking an handle. + // NOTE: On hardware, there is another RegisterBuffer method taking a handle. // This variant of the call always return false (stubbed?) as a result this logic will never succeed. return false; @@ -425,10 +425,8 @@ namespace Ryujinx.Audio.Common { return 0; } - else - { - return _hardwareDeviceSession.GetPlayedSampleCount(); - } + + return _hardwareDeviceSession.GetPlayedSampleCount(); } /// @@ -515,4 +513,4 @@ namespace Ryujinx.Audio.Common } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioDeviceState.cs b/src/Ryujinx.Audio/Common/AudioDeviceState.cs index b3f968da2..8705e802e 100644 --- a/src/Ryujinx.Audio/Common/AudioDeviceState.cs +++ b/src/Ryujinx.Audio/Common/AudioDeviceState.cs @@ -13,6 +13,6 @@ namespace Ryujinx.Audio.Common /// /// The audio device is stopped. /// - Stopped + Stopped, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs b/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs index d3cfdd47b..078c3a394 100644 --- a/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs +++ b/src/Ryujinx.Audio/Common/AudioInputConfiguration.cs @@ -24,6 +24,6 @@ namespace Ryujinx.Audio.Common /// /// Reserved/unused. /// - private ushort _reserved; + private readonly ushort _reserved; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs b/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs index e17e17576..594f12250 100644 --- a/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs +++ b/src/Ryujinx.Audio/Common/AudioOutputConfiguration.cs @@ -34,4 +34,4 @@ namespace Ryujinx.Audio.Common /// public AudioDeviceState AudioOutState; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/AudioUserBuffer.cs b/src/Ryujinx.Audio/Common/AudioUserBuffer.cs index 50ab67fa3..bb71165ff 100644 --- a/src/Ryujinx.Audio/Common/AudioUserBuffer.cs +++ b/src/Ryujinx.Audio/Common/AudioUserBuffer.cs @@ -33,4 +33,4 @@ namespace Ryujinx.Audio.Common /// public ulong DataOffset; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Common/SampleFormat.cs b/src/Ryujinx.Audio/Common/SampleFormat.cs index 901410a24..39e525e87 100644 --- a/src/Ryujinx.Audio/Common/SampleFormat.cs +++ b/src/Ryujinx.Audio/Common/SampleFormat.cs @@ -38,6 +38,6 @@ namespace Ryujinx.Audio.Common /// /// ADPCM sample format. (Also known as GC-ADPCM) /// - Adpcm = 6 + Adpcm = 6, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Constants.cs b/src/Ryujinx.Audio/Constants.cs index 7d2ffa57b..eb5b39013 100644 --- a/src/Ryujinx.Audio/Constants.cs +++ b/src/Ryujinx.Audio/Constants.cs @@ -164,7 +164,7 @@ namespace Ryujinx.Audio /// /// The default coefficients used for standard 5.1 surround to stereo downmixing. /// - public static float[] DefaultSurroundToStereoCoefficients = new float[4] + public static readonly float[] DefaultSurroundToStereoCoefficients = new float[4] { 1.0f, 0.707f, @@ -172,4 +172,4 @@ namespace Ryujinx.Audio 0.707f, }; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Input/AudioInputManager.cs b/src/Ryujinx.Audio/Input/AudioInputManager.cs index ac012c4a9..4d1796c96 100644 --- a/src/Ryujinx.Audio/Input/AudioInputManager.cs +++ b/src/Ryujinx.Audio/Input/AudioInputManager.cs @@ -14,17 +14,17 @@ namespace Ryujinx.Audio.Input /// public class AudioInputManager : IDisposable { - private object _lock = new object(); + private readonly object _lock = new(); /// /// Lock used for session allocation. /// - private object _sessionLock = new object(); + private readonly object _sessionLock = new(); /// /// The session ids allocation table. /// - private int[] _sessionIds; + private readonly int[] _sessionIds; /// /// The device driver. @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Input /// /// The session instances. /// - private AudioInputSystem[] _sessions; + private readonly AudioInputSystem[] _sessions; /// /// The count of active sessions. @@ -166,6 +166,7 @@ namespace Ryujinx.Audio.Input /// /// If true, filter disconnected devices /// The list of all audio inputs name +#pragma warning disable CA1822 // Mark member as static public string[] ListAudioIns(bool filtered) { if (filtered) @@ -173,8 +174,9 @@ namespace Ryujinx.Audio.Input // TODO: Detect if the driver supports audio input } - return new string[] { Constants.DefaultDeviceInputName }; + return new[] { Constants.DefaultDeviceInputName }; } +#pragma warning restore CA1822 /// /// Open a new . @@ -205,7 +207,7 @@ namespace Ryujinx.Audio.Input IHardwareDeviceSession deviceSession = _deviceDriver.OpenDeviceSession(IHardwareDeviceDriver.Direction.Input, memoryManager, sampleFormat, parameter.SampleRate, parameter.ChannelCount); - AudioInputSystem audioIn = new AudioInputSystem(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); + AudioInputSystem audioIn = new(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); ResultCode result = audioIn.Initialize(inputDeviceName, sampleFormat, ref parameter, sessionId); @@ -238,6 +240,8 @@ namespace Ryujinx.Audio.Input public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -263,4 +267,4 @@ namespace Ryujinx.Audio.Input } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Input/AudioInputSystem.cs b/src/Ryujinx.Audio/Input/AudioInputSystem.cs index b3ca0fd68..34623b34f 100644 --- a/src/Ryujinx.Audio/Input/AudioInputSystem.cs +++ b/src/Ryujinx.Audio/Input/AudioInputSystem.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Input /// /// The session the . /// - private AudioDeviceSession _session; + private readonly AudioDeviceSession _session; /// /// The target device name of the . @@ -43,12 +43,12 @@ namespace Ryujinx.Audio.Input /// /// The owning this. /// - private AudioInputManager _manager; + private readonly AudioInputManager _manager; /// /// The lock of the parent. /// - private object _parentLock; + private readonly object _parentLock; /// /// The dispose state. @@ -90,11 +90,13 @@ namespace Ryujinx.Audio.Input { return ResultCode.DeviceNotFound; } - else if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) + + if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) { return ResultCode.UnsupportedSampleRate; } - else if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) + + if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) { return ResultCode.UnsupportedChannelConfiguration; } @@ -185,11 +187,11 @@ namespace Ryujinx.Audio.Input { lock (_parentLock) { - AudioBuffer buffer = new AudioBuffer + AudioBuffer buffer = new() { BufferTag = bufferTag, DataPointer = userBuffer.Data, - DataSize = userBuffer.DataSize + DataSize = userBuffer.DataSize, }; if (_session.AppendBuffer(buffer)) @@ -213,14 +215,14 @@ namespace Ryujinx.Audio.Input { lock (_parentLock) { - AudioBuffer buffer = new AudioBuffer + AudioBuffer buffer = new() { BufferTag = bufferTag, DataPointer = userBuffer.Data, - DataSize = userBuffer.DataSize + DataSize = userBuffer.DataSize, }; - if (_session.AppendUacBuffer(buffer, handle)) + if (AudioDeviceSession.AppendUacBuffer(buffer, handle)) { return ResultCode.Success; } @@ -373,6 +375,8 @@ namespace Ryujinx.Audio.Input public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -389,4 +393,4 @@ namespace Ryujinx.Audio.Input } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs b/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs index 552f1ab24..576954b96 100644 --- a/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs +++ b/src/Ryujinx.Audio/Integration/HardwareDeviceImpl.cs @@ -6,12 +6,12 @@ namespace Ryujinx.Audio.Integration { public class HardwareDeviceImpl : IHardwareDevice { - private IHardwareDeviceSession _session; - private uint _channelCount; - private uint _sampleRate; + private readonly IHardwareDeviceSession _session; + private readonly uint _channelCount; + private readonly uint _sampleRate; private uint _currentBufferTag; - private byte[] _buffer; + private readonly byte[] _buffer; public HardwareDeviceImpl(IHardwareDeviceDriver deviceDriver, uint channelCount, uint sampleRate, float volume) { @@ -36,7 +36,7 @@ namespace Ryujinx.Audio.Integration DataSize = (ulong)_buffer.Length, }); - _currentBufferTag = _currentBufferTag % 4; + _currentBufferTag %= 4; } public void SetVolume(float volume) @@ -61,6 +61,7 @@ namespace Ryujinx.Audio.Integration public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -72,4 +73,4 @@ namespace Ryujinx.Audio.Integration } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IHardwareDevice.cs b/src/Ryujinx.Audio/Integration/IHardwareDevice.cs index 300de8c5d..f9ade9dbc 100644 --- a/src/Ryujinx.Audio/Integration/IHardwareDevice.cs +++ b/src/Ryujinx.Audio/Integration/IHardwareDevice.cs @@ -52,4 +52,4 @@ namespace Ryujinx.Audio.Integration return channelCount != Constants.ChannelCountMax; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs b/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs index 4ed179519..9c812fb9a 100644 --- a/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs +++ b/src/Ryujinx.Audio/Integration/IHardwareDeviceDriver.cs @@ -13,7 +13,7 @@ namespace Ryujinx.Audio.Integration public enum Direction { Input, - Output + Output, } IHardwareDeviceSession OpenDeviceSession(Direction direction, IVirtualMemoryManager memoryManager, SampleFormat sampleFormat, uint sampleRate, uint channelCount, float volume = 1f); @@ -33,4 +33,4 @@ namespace Ryujinx.Audio.Integration return this; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs b/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs index 400daec00..f29c109cb 100644 --- a/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs +++ b/src/Ryujinx.Audio/Integration/IHardwareDeviceSession.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Audio.Integration void PrepareToClose(); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Integration/IWritableEvent.cs b/src/Ryujinx.Audio/Integration/IWritableEvent.cs index 9a12e3d28..a3b3bc0bc 100644 --- a/src/Ryujinx.Audio/Integration/IWritableEvent.cs +++ b/src/Ryujinx.Audio/Integration/IWritableEvent.cs @@ -15,4 +15,4 @@ namespace Ryujinx.Audio.Integration /// void Clear(); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Output/AudioOutputManager.cs b/src/Ryujinx.Audio/Output/AudioOutputManager.cs index 8c21f76a1..5232357bb 100644 --- a/src/Ryujinx.Audio/Output/AudioOutputManager.cs +++ b/src/Ryujinx.Audio/Output/AudioOutputManager.cs @@ -14,17 +14,17 @@ namespace Ryujinx.Audio.Output /// public class AudioOutputManager : IDisposable { - private object _lock = new object(); + private readonly object _lock = new(); /// /// Lock used for session allocation. /// - private object _sessionLock = new object(); + private readonly object _sessionLock = new(); /// /// The session ids allocation table. /// - private int[] _sessionIds; + private readonly int[] _sessionIds; /// /// The device driver. @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Output /// /// The session instances. /// - private AudioOutputSystem[] _sessions; + private readonly AudioOutputSystem[] _sessions; /// /// The count of active sessions. @@ -165,10 +165,12 @@ namespace Ryujinx.Audio.Output /// Get the list of all audio outputs name. /// /// The list of all audio outputs name +#pragma warning disable CA1822 // Mark member as static public string[] ListAudioOuts() { - return new string[] { Constants.DefaultDeviceOutputName }; + return new[] { Constants.DefaultDeviceOutputName }; } +#pragma warning restore CA1822 /// /// Open a new . @@ -182,6 +184,7 @@ namespace Ryujinx.Audio.Output /// The user configuration /// The applet resource user id of the application /// The process handle of the application + /// The volume level to request /// A reporting an error or a success public ResultCode OpenAudioOut(out string outputDeviceName, out AudioOutputConfiguration outputConfiguration, @@ -200,7 +203,7 @@ namespace Ryujinx.Audio.Output IHardwareDeviceSession deviceSession = _deviceDriver.OpenDeviceSession(IHardwareDeviceDriver.Direction.Output, memoryManager, sampleFormat, parameter.SampleRate, parameter.ChannelCount, volume); - AudioOutputSystem audioOut = new AudioOutputSystem(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); + AudioOutputSystem audioOut = new(this, _lock, deviceSession, _sessionsBufferEvents[sessionId]); ResultCode result = audioOut.Initialize(inputDeviceName, sampleFormat, ref parameter, sessionId); @@ -268,6 +271,8 @@ namespace Ryujinx.Audio.Output public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -293,4 +298,4 @@ namespace Ryujinx.Audio.Output } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Output/AudioOutputSystem.cs b/src/Ryujinx.Audio/Output/AudioOutputSystem.cs index 93df87aab..f9b9bdcf1 100644 --- a/src/Ryujinx.Audio/Output/AudioOutputSystem.cs +++ b/src/Ryujinx.Audio/Output/AudioOutputSystem.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Output /// /// The session the . /// - private AudioDeviceSession _session; + private readonly AudioDeviceSession _session; /// /// The target device name of the . @@ -43,12 +43,12 @@ namespace Ryujinx.Audio.Output /// /// The owning this. /// - private AudioOutputManager _manager; + private readonly AudioOutputManager _manager; /// /// THe lock of the parent. /// - private object _parentLock; + private readonly object _parentLock; /// /// The dispose state. @@ -90,11 +90,13 @@ namespace Ryujinx.Audio.Output { return ResultCode.DeviceNotFound; } - else if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) + + if (configuration.SampleRate != 0 && configuration.SampleRate != Constants.TargetSampleRate) { return ResultCode.UnsupportedSampleRate; } - else if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) + + if (configuration.ChannelCount != 0 && configuration.ChannelCount != 1 && configuration.ChannelCount != 2 && configuration.ChannelCount != 6) { return ResultCode.UnsupportedChannelConfiguration; } @@ -185,11 +187,11 @@ namespace Ryujinx.Audio.Output { lock (_parentLock) { - AudioBuffer buffer = new AudioBuffer + AudioBuffer buffer = new() { BufferTag = bufferTag, DataPointer = userBuffer.Data, - DataSize = userBuffer.DataSize + DataSize = userBuffer.DataSize, }; if (_session.AppendBuffer(buffer)) @@ -346,6 +348,8 @@ namespace Ryujinx.Audio.Output public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -362,4 +366,4 @@ namespace Ryujinx.Audio.Output } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs b/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs index 966474052..b7b97d5d8 100644 --- a/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs +++ b/src/Ryujinx.Audio/Renderer/Common/AuxiliaryBufferAddresses.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Audio.Renderer.Common public ulong ReturnBufferInfo; public ulong ReturnBufferInfoBase; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs b/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs index 270f84d5b..b0963c935 100644 --- a/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Common/BehaviourParameter.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Reserved/padding. /// - private uint _padding; + private readonly uint _padding; /// /// The flags given controlling behaviour of the audio renderer @@ -38,7 +38,7 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Reserved/padding. /// - private uint _padding; + private readonly uint _padding; /// /// Extra information given with the @@ -47,4 +47,4 @@ namespace Ryujinx.Audio.Renderer.Common public ulong ExtraErrorInfo; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs b/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs index 24a9350fc..3beb62399 100644 --- a/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs +++ b/src/Ryujinx.Audio/Renderer/Common/EdgeMatrix.cs @@ -147,4 +147,4 @@ namespace Ryujinx.Audio.Renderer.Common return _nodeCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/EffectType.cs b/src/Ryujinx.Audio/Renderer/Common/EffectType.cs index 7128db4ce..7c8713b12 100644 --- a/src/Ryujinx.Audio/Renderer/Common/EffectType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/EffectType.cs @@ -55,4 +55,4 @@ namespace Ryujinx.Audio.Renderer.Common /// Compressor, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs b/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs index 590731c3b..6d835879c 100644 --- a/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs +++ b/src/Ryujinx.Audio/Renderer/Common/MemoryPoolUserState.cs @@ -38,6 +38,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// The memory pool is released. (client side only) /// - Released = 6 + Released = 6, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs b/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs index a999e3ad1..76fba54b6 100644 --- a/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Common/NodeIdHelper.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Audio.Renderer.Common return (nodeId >> 16) & 0xFFF; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs b/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs index 69b58f6bc..b226da14f 100644 --- a/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/NodeIdType.cs @@ -28,6 +28,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Performance monitoring related node id (performance commands) /// - Performance = 15 + Performance = 15, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs b/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs index 45748d606..75290a741 100644 --- a/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs +++ b/src/Ryujinx.Audio/Renderer/Common/NodeStates.cs @@ -53,17 +53,17 @@ namespace Ryujinx.Audio.Renderer.Common } private int _nodeCount; - private EdgeMatrix _discovered; - private EdgeMatrix _finished; + private readonly EdgeMatrix _discovered; + private readonly EdgeMatrix _finished; private Memory _resultArray; - private Stack _stack; + private readonly Stack _stack; private int _tsortResultIndex; private enum NodeState : byte { Unknown, Discovered, - Finished + Finished, } public NodeStates() @@ -88,16 +88,16 @@ namespace Ryujinx.Audio.Renderer.Common int edgeMatrixWorkBufferSize = EdgeMatrix.GetWorkBufferSize(nodeCount); - _discovered.Initialize(nodeStatesWorkBuffer.Slice(0, edgeMatrixWorkBufferSize), nodeCount); + _discovered.Initialize(nodeStatesWorkBuffer[..edgeMatrixWorkBufferSize], nodeCount); _finished.Initialize(nodeStatesWorkBuffer.Slice(edgeMatrixWorkBufferSize, edgeMatrixWorkBufferSize), nodeCount); - nodeStatesWorkBuffer = nodeStatesWorkBuffer.Slice(edgeMatrixWorkBufferSize * 2); + nodeStatesWorkBuffer = nodeStatesWorkBuffer[(edgeMatrixWorkBufferSize * 2)..]; - _resultArray = SpanMemoryManager.Cast(nodeStatesWorkBuffer.Slice(0, sizeof(int) * nodeCount)); + _resultArray = SpanMemoryManager.Cast(nodeStatesWorkBuffer[..(sizeof(int) * nodeCount)]); - nodeStatesWorkBuffer = nodeStatesWorkBuffer.Slice(sizeof(int) * nodeCount); + nodeStatesWorkBuffer = nodeStatesWorkBuffer[(sizeof(int) * nodeCount)..]; - Memory stackWorkBuffer = SpanMemoryManager.Cast(nodeStatesWorkBuffer.Slice(0, Stack.CalcBufferSize(nodeCount * nodeCount))); + Memory stackWorkBuffer = SpanMemoryManager.Cast(nodeStatesWorkBuffer[..Stack.CalcBufferSize(nodeCount * nodeCount)]); _stack.Reset(stackWorkBuffer, nodeCount * nodeCount); } @@ -120,7 +120,8 @@ namespace Ryujinx.Audio.Renderer.Common return NodeState.Discovered; } - else if (_finished.Test(index)) + + if (_finished.Test(index)) { Debug.Assert(!_discovered.Test(index)); @@ -158,7 +159,7 @@ namespace Ryujinx.Audio.Renderer.Common public ReadOnlySpan GetTsortResult() { - return _resultArray.Span.Slice(0, _tsortResultIndex); + return _resultArray.Span[.._tsortResultIndex]; } public bool Sort(EdgeMatrix edgeMatrix) @@ -226,4 +227,4 @@ namespace Ryujinx.Audio.Renderer.Common return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs b/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs index 805d55183..bde32a709 100644 --- a/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/PerformanceDetailType.cs @@ -15,6 +15,6 @@ namespace Ryujinx.Audio.Renderer.Common PcmFloat, Limiter, CaptureBuffer, - Compressor + Compressor, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs b/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs index bde72aaed..e32095e62 100644 --- a/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/PerformanceEntryType.cs @@ -6,6 +6,6 @@ namespace Ryujinx.Audio.Renderer.Common Voice, SubMix, FinalMix, - Sink + Sink, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/PlayState.cs b/src/Ryujinx.Audio/Renderer/Common/PlayState.cs index 4a6929e03..a83d16afb 100644 --- a/src/Ryujinx.Audio/Renderer/Common/PlayState.cs +++ b/src/Ryujinx.Audio/Renderer/Common/PlayState.cs @@ -18,6 +18,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// The user request the voice to be paused. /// - Pause + Pause, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs b/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs index aa7685621..c7443cc49 100644 --- a/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs +++ b/src/Ryujinx.Audio/Renderer/Common/ReverbEarlyMode.cs @@ -28,6 +28,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// No early reflection. /// - Disabled + Disabled, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs b/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs index 8aa88165a..78f91cf08 100644 --- a/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs +++ b/src/Ryujinx.Audio/Renderer/Common/ReverbLateMode.cs @@ -33,6 +33,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Max delay. (used for delay line limits) /// - Limit = NoDelay + Limit = NoDelay, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/SinkType.cs b/src/Ryujinx.Audio/Renderer/Common/SinkType.cs index 2e17201e7..5a08df4e1 100644 --- a/src/Ryujinx.Audio/Renderer/Common/SinkType.cs +++ b/src/Ryujinx.Audio/Renderer/Common/SinkType.cs @@ -18,6 +18,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// The sink is a circular buffer. /// - CircularBuffer + CircularBuffer, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs b/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs index 70dbfa947..7efe3b02b 100644 --- a/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Common/UpdateDataHeader.cs @@ -1,3 +1,4 @@ +using Ryujinx.Common.Memory; using System.Runtime.CompilerServices; namespace Ryujinx.Audio.Renderer.Common @@ -19,7 +20,9 @@ namespace Ryujinx.Audio.Renderer.Common public uint Unknown24; public uint RenderInfoSize; - private unsafe fixed int _reserved[4]; +#pragma warning disable IDE0051, CS0169 // Remove unused field + private Array4 _reserved; +#pragma warning restore IDE0051, CS0169 public uint TotalSize; @@ -30,4 +33,4 @@ namespace Ryujinx.Audio.Renderer.Common TotalSize = (uint)Unsafe.SizeOf(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs b/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs index f52c2f4c4..608381af1 100644 --- a/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs +++ b/src/Ryujinx.Audio/Renderer/Common/VoiceUpdateState.cs @@ -101,4 +101,4 @@ namespace Ryujinx.Audio.Renderer.Common } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs b/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs index 0d00e8384..5109d3fa0 100644 --- a/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs +++ b/src/Ryujinx.Audio/Renderer/Common/WaveBuffer.cs @@ -1,5 +1,4 @@ using System.Runtime.InteropServices; - using DspAddr = System.UInt64; namespace Ryujinx.Audio.Renderer.Common @@ -77,6 +76,6 @@ namespace Ryujinx.Audio.Renderer.Common /// /// Padding/Reserved. /// - private ushort _padding; + private readonly ushort _padding; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs b/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs index f35dbec7f..54673f2f6 100644 --- a/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs +++ b/src/Ryujinx.Audio/Renderer/Common/WorkBufferAllocator.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Audio.Renderer.Common if (size != 0) { - ulong alignedOffset = BitUtils.AlignUp(Offset, (ulong)align); + ulong alignedOffset = BitUtils.AlignUp(Offset, (ulong)align); if (alignedOffset + size <= (ulong)BackingMemory.Length) { @@ -32,7 +32,7 @@ namespace Ryujinx.Audio.Renderer.Common Offset = alignedOffset + size; // Clear the memory to be sure that is does not contain any garbage. - result.Span.Fill(0); + result.Span.Clear(); return result; } @@ -55,7 +55,7 @@ namespace Ryujinx.Audio.Renderer.Common public static ulong GetTargetSize(ulong currentSize, ulong count, int align) where T : unmanaged { - return BitUtils.AlignUp(currentSize, (ulong)align) + (ulong)Unsafe.SizeOf() * count; + return BitUtils.AlignUp(currentSize, (ulong)align) + (ulong)Unsafe.SizeOf() * count; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs b/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs index 90692b004..91956fda6 100644 --- a/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Device/VirtualDevice.cs @@ -12,11 +12,11 @@ namespace Ryujinx.Audio.Renderer.Device /// public static readonly VirtualDevice[] Devices = new VirtualDevice[5] { - new VirtualDevice("AudioStereoJackOutput", 2, true), - new VirtualDevice("AudioBuiltInSpeakerOutput", 2, false), - new VirtualDevice("AudioTvOutput", 6, false), - new VirtualDevice("AudioUsbDeviceOutput", 2, true), - new VirtualDevice("AudioExternalOutput", 6, true), + new("AudioStereoJackOutput", 2, true), + new("AudioBuiltInSpeakerOutput", 2, false), + new("AudioTvOutput", 6, false), + new("AudioUsbDeviceOutput", 2, true), + new("AudioExternalOutput", 6, true), }; /// @@ -86,4 +86,4 @@ namespace Ryujinx.Audio.Renderer.Device return Name; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs index db35d26d2..09fa71eda 100644 --- a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs +++ b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSession.cs @@ -24,4 +24,4 @@ namespace Ryujinx.Audio.Renderer.Device Device = virtualDevice; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs index 696af90fa..4ad70619e 100644 --- a/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs +++ b/src/Ryujinx.Audio/Renderer/Device/VirtualDeviceSessionRegistry.cs @@ -11,13 +11,15 @@ namespace Ryujinx.Audio.Renderer.Device /// /// The session registry, used to store the sessions of a given AppletResourceId. /// - private Dictionary _sessionsRegistry = new Dictionary(); + private readonly Dictionary _sessionsRegistry = new(); /// /// The default . /// /// This is used when the USB device is the default one on older revision. +#pragma warning disable CA1822 // Mark member as static public VirtualDevice DefaultDevice => VirtualDevice.Devices[0]; +#pragma warning restore CA1822 /// /// The current active . @@ -76,4 +78,4 @@ namespace Ryujinx.Audio.Renderer.Device return virtualDeviceSession; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs index 2680dcb1e..5cb4509ff 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/AdpcmHelper.cs @@ -12,7 +12,9 @@ namespace Ryujinx.Audio.Renderer.Dsp private const int SamplesPerFrame = 14; private const int NibblesPerFrame = SamplesPerFrame + 2; private const int BytesPerFrame = 8; +#pragma warning disable IDE0051 // Remove unused private member private const int BitsPerFrame = BytesPerFrame * 8; +#pragma warning restore IDE0051 [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetAdpcmDataSize(int sampleCount) @@ -64,10 +66,14 @@ namespace Ryujinx.Audio.Renderer.Dsp private static short Saturate(int value) { if (value > short.MaxValue) + { value = short.MaxValue; + } if (value < short.MinValue) + { value = short.MinValue; + } return (short)value; } @@ -109,7 +115,7 @@ namespace Ryujinx.Audio.Renderer.Dsp ReadOnlySpan targetInput; - targetInput = input.Slice(nibbles / 2); + targetInput = input[(nibbles / 2)..]; while (remaining > 0) { @@ -213,4 +219,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return decodedCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs b/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs index 899c2ef97..9c885b2cf 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/AudioProcessor.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Renderer.Dsp Start, Stop, RenderStart, - RenderEnd + RenderEnd, } private class RendererSession @@ -36,7 +36,7 @@ namespace Ryujinx.Audio.Renderer.Dsp private long _lastTime; private long _playbackEnds; - private ManualResetEvent _event; + private readonly ManualResetEvent _event; private ManualResetEvent _pauseEvent; @@ -45,6 +45,7 @@ namespace Ryujinx.Audio.Renderer.Dsp _event = new ManualResetEvent(false); } +#pragma warning disable IDE0051 // Remove unused private member private static uint GetHardwareChannelCount(IHardwareDeviceDriver deviceDriver) { // Get the real device driver (In case the compat layer is on top of it). @@ -54,12 +55,11 @@ namespace Ryujinx.Audio.Renderer.Dsp { return 6; } - else - { - // NOTE: We default to stereo as this will get downmixed to mono by the compat layer if it's not compatible. - return 2; - } + + // NOTE: We default to stereo as this will get downmixed to mono by the compat layer if it's not compatible. + return 2; } +#pragma warning restore IDE0051 public void Start(IHardwareDeviceDriver deviceDriver, float volume) { @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Renderer.Dsp { CommandList = commands, RenderingLimit = renderingLimit, - AppletResourceId = appletResourceId + AppletResourceId = appletResourceId, }; } @@ -171,7 +171,7 @@ namespace Ryujinx.Audio.Renderer.Dsp { _workerThread = new Thread(Work) { - Name = "AudioProcessor.Worker" + Name = "AudioProcessor.Worker", }; _workerThread.Start(); @@ -260,6 +260,7 @@ namespace Ryujinx.Audio.Renderer.Dsp public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -271,4 +272,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs index 98460ff1a..1a51a1fbd 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/BiquadFilterHelper.cs @@ -80,4 +80,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs index 1fe6069f7..51a12b4e7 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/AdpcmDataSourceCommandVersion1.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -29,7 +31,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public DecodingBehaviour DecodingBehaviour { get; } - public AdpcmDataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, int nodeId) + public AdpcmDataSourceCommandVersion1(ref VoiceState serverState, Memory state, ushort outputBufferIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -57,7 +59,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat.Adpcm, @@ -72,4 +74,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs index 5c3c0324b..7ed32800f 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/AuxiliaryBufferCommand.cs @@ -155,7 +155,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (readResult != context.SampleCount) { - outputBuffer.Slice((int)readResult, (int)context.SampleCount - (int)readResult).Fill(0); + outputBuffer[(int)readResult..(int)context.SampleCount].Clear(); } } else @@ -170,4 +170,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs index b994c1cb9..f56dd70e3 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/BiquadFilterCommand.cs @@ -48,4 +48,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command BiquadFilterHelper.ProcessBiquadFilter(ref _parameter, ref state, outputBuffer, inputBuffer, context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs index da1cb2546..01bff1e7d 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CaptureBufferCommand.cs @@ -133,4 +133,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CircularBufferSinkCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CircularBufferSinkCommand.cs index e50637eb3..59ef70932 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CircularBufferSinkCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CircularBufferSinkCommand.cs @@ -43,7 +43,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public void Process(CommandList context) { - const int targetChannelCount = 2; + const int TargetChannelCount = 2; ulong currentOffset = CurrentOffset; @@ -59,10 +59,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int y = 0; y < context.SampleCount; y++) { - context.MemoryManager.Write(targetOffset + (ulong)y * targetChannelCount, PcmHelper.Saturate(inputBuffer[y])); + context.MemoryManager.Write(targetOffset + (ulong)y * TargetChannelCount, PcmHelper.Saturate(inputBuffer[y])); } - currentOffset += context.SampleCount * targetChannelCount; + currentOffset += context.SampleCount * TargetChannelCount; if (currentOffset >= CircularBufferSize) { @@ -73,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs index 9e653e804..f0f85b0b2 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/ClearMixBufferCommand.cs @@ -21,4 +21,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command context.ClearBuffers(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs index 2cbed9c2b..19a9576f7 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandList.cs @@ -71,7 +71,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command return (IntPtr)((float*)_buffersMemoryHandle.Pointer + index * _sampleCount); } - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(index), index, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -149,7 +149,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public void Dispose() { + GC.SuppressFinalize(this); _buffersMemoryHandle.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs index 9ce181b17..098a04a04 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CommandType.cs @@ -32,6 +32,6 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command LimiterVersion2, GroupedBiquadFilter, CaptureBuffer, - Compressor + Compressor, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs index 34231e614..01291852e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CompressorCommand.cs @@ -1,6 +1,7 @@ using Ryujinx.Audio.Renderer.Dsp.Effect; using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; @@ -51,11 +52,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (_parameter.Status == Server.Effect.UsageState.Invalid) + if (_parameter.Status == UsageState.Invalid) { state = new CompressorState(ref _parameter); } - else if (_parameter.Status == Server.Effect.UsageState.New) + else if (_parameter.Status == UsageState.New) { state.UpdateParameter(ref _parameter); } diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs index 7237fddf6..3f6aa8390 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/CopyMixBufferCommand.cs @@ -27,4 +27,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command context.CopyBuffer(OutputBufferIndex, InputBufferIndex); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs index c1503b6a0..e82d403bf 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DataSourceVersion2Command.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -37,7 +39,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public SampleRateConversionQuality SrcQuality { get; } - public DataSourceVersion2Command(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) + public DataSourceVersion2Command(ref VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -72,24 +74,20 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command private static CommandType GetCommandTypeBySampleFormat(SampleFormat sampleFormat) { - switch (sampleFormat) + return sampleFormat switch { - case SampleFormat.Adpcm: - return CommandType.AdpcmDataSourceVersion2; - case SampleFormat.PcmInt16: - return CommandType.PcmInt16DataSourceVersion2; - case SampleFormat.PcmFloat: - return CommandType.PcmFloatDataSourceVersion2; - default: - throw new NotImplementedException($"{sampleFormat}"); - } + SampleFormat.Adpcm => CommandType.AdpcmDataSourceVersion2, + SampleFormat.PcmInt16 => CommandType.PcmInt16DataSourceVersion2, + SampleFormat.PcmFloat => CommandType.PcmFloatDataSourceVersion2, + _ => throw new NotImplementedException($"{sampleFormat}"), + }; } public void Process(CommandList context) { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat, @@ -99,10 +97,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ExtraParameterSize = ExtraParameterSize, ChannelIndex = (int)ChannelIndex, ChannelCount = (int)ChannelCount, - SrcQuality = SrcQuality + SrcQuality = SrcQuality, }; DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs index 6dc766594..003806cf7 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DelayCommand.cs @@ -56,7 +56,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe void ProcessDelayMono(ref DelayState state, float* outputBuffer, float* inputBuffer, uint sampleCount) { - const ushort channelCount = 1; + const ushort ChannelCount = 1; float feedbackGain = FixedPointHelper.ToFloat(Parameter.FeedbackGain, FixedPointPrecision); float inGain = FixedPointHelper.ToFloat(Parameter.InGain, FixedPointPrecision); @@ -70,7 +70,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float temp = input * inGain + delayLineValue * feedbackGain; - state.UpdateLowPassFilter(ref temp, channelCount); + state.UpdateLowPassFilter(ref temp, ChannelCount); outputBuffer[i] = (input * dryGain + delayLineValue * outGain) / 64; } @@ -79,7 +79,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe void ProcessDelayStereo(ref DelayState state, Span outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - const ushort channelCount = 2; + const ushort ChannelCount = 2; float delayFeedbackBaseGain = state.DelayFeedbackBaseGain; float delayFeedbackCrossGain = state.DelayFeedbackCrossGain; @@ -87,18 +87,18 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float dryGain = FixedPointHelper.ToFloat(Parameter.DryGain, FixedPointPrecision); float outGain = FixedPointHelper.ToFloat(Parameter.OutGain, FixedPointPrecision); - Matrix2x2 delayFeedback = new Matrix2x2(delayFeedbackBaseGain, delayFeedbackCrossGain, + Matrix2x2 delayFeedback = new(delayFeedbackBaseGain, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackBaseGain); for (int i = 0; i < sampleCount; i++) { - Vector2 channelInput = new Vector2 + Vector2 channelInput = new() { X = *((float*)inputBuffers[0] + i) * 64, Y = *((float*)inputBuffers[1] + i) * 64, }; - Vector2 delayLineValues = new Vector2() + Vector2 delayLineValues = new() { X = state.DelayLines[0].Read(), Y = state.DelayLines[1].Read(), @@ -106,7 +106,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command Vector2 temp = MatrixHelper.Transform(ref delayLineValues, ref delayFeedback) + channelInput * inGain; - state.UpdateLowPassFilter(ref Unsafe.As(ref temp), channelCount); + state.UpdateLowPassFilter(ref Unsafe.As(ref temp), ChannelCount); *((float*)outputBuffers[0] + i) = (channelInput.X * dryGain + delayLineValues.X * outGain) / 64; *((float*)outputBuffers[1] + i) = (channelInput.Y * dryGain + delayLineValues.Y * outGain) / 64; @@ -116,7 +116,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe void ProcessDelayQuadraphonic(ref DelayState state, Span outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - const ushort channelCount = 4; + const ushort ChannelCount = 4; float delayFeedbackBaseGain = state.DelayFeedbackBaseGain; float delayFeedbackCrossGain = state.DelayFeedbackCrossGain; @@ -124,7 +124,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float dryGain = FixedPointHelper.ToFloat(Parameter.DryGain, FixedPointPrecision); float outGain = FixedPointHelper.ToFloat(Parameter.OutGain, FixedPointPrecision); - Matrix4x4 delayFeedback = new Matrix4x4(delayFeedbackBaseGain, delayFeedbackCrossGain, delayFeedbackCrossGain, 0.0f, + Matrix4x4 delayFeedback = new(delayFeedbackBaseGain, delayFeedbackCrossGain, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, delayFeedbackBaseGain, 0.0f, delayFeedbackCrossGain, delayFeedbackCrossGain, 0.0f, delayFeedbackBaseGain, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackBaseGain); @@ -132,25 +132,25 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int i = 0; i < sampleCount; i++) { - Vector4 channelInput = new Vector4 + Vector4 channelInput = new() { X = *((float*)inputBuffers[0] + i) * 64, Y = *((float*)inputBuffers[1] + i) * 64, Z = *((float*)inputBuffers[2] + i) * 64, - W = *((float*)inputBuffers[3] + i) * 64 + W = *((float*)inputBuffers[3] + i) * 64, }; - Vector4 delayLineValues = new Vector4() + Vector4 delayLineValues = new() { X = state.DelayLines[0].Read(), Y = state.DelayLines[1].Read(), Z = state.DelayLines[2].Read(), - W = state.DelayLines[3].Read() + W = state.DelayLines[3].Read(), }; Vector4 temp = MatrixHelper.Transform(ref delayLineValues, ref delayFeedback) + channelInput * inGain; - state.UpdateLowPassFilter(ref Unsafe.As(ref temp), channelCount); + state.UpdateLowPassFilter(ref Unsafe.As(ref temp), ChannelCount); *((float*)outputBuffers[0] + i) = (channelInput.X * dryGain + delayLineValues.X * outGain) / 64; *((float*)outputBuffers[1] + i) = (channelInput.Y * dryGain + delayLineValues.Y * outGain) / 64; @@ -162,7 +162,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe void ProcessDelaySurround(ref DelayState state, Span outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - const ushort channelCount = 6; + const ushort ChannelCount = 6; float feedbackGain = FixedPointHelper.ToFloat(Parameter.FeedbackGain, FixedPointPrecision); float delayFeedbackBaseGain = state.DelayFeedbackBaseGain; @@ -171,7 +171,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command float dryGain = FixedPointHelper.ToFloat(Parameter.DryGain, FixedPointPrecision); float outGain = FixedPointHelper.ToFloat(Parameter.OutGain, FixedPointPrecision); - Matrix6x6 delayFeedback = new Matrix6x6(delayFeedbackBaseGain, 0.0f, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, 0.0f, + Matrix6x6 delayFeedback = new(delayFeedbackBaseGain, 0.0f, delayFeedbackCrossGain, 0.0f, delayFeedbackCrossGain, 0.0f, 0.0f, delayFeedbackBaseGain, delayFeedbackCrossGain, 0.0f, 0.0f, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackCrossGain, delayFeedbackBaseGain, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, feedbackGain, 0.0f, 0.0f, @@ -180,29 +180,29 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int i = 0; i < sampleCount; i++) { - Vector6 channelInput = new Vector6 + Vector6 channelInput = new() { X = *((float*)inputBuffers[0] + i) * 64, Y = *((float*)inputBuffers[1] + i) * 64, Z = *((float*)inputBuffers[2] + i) * 64, W = *((float*)inputBuffers[3] + i) * 64, V = *((float*)inputBuffers[4] + i) * 64, - U = *((float*)inputBuffers[5] + i) * 64 + U = *((float*)inputBuffers[5] + i) * 64, }; - Vector6 delayLineValues = new Vector6 + Vector6 delayLineValues = new() { X = state.DelayLines[0].Read(), Y = state.DelayLines[1].Read(), Z = state.DelayLines[2].Read(), W = state.DelayLines[3].Read(), V = state.DelayLines[4].Read(), - U = state.DelayLines[5].Read() + U = state.DelayLines[5].Read(), }; Vector6 temp = MatrixHelper.Transform(ref delayLineValues, ref delayFeedback) + channelInput * inGain; - state.UpdateLowPassFilter(ref Unsafe.As(ref temp), channelCount); + state.UpdateLowPassFilter(ref Unsafe.As(ref temp), ChannelCount); *((float*)outputBuffers[0] + i) = (channelInput.X * dryGain + delayLineValues.X * outGain) / 64; *((float*)outputBuffers[1] + i) = (channelInput.Y * dryGain + delayLineValues.Y * outGain) / 64; @@ -277,4 +277,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessDelay(context, ref state); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs index 1dba56e6c..ff38f38ca 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopForMixBuffersCommand.cs @@ -55,17 +55,15 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command return -depopValue; } - else + + for (int i = 0; i < sampleCount; i++) { - for (int i = 0; i < sampleCount; i++) - { - depopValue = FloatingPointHelper.MultiplyRoundDown(Decay, depopValue); + depopValue = FloatingPointHelper.MultiplyRoundDown(Decay, depopValue); - buffer[i] += depopValue; - } - - return depopValue; + buffer[i] += depopValue; } + + return depopValue; } public void Process(CommandList context) @@ -89,4 +87,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs index d02f7c121..c64bbdc57 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DepopPrepareCommand.cs @@ -54,4 +54,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DeviceSinkCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DeviceSinkCommand.cs index 27bb34bf3..19afc66f4 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DeviceSinkCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DeviceSinkCommand.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command int channelCount = (int)device.GetChannelCount(); uint bufferCount = Math.Min(device.GetChannelCount(), InputCount); - const int sampleCount = Constants.TargetSampleCount; + const int SampleCount = Constants.TargetSampleCount; uint inputCount; @@ -79,13 +79,13 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command inputCount = bufferCount; } - short[] outputBuffer = new short[inputCount * sampleCount]; + short[] outputBuffer = new short[inputCount * SampleCount]; for (int i = 0; i < bufferCount; i++) { - ReadOnlySpan inputBuffer = GetBuffer(InputBufferIndices[i], sampleCount); + ReadOnlySpan inputBuffer = GetBuffer(InputBufferIndices[i], SampleCount); - for (int j = 0; j < sampleCount; j++) + for (int j = 0; j < SampleCount; j++) { outputBuffer[i + j * channelCount] = PcmHelper.Saturate(inputBuffer[j]); } @@ -100,4 +100,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs index 79cefcc53..8997b0dbd 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/DownMixSurroundToStereoCommand.cs @@ -65,4 +65,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command context.ClearBuffer(OutputBufferIndices[5]); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs index b190cc10d..7af851bdc 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/GroupedBiquadFilterCommand.cs @@ -14,11 +14,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public uint EstimatedProcessingTime { get; set; } - private BiquadFilterParameter[] _parameters; - private Memory _biquadFilterStates; - private int _inputBufferIndex; - private int _outputBufferIndex; - private bool[] _isInitialized; + private readonly BiquadFilterParameter[] _parameters; + private readonly Memory _biquadFilterStates; + private readonly int _inputBufferIndex; + private readonly int _outputBufferIndex; + private readonly bool[] _isInitialized; public GroupedBiquadFilterCommand(int baseIndex, ReadOnlySpan filters, Memory biquadFilterStateMemory, int inputBufferOffset, int outputBufferOffset, ReadOnlySpan isInitialized, int nodeId) { @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs index d281e6e9f..34a62c58d 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/ICommand.cs @@ -17,4 +17,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command return false; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs index a464ad704..3ba0b5884 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion1.cs @@ -1,5 +1,6 @@ using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; @@ -50,13 +51,13 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (Parameter.Status == Server.Effect.UsageState.Invalid) + if (Parameter.Status == UsageState.Invalid) { state = new LimiterState(ref _parameter, WorkBuffer); } - else if (Parameter.Status == Server.Effect.UsageState.New) + else if (Parameter.Status == UsageState.New) { - state.UpdateParameter(ref _parameter); + LimiterState.UpdateParameter(ref _parameter); } } @@ -141,4 +142,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs index 950de97b8..682098670 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/LimiterCommandVersion2.cs @@ -1,6 +1,7 @@ using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -54,13 +55,13 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (Parameter.Status == Server.Effect.UsageState.Invalid) + if (Parameter.Status == UsageState.Invalid) { state = new LimiterState(ref _parameter, WorkBuffer); } - else if (Parameter.Status == Server.Effect.UsageState.New) + else if (Parameter.Status == UsageState.New) { - state.UpdateParameter(ref _parameter); + LimiterState.UpdateParameter(ref _parameter); } } @@ -160,4 +161,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs index 2616bda57..c701f80eb 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixCommand.cs @@ -134,4 +134,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessMix(outputBuffer, inputBuffer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs index 76a1aba25..f77a233e1 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampCommand.cs @@ -65,4 +65,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command State.Span[0].LastSamples[LastSampleIndex] = ProcessMixRamp(outputBuffer, inputBuffer, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs index e348e3588..3c7dd63b2 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/MixRampGroupedCommand.cs @@ -48,7 +48,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private float ProcessMixRampGrouped(Span outputBuffer, ReadOnlySpan inputBuffer, float volume0, float volume1, int sampleCount) + private static float ProcessMixRampGrouped(Span outputBuffer, ReadOnlySpan inputBuffer, float volume0, float volume1, int sampleCount) { float ramp = (volume1 - volume0) / sampleCount; float volume = volume0; @@ -88,4 +88,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs index 7cec7d2ab..585edc058 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmFloatDataSourceCommandVersion1.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -28,7 +30,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public Memory State { get; } public DecodingBehaviour DecodingBehaviour { get; } - public PcmFloatDataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) + public PcmFloatDataSourceCommandVersion1(ref VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -56,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat.PcmFloat, @@ -71,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs index dfe9814fe..6f01219f3 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/PcmInt16DataSourceCommandVersion1.cs @@ -1,7 +1,9 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Server.Voice; using System; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using WaveBuffer = Ryujinx.Audio.Renderer.Common.WaveBuffer; namespace Ryujinx.Audio.Renderer.Dsp.Command { @@ -28,7 +30,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command public Memory State { get; } public DecodingBehaviour DecodingBehaviour { get; } - public PcmInt16DataSourceCommandVersion1(ref Server.Voice.VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) + public PcmInt16DataSourceCommandVersion1(ref VoiceState serverState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { Enabled = true; NodeId = nodeId; @@ -56,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Span outputBuffer = context.GetBuffer(OutputBufferIndex); - DataSourceHelper.WaveBufferInformation info = new DataSourceHelper.WaveBufferInformation + DataSourceHelper.WaveBufferInformation info = new() { SourceSampleRate = SampleRate, SampleFormat = SampleFormat.PcmInt16, @@ -71,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command DataSourceHelper.ProcessWaveBuffers(context.MemoryManager, outputBuffer, ref info, WaveBuffers, ref State.Span[0], context.SampleRate, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs index d3e3f8056..d3d2ee306 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/PerformanceCommand.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { Invalid, Start, - End + End, } public bool Enabled { get; set; } @@ -44,4 +44,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs index 74b53b24b..8cdd4843b 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/Reverb3dCommand.cs @@ -9,21 +9,21 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { public class Reverb3dCommand : ICommand { - private static readonly int[] OutputEarlyIndicesTableMono = new int[20] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableMono = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableMono = new int[1] { 0 }; + private static readonly int[] _outputEarlyIndicesTableMono = new int[20] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableMono = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableMono = new int[1] { 0 }; - private static readonly int[] OutputEarlyIndicesTableStereo = new int[20] { 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableStereo = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableStereo = new int[2] { 0, 1 }; + private static readonly int[] _outputEarlyIndicesTableStereo = new int[20] { 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableStereo = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableStereo = new int[2] { 0, 1 }; - private static readonly int[] OutputEarlyIndicesTableQuadraphonic = new int[20] { 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableQuadraphonic = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _outputEarlyIndicesTableQuadraphonic = new int[20] { 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableQuadraphonic = new int[20] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] OutputEarlyIndicesTableSurround = new int[40] { 4, 5, 0, 5, 0, 5, 1, 5, 1, 5, 1, 5, 1, 5, 2, 5, 2, 5, 2, 5, 1, 5, 1, 5, 1, 5, 0, 5, 0, 5, 0, 5, 0, 5, 3, 5, 3, 5, 3, 5 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableSurround = new int[40] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19 }; - private static readonly int[] TargetOutputFeedbackIndicesTableSurround = new int[6] { 0, 1, 2, 3, -1, 3 }; + private static readonly int[] _outputEarlyIndicesTableSurround = new int[40] { 4, 5, 0, 5, 0, 5, 1, 5, 1, 5, 1, 5, 1, 5, 2, 5, 2, 5, 2, 5, 1, 5, 1, 5, 1, 5, 0, 5, 0, 5, 0, 5, 0, 5, 3, 5, 3, 5, 3, 5 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableSurround = new int[40] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19 }; + private static readonly int[] _targetOutputFeedbackIndicesTableSurround = new int[6] { 0, 1, 2, 3, -1, 3 }; public bool Enabled { get; set; } @@ -73,30 +73,30 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dMono(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableMono, TargetEarlyDelayLineIndicesTableMono, TargetOutputFeedbackIndicesTableMono); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableMono, _targetEarlyDelayLineIndicesTableMono, _targetOutputFeedbackIndicesTableMono); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dStereo(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableStereo, TargetEarlyDelayLineIndicesTableStereo, TargetOutputFeedbackIndicesTableStereo); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableStereo, _targetEarlyDelayLineIndicesTableStereo, _targetOutputFeedbackIndicesTableStereo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dQuadraphonic(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableQuadraphonic, TargetEarlyDelayLineIndicesTableQuadraphonic, TargetOutputFeedbackIndicesTableQuadraphonic); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableQuadraphonic, _targetEarlyDelayLineIndicesTableQuadraphonic, _targetOutputFeedbackIndicesTableQuadraphonic); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ProcessReverb3dSurround(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount) { - ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, OutputEarlyIndicesTableSurround, TargetEarlyDelayLineIndicesTableSurround, TargetOutputFeedbackIndicesTableSurround); + ProcessReverb3dGeneric(ref state, outputBuffers, inputBuffers, sampleCount, _outputEarlyIndicesTableSurround, _targetEarlyDelayLineIndicesTableSurround, _targetOutputFeedbackIndicesTableSurround); } private unsafe void ProcessReverb3dGeneric(ref Reverb3dState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount, ReadOnlySpan outputEarlyIndicesTable, ReadOnlySpan targetEarlyDelayLineIndicesTable, ReadOnlySpan targetOutputFeedbackIndicesTable) { - const int delayLineSampleIndexOffset = 1; + const int DelayLineSampleIndexOffset = 1; bool isMono = Parameter.ChannelCount == 1; bool isSurround = Parameter.ChannelCount == 6; @@ -109,16 +109,16 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { - outputValues.Fill(0); + outputValues.Clear(); - float tapOut = state.PreDelayLine.TapUnsafe(state.ReflectionDelayTime, delayLineSampleIndexOffset); + float tapOut = state.PreDelayLine.TapUnsafe(state.ReflectionDelayTime, DelayLineSampleIndexOffset); for (int i = 0; i < targetEarlyDelayLineIndicesTable.Length; i++) { int earlyDelayIndex = targetEarlyDelayLineIndicesTable[i]; int outputIndex = outputEarlyIndicesTable[earlyDelayIndex]; - float tempTapOut = state.PreDelayLine.TapUnsafe(state.EarlyDelayTime[earlyDelayIndex], delayLineSampleIndexOffset); + float tempTapOut = state.PreDelayLine.TapUnsafe(state.EarlyDelayTime[earlyDelayIndex], DelayLineSampleIndexOffset); outputValues[outputIndex] += tempTapOut * state.EarlyGain[earlyDelayIndex]; } @@ -251,4 +251,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessReverb3d(context, ref state); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs index cd08b838a..f494b3028 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/ReverbCommand.cs @@ -1,5 +1,6 @@ using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter.Effect; +using Ryujinx.Audio.Renderer.Server.Effect; using System; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -8,25 +9,25 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command { public class ReverbCommand : ICommand { - private static readonly int[] OutputEarlyIndicesTableMono = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableMono = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private static readonly int[] OutputIndicesTableMono = new int[4] { 0, 0, 0, 0 }; - private static readonly int[] TargetOutputFeedbackIndicesTableMono = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _outputEarlyIndicesTableMono = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableMono = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private static readonly int[] _outputIndicesTableMono = new int[4] { 0, 0, 0, 0 }; + private static readonly int[] _targetOutputFeedbackIndicesTableMono = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] OutputEarlyIndicesTableStereo = new int[10] { 0, 0, 1, 1, 0, 1, 0, 0, 1, 1 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableStereo = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private static readonly int[] OutputIndicesTableStereo = new int[4] { 0, 0, 1, 1 }; - private static readonly int[] TargetOutputFeedbackIndicesTableStereo = new int[4] { 2, 0, 3, 1 }; + private static readonly int[] _outputEarlyIndicesTableStereo = new int[10] { 0, 0, 1, 1, 0, 1, 0, 0, 1, 1 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableStereo = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private static readonly int[] _outputIndicesTableStereo = new int[4] { 0, 0, 1, 1 }; + private static readonly int[] _targetOutputFeedbackIndicesTableStereo = new int[4] { 2, 0, 3, 1 }; - private static readonly int[] OutputEarlyIndicesTableQuadraphonic = new int[10] { 0, 0, 1, 1, 0, 1, 2, 2, 3, 3 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableQuadraphonic = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private static readonly int[] OutputIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] TargetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _outputEarlyIndicesTableQuadraphonic = new int[10] { 0, 0, 1, 1, 0, 1, 2, 2, 3, 3 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableQuadraphonic = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private static readonly int[] _outputIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; + private static readonly int[] _targetOutputFeedbackIndicesTableQuadraphonic = new int[4] { 0, 1, 2, 3 }; - private static readonly int[] OutputEarlyIndicesTableSurround = new int[20] { 0, 5, 0, 5, 1, 5, 1, 5, 4, 5, 4, 5, 2, 5, 2, 5, 3, 5, 3, 5 }; - private static readonly int[] TargetEarlyDelayLineIndicesTableSurround = new int[20] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 }; - private static readonly int[] OutputIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, 4, 5 }; - private static readonly int[] TargetOutputFeedbackIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, -1, 3 }; + private static readonly int[] _outputEarlyIndicesTableSurround = new int[20] { 0, 5, 0, 5, 1, 5, 1, 5, 4, 5, 4, 5, 2, 5, 2, 5, 3, 5, 3, 5 }; + private static readonly int[] _targetEarlyDelayLineIndicesTableSurround = new int[20] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 }; + private static readonly int[] _outputIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, 4, 5 }; + private static readonly int[] _targetOutputFeedbackIndicesTableSurround = new int[Constants.ChannelCountMax] { 0, 1, 2, 3, -1, 3 }; public bool Enabled { get; set; } @@ -82,10 +83,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableMono, - TargetEarlyDelayLineIndicesTableMono, - TargetOutputFeedbackIndicesTableMono, - OutputIndicesTableMono); + _outputEarlyIndicesTableMono, + _targetEarlyDelayLineIndicesTableMono, + _targetOutputFeedbackIndicesTableMono, + _outputIndicesTableMono); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -95,10 +96,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableStereo, - TargetEarlyDelayLineIndicesTableStereo, - TargetOutputFeedbackIndicesTableStereo, - OutputIndicesTableStereo); + _outputEarlyIndicesTableStereo, + _targetEarlyDelayLineIndicesTableStereo, + _targetOutputFeedbackIndicesTableStereo, + _outputIndicesTableStereo); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -108,10 +109,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableQuadraphonic, - TargetEarlyDelayLineIndicesTableQuadraphonic, - TargetOutputFeedbackIndicesTableQuadraphonic, - OutputIndicesTableQuadraphonic); + _outputEarlyIndicesTableQuadraphonic, + _targetEarlyDelayLineIndicesTableQuadraphonic, + _targetOutputFeedbackIndicesTableQuadraphonic, + _outputIndicesTableQuadraphonic); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -121,10 +122,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command outputBuffers, inputBuffers, sampleCount, - OutputEarlyIndicesTableSurround, - TargetEarlyDelayLineIndicesTableSurround, - TargetOutputFeedbackIndicesTableSurround, - OutputIndicesTableSurround); + _outputEarlyIndicesTableSurround, + _targetEarlyDelayLineIndicesTableSurround, + _targetOutputFeedbackIndicesTableSurround, + _outputIndicesTableSurround); } private unsafe void ProcessReverbGeneric(ref ReverbState state, ReadOnlySpan outputBuffers, ReadOnlySpan inputBuffers, uint sampleCount, ReadOnlySpan outputEarlyIndicesTable, ReadOnlySpan targetEarlyDelayLineIndicesTable, ReadOnlySpan targetOutputFeedbackIndicesTable, ReadOnlySpan outputIndicesTable) @@ -143,7 +144,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command for (int sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) { - outputValues.Fill(0); + outputValues.Clear(); for (int i = 0; i < targetEarlyDelayLineIndicesTable.Length; i++) { @@ -263,11 +264,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command if (IsEffectEnabled) { - if (Parameter.Status == Server.Effect.UsageState.Invalid) + if (Parameter.Status == UsageState.Invalid) { state = new ReverbState(ref _parameter, WorkBuffer, IsLongSizePreDelaySupported); } - else if (Parameter.Status == Server.Effect.UsageState.New) + else if (Parameter.Status == UsageState.New) { state.UpdateParameter(ref _parameter); } @@ -276,4 +277,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessReverb(context, ref state); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs index 0870d59ce..8882500cd 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/UpsampleCommand.cs @@ -67,4 +67,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs index 0628f6d81..5deeb07f1 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeCommand.cs @@ -134,4 +134,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessVolume(outputBuffer, inputBuffer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs index 5c0c88451..bffbcbc63 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Command/VolumeRampCommand.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Command ProcessVolumeRamp(outputBuffer, inputBuffer, (int)context.SampleCount); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs index 721830c9a..98657bd13 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/DataSourceHelper.cs @@ -44,9 +44,9 @@ namespace Ryujinx.Audio.Renderer.Dsp public static void ProcessWaveBuffers(IVirtualMemoryManager memoryManager, Span outputBuffer, ref WaveBufferInformation info, Span wavebuffers, ref VoiceUpdateState voiceState, uint targetSampleRate, int sampleCount) { - const int tempBufferSize = 0x3F00; + const int TempBufferSize = 0x3F00; - Span tempBuffer = stackalloc short[tempBufferSize]; + Span tempBuffer = stackalloc short[TempBufferSize]; float sampleRateRatio = (float)info.SourceSampleRate / targetSampleRate * info.Pitch; @@ -60,11 +60,11 @@ namespace Ryujinx.Audio.Renderer.Dsp int totalNeededSize = (int)MathF.Truncate(fraction + sampleRateRatio * sampleCount); - if (totalNeededSize + pitchMaxLength <= tempBufferSize && totalNeededSize >= 0) + if (totalNeededSize + pitchMaxLength <= TempBufferSize && totalNeededSize >= 0) { int sourceSampleCountToProcess = sampleCount; - int maxSampleCountPerIteration = Math.Min((int)MathF.Truncate((tempBufferSize - fraction) / sampleRateRatio), sampleCount); + int maxSampleCountPerIteration = Math.Min((int)MathF.Truncate((TempBufferSize - fraction) / sampleRateRatio), sampleCount); bool isStarving = false; @@ -76,7 +76,7 @@ namespace Ryujinx.Audio.Renderer.Dsp if (!info.DecodingBehaviour.HasFlag(DecodingBehaviour.SkipPitchAndSampleRateConversion)) { - voiceState.Pitch.AsSpan().Slice(0, pitchMaxLength).CopyTo(tempBuffer); + voiceState.Pitch.AsSpan()[..pitchMaxLength].CopyTo(tempBuffer); tempBufferIndex += pitchMaxLength; } @@ -107,7 +107,7 @@ namespace Ryujinx.Audio.Renderer.Dsp voiceState.LoopContext = memoryManager.Read(waveBuffer.Context); } - Span tempSpan = tempBuffer.Slice(tempBufferIndex + y); + Span tempSpan = tempBuffer[(tempBufferIndex + y)..]; int decodedSampleCount = -1; @@ -168,7 +168,7 @@ namespace Ryujinx.Audio.Renderer.Dsp decodedSampleCount = PcmHelper.Decode(tempSpan, waveBufferPcmFloat, targetSampleStartOffset, targetSampleEndOffset, info.ChannelIndex, info.ChannelCount); break; default: - Logger.Error?.Print(LogClass.AudioRenderer, $"Unsupported sample format " + info.SampleFormat); + Logger.Error?.Print(LogClass.AudioRenderer, "Unsupported sample format " + info.SampleFormat); break; } @@ -220,7 +220,7 @@ namespace Ryujinx.Audio.Renderer.Dsp } } - Span outputSpanInt = MemoryMarshal.Cast(outputBuffer.Slice(i)); + Span outputSpanInt = MemoryMarshal.Cast(outputBuffer[i..]); if (info.DecodingBehaviour.HasFlag(DecodingBehaviour.SkipPitchAndSampleRateConversion)) { @@ -231,9 +231,9 @@ namespace Ryujinx.Audio.Renderer.Dsp } else { - Span tempSpan = tempBuffer.Slice(tempBufferIndex + y); + Span tempSpan = tempBuffer[(tempBufferIndex + y)..]; - tempSpan.Slice(0, sampleCountToDecode - y).Fill(0); + tempSpan[..(sampleCountToDecode - y)].Clear(); ToFloat(outputBuffer, outputSpanInt, sampleCountToProcess); @@ -463,4 +463,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs index 37e066bf0..7253fdc92 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DecayDelay.cs @@ -49,4 +49,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return _delayLine.Tap(sampleIndex); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs index 56890ebe8..8a3590a20 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLine.cs @@ -4,8 +4,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect { public class DelayLine : IDelayLine { - private float[] _workBuffer; - private uint _sampleRate; + private readonly float[] _workBuffer; + private readonly uint _sampleRate; private uint _currentSampleIndex; private uint _lastSampleIndex; @@ -75,4 +75,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return TapUnsafe(sampleIndex, -1); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs index a2ac9d265..ed8e7cfe0 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/DelayLineReverb3d.cs @@ -4,8 +4,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect { public class DelayLine3d : IDelayLine { - private float[] _workBuffer; - private uint _sampleRate; + private readonly float[] _workBuffer; + private readonly uint _sampleRate; private uint _currentSampleIndex; private uint _lastSampleIndex; @@ -73,4 +73,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return TapUnsafe(sampleIndex, -1); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs index 78e46bf96..253400a5a 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/ExponentialMovingAverage.cs @@ -1,6 +1,4 @@ -using System.Runtime.CompilerServices; - -namespace Ryujinx.Audio.Renderer.Dsp.Effect +namespace Ryujinx.Audio.Renderer.Dsp.Effect { public struct ExponentialMovingAverage { @@ -11,7 +9,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect _mean = mean; } - public float Read() + public readonly float Read() { return _mean; } diff --git a/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs b/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs index fd902525e..b408e294d 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/Effect/IDelayLine.cs @@ -34,4 +34,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.Effect return (uint)MathF.Round(sampleRate * delayTime); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs index 280e47c0c..d519de333 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/FixedPointHelper.cs @@ -36,4 +36,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return ToInt(value + half, qBits); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs index 6645e20a3..b231dbb6a 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/FloatingPointHelper.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection.Metadata; using System.Runtime.CompilerServices; namespace Ryujinx.Audio.Renderer.Dsp @@ -39,7 +38,8 @@ namespace Ryujinx.Audio.Renderer.Dsp { return 1.0f; } - else if (x <= -5.3f) + + if (x <= -5.3f) { return 0.0f; } @@ -112,4 +112,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return MathF.Sin(DegreesToRadians(value)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs index 0233a8d71..d209c515b 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/PcmHelper.cs @@ -1,5 +1,4 @@ using System; -using System.Numerics; using System.Runtime.CompilerServices; namespace Ryujinx.Audio.Renderer.Dsp @@ -62,7 +61,7 @@ namespace Ryujinx.Audio.Renderer.Dsp { for (int i = 0; i < input.Length; i++) { - output[i] = ((int)input[i]) << 16; + output[i] = input[i] << 16; } } @@ -127,4 +126,4 @@ namespace Ryujinx.Audio.Renderer.Dsp return (short)value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs index 7873c4d27..e44e9f41e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/ResamplerHelper.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; @@ -11,8 +10,7 @@ namespace Ryujinx.Audio.Renderer.Dsp public static class ResamplerHelper { #region "Default Quality Lookup Tables" - private static short[] _normalCurveLut0 = new short[] - { + private static readonly short[] _normalCurveLut0 = { 6600, 19426, 6722, 3, 6479, 19424, 6845, 9, 6359, 19419, 6968, 15, 6239, 19412, 7093, 22, 6121, 19403, 7219, 28, 6004, 19391, 7345, 34, 5888, 19377, 7472, 41, 5773, 19361, 7600, 48, 5659, 19342, 7728, 55, 5546, 19321, 7857, 62, 5434, 19298, 7987, 69, 5323, 19273, 8118, 77, @@ -44,11 +42,10 @@ namespace Ryujinx.Audio.Renderer.Dsp 109, 8646, 19148, 4890, 101, 8513, 19183, 4997, 92, 8381, 19215, 5104, 84, 8249, 19245, 5213, 77, 8118, 19273, 5323, 69, 7987, 19298, 5434, 62, 7857, 19321, 5546, 55, 7728, 19342, 5659, 48, 7600, 19361, 5773, 41, 7472, 19377, 5888, 34, 7345, 19391, 6004, 28, 7219, 19403, 6121, - 22, 7093, 19412, 6239, 15, 6968, 19419, 6359, 9, 6845, 19424, 6479, 3, 6722, 19426, 6600 + 22, 7093, 19412, 6239, 15, 6968, 19419, 6359, 9, 6845, 19424, 6479, 3, 6722, 19426, 6600, }; - private static short[] _normalCurveLut1 = new short[] - { + private static readonly short[] _normalCurveLut1 = { -68, 32639, 69, -5, -200, 32630, 212, -15, -328, 32613, 359, -26, -450, 32586, 512, -36, -568, 32551, 669, -47, -680, 32507, 832, -58, -788, 32454, 1000, -69, -891, 32393, 1174, -80, -990, 32323, 1352, -92, -1084, 32244, 1536, -103, -1173, 32157, 1724, -115, -1258, 32061, 1919, -128, @@ -80,11 +77,10 @@ namespace Ryujinx.Audio.Renderer.Dsp -180, 2747, 31593, -1554, -167, 2532, 31723, -1486, -153, 2322, 31844, -1414, -140, 2118, 31956, -1338, -128, 1919, 32061, -1258, -115, 1724, 32157, -1173, -103, 1536, 32244, -1084, -92, 1352, 32323, -990, -80, 1174, 32393, -891, -69, 1000, 32454, -788, -58, 832, 32507, -680, -47, 669, 32551, -568, - -36, 512, 32586, -450, -26, 359, 32613, -328, -15, 212, 32630, -200, -5, 69, 32639, -68 + -36, 512, 32586, -450, -26, 359, 32613, -328, -15, 212, 32630, -200, -5, 69, 32639, -68, }; - private static short[] _normalCurveLut2 = new short[] - { + private static readonly short[] _normalCurveLut2 = { 3195, 26287, 3329, -32, 3064, 26281, 3467, -34, 2936, 26270, 3608, -38, 2811, 26253, 3751, -42, 2688, 26230, 3897, -46, 2568, 26202, 4046, -50, 2451, 26169, 4199, -54, 2338, 26130, 4354, -58, 2227, 26085, 4512, -63, 2120, 26035, 4673, -67, 2015, 25980, 4837, -72, 1912, 25919, 5004, -76, @@ -116,13 +112,12 @@ namespace Ryujinx.Audio.Renderer.Dsp -98, 5701, 25621, 1531, -92, 5522, 25704, 1622, -87, 5347, 25780, 1716, -81, 5174, 25852, 1813, -76, 5004, 25919, 1912, -72, 4837, 25980, 2015, -67, 4673, 26035, 2120, -63, 4512, 26085, 2227, -58, 4354, 26130, 2338, -54, 4199, 26169, 2451, -50, 4046, 26202, 2568, -46, 3897, 26230, 2688, - -42, 3751, 26253, 2811, -38, 3608, 26270, 2936, -34, 3467, 26281, 3064, -32, 3329, 26287, 3195 + -42, 3751, 26253, 2811, -38, 3608, 26270, 2936, -34, 3467, 26281, 3064, -32, 3329, 26287, 3195, }; #endregion #region "High Quality Lookup Tables" - private static short[] _highCurveLut0 = new short[] - { + private static readonly short[] _highCurveLut0 = { -582, -23, 8740, 16386, 8833, 8, -590, 0, -573, -54, 8647, 16385, 8925, 40, -598, -1, -565, -84, 8555, 16383, 9018, 72, -606, -1, -557, -113, 8462, 16379, 9110, 105, -614, -2, -549, -142, 8370, 16375, 9203, 139, -622, -2, -541, -170, 8277, 16369, 9295, 173, -630, -3, @@ -189,8 +184,7 @@ namespace Ryujinx.Audio.Renderer.Dsp -1, -598, 40, 8925, 16385, 8647, -54, -573, 0, -590, 8, 8833, 16386, 8740, -23, -582, }; - private static short[] _highCurveLut1 = new short[] - { + private static readonly short[] _highCurveLut1 = { -12, 47, -134, 32767, 81, -16, 2, 0, -26, 108, -345, 32760, 301, -79, 17, -1, -40, 168, -552, 32745, 526, -144, 32, -2, -53, 226, -753, 32723, 755, -210, 47, -3, -66, 284, -950, 32694, 989, -277, 63, -5, -78, 340, -1143, 32658, 1226, -346, 79, -6, @@ -257,8 +251,7 @@ namespace Ryujinx.Audio.Renderer.Dsp -1, 17, -79, 301, 32760, -345, 108, -26, 0, 2, -16, 81, 32767, -134, 47, -12, }; - private static short[] _highCurveLut2 = new short[] - { + private static readonly short[] _highCurveLut2 = { 418, -2538, 6118, 24615, 6298, -2563, 417, 0, 420, -2512, 5939, 24611, 6479, -2588, 415, 1, 421, -2485, 5761, 24605, 6662, -2612, 412, 2, 422, -2458, 5585, 24595, 6846, -2635, 409, 3, 423, -2430, 5410, 24582, 7030, -2658, 406, 4, 423, -2402, 5236, 24565, 7216, -2680, 403, 5, @@ -326,13 +319,13 @@ namespace Ryujinx.Audio.Renderer.Dsp }; #endregion - private static float[] _normalCurveLut0F; - private static float[] _normalCurveLut1F; - private static float[] _normalCurveLut2F; + private static readonly float[] _normalCurveLut0F; + private static readonly float[] _normalCurveLut1F; + private static readonly float[] _normalCurveLut2F; - private static float[] _highCurveLut0F; - private static float[] _highCurveLut1F; - private static float[] _highCurveLut2F; + private static readonly float[] _highCurveLut0F; + private static readonly float[] _highCurveLut1F; + private static readonly float[] _highCurveLut2F; static ResamplerHelper() { @@ -373,7 +366,8 @@ namespace Ryujinx.Audio.Renderer.Dsp { return _normalCurveLut1F; } - else if (ratio > 1.333313f) + + if (ratio > 1.333313f) { return _normalCurveLut0F; } @@ -514,7 +508,8 @@ namespace Ryujinx.Audio.Renderer.Dsp { return _highCurveLut1F; } - else if (ratio > 1.333313f) + + if (ratio > 1.333313f) { return _highCurveLut0F; } @@ -601,4 +596,4 @@ namespace Ryujinx.Audio.Renderer.Dsp } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs index 821a135ef..f9ef201f2 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/AdpcmLoopContext.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State public short History0; public short History1; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs index 4e8d11e4c..97bbc80cc 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/AuxiliaryBufferHeader.cs @@ -71,4 +71,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State public AuxiliaryBufferInfo CpuBufferInfo; public AuxiliaryBufferInfo DspBufferInfo; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs index 4220e6d51..f9a32b3f9 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/BiquadFilterState.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State public float State2; public float State3; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs index 2a1e7f834..c56fa078a 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/DelayState.cs @@ -64,4 +64,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs index 0560757c9..80d1cb62e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/LimiterState.cs @@ -20,12 +20,12 @@ namespace Ryujinx.Audio.Renderer.Dsp.State DetectorAverage.AsSpan().Fill(new ExponentialMovingAverage(0.0f)); CompressionGainAverage.AsSpan().Fill(new ExponentialMovingAverage(1.0f)); - DelayedSampleBufferPosition.AsSpan().Fill(0); - DelayedSampleBuffer.AsSpan().Fill(0.0f); + DelayedSampleBufferPosition.AsSpan().Clear(); + DelayedSampleBuffer.AsSpan().Clear(); UpdateParameter(ref parameter); } - public void UpdateParameter(ref LimiterParameter parameter) { } + public static void UpdateParameter(ref LimiterParameter parameter) { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs index c06466031..5056b750e 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/Reverb3dState.cs @@ -6,11 +6,11 @@ namespace Ryujinx.Audio.Renderer.Dsp.State { public class Reverb3dState { - private readonly float[] FdnDelayMinTimes = new float[4] { 5.0f, 6.0f, 13.0f, 14.0f }; - private readonly float[] FdnDelayMaxTimes = new float[4] { 45.704f, 82.782f, 149.94f, 271.58f }; - private readonly float[] DecayDelayMaxTimes1 = new float[4] { 17.0f, 13.0f, 9.0f, 7.0f }; - private readonly float[] DecayDelayMaxTimes2 = new float[4] { 19.0f, 11.0f, 10.0f, 6.0f }; - private readonly float[] EarlyDelayTimes = new float[20] { 0.017136f, 0.059154f, 0.16173f, 0.39019f, 0.42526f, 0.45541f, 0.68974f, 0.74591f, 0.83384f, 0.8595f, 0.0f, 0.075024f, 0.16879f, 0.2999f, 0.33744f, 0.3719f, 0.59901f, 0.71674f, 0.81786f, 0.85166f }; + private readonly float[] _fdnDelayMinTimes = new float[4] { 5.0f, 6.0f, 13.0f, 14.0f }; + private readonly float[] _fdnDelayMaxTimes = new float[4] { 45.704f, 82.782f, 149.94f, 271.58f }; + private readonly float[] _decayDelayMaxTimes1 = new float[4] { 17.0f, 13.0f, 9.0f, 7.0f }; + private readonly float[] _decayDelayMaxTimes2 = new float[4] { 19.0f, 11.0f, 10.0f, 6.0f }; + private readonly float[] _earlyDelayTimes = new float[20] { 0.017136f, 0.059154f, 0.16173f, 0.39019f, 0.42526f, 0.45541f, 0.68974f, 0.74591f, 0.83384f, 0.8595f, 0.0f, 0.075024f, 0.16879f, 0.2999f, 0.33744f, 0.3719f, 0.59901f, 0.71674f, 0.81786f, 0.85166f }; public readonly float[] EarlyGain = new float[20] { 0.67096f, 0.61027f, 1.0f, 0.35680f, 0.68361f, 0.65978f, 0.51939f, 0.24712f, 0.45945f, 0.45021f, 0.64196f, 0.54879f, 0.92925f, 0.38270f, 0.72867f, 0.69794f, 0.5464f, 0.24563f, 0.45214f, 0.44042f }; public IDelayLine[] FdnDelayLines { get; } @@ -46,9 +46,9 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < 4; i++) { - FdnDelayLines[i] = new DelayLine3d(sampleRate, FdnDelayMaxTimes[i]); - DecayDelays1[i] = new DecayDelay(new DelayLine3d(sampleRate, DecayDelayMaxTimes1[i])); - DecayDelays2[i] = new DecayDelay(new DelayLine3d(sampleRate, DecayDelayMaxTimes2[i])); + FdnDelayLines[i] = new DelayLine3d(sampleRate, _fdnDelayMaxTimes[i]); + DecayDelays1[i] = new DecayDelay(new DelayLine3d(sampleRate, _decayDelayMaxTimes1[i])); + DecayDelays2[i] = new DecayDelay(new DelayLine3d(sampleRate, _decayDelayMaxTimes2[i])); } PreDelayLine = new DelayLine3d(sampleRate, 400); @@ -63,7 +63,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State EarlyDelayTime = new uint[20]; DryGain = parameter.DryGain; - PreviousFeedbackOutputDecayed.AsSpan().Fill(0); + PreviousFeedbackOutputDecayed.AsSpan().Clear(); PreviousPreDelayValue = 0; EarlyReflectionsGain = FloatingPointHelper.Pow10(Math.Min(parameter.RoomGain + parameter.ReflectionsGain, 5000.0f) / 2000.0f); @@ -91,7 +91,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < FdnDelayLines.Length; i++) { - FdnDelayLines[i].SetDelay(FdnDelayMinTimes[i] + (parameter.Density / 100 * (FdnDelayMaxTimes[i] - FdnDelayMinTimes[i]))); + FdnDelayLines[i].SetDelay(_fdnDelayMinTimes[i] + (parameter.Density / 100 * (_fdnDelayMaxTimes[i] - _fdnDelayMinTimes[i]))); uint tempSampleCount = FdnDelayLines[i].CurrentSampleCount + DecayDelays1[i].CurrentSampleCount + DecayDelays2[i].CurrentSampleCount; @@ -111,9 +111,9 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < EarlyDelayTime.Length; i++) { - uint sampleCount = Math.Min(IDelayLine.GetSampleCount(sampleRate, (parameter.ReflectionDelay * 1000.0f) + (EarlyDelayTimes[i] * 1000.0f * ((parameter.ReverbDelayTime * 0.9998f) + 0.02f))), PreDelayLine.SampleCountMax); + uint sampleCount = Math.Min(IDelayLine.GetSampleCount(sampleRate, (parameter.ReflectionDelay * 1000.0f) + (_earlyDelayTimes[i] * 1000.0f * ((parameter.ReverbDelayTime * 0.9998f) + 0.02f))), PreDelayLine.SampleCountMax); EarlyDelayTime[i] = sampleCount; } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs b/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs index 1ffabe05c..2f574f475 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/State/ReverbState.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State { public class ReverbState { - private static readonly float[] FdnDelayTimes = new float[20] + private static readonly float[] _fdnDelayTimes = new float[20] { // Room 53.953247f, 79.192566f, 116.238770f, 130.615295f, @@ -21,7 +21,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State 53.953247f, 79.192566f, 116.238770f, 170.615295f, }; - private static readonly float[] DecayDelayTimes = new float[20] + private static readonly float[] _decayDelayTimes = new float[20] { // Room 7f, 9f, 13f, 17f, @@ -35,7 +35,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State 7f, 9f, 13f, 17f, }; - private static readonly float[] EarlyDelayTimes = new float[50] + private static readonly float[] _earlyDelayTimes = new float[50] { // Room 0.0f, 3.5f, 2.8f, 3.9f, 2.7f, 13.4f, 7.9f, 8.4f, 9.9f, 12.0f, @@ -46,10 +46,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.State // Cathedral 33.1f, 43.3f, 22.8f, 37.9f, 14.9f, 35.3f, 17.9f, 34.2f, 0.0f, 43.3f, // Disabled - 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }; - private static readonly float[] EarlyGainBase = new float[50] + private static readonly float[] _earlyGainBase = new float[50] { // Room 0.70f, 0.68f, 0.70f, 0.68f, 0.70f, 0.68f, 0.70f, 0.68f, 0.68f, 0.68f, @@ -60,10 +60,10 @@ namespace Ryujinx.Audio.Renderer.Dsp.State // Cathedral 0.93f, 0.92f, 0.87f, 0.86f, 0.94f, 0.81f, 0.80f, 0.77f, 0.76f, 0.65f, // Disabled - 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f + 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, }; - private static readonly float[] PreDelayTimes = new float[5] + private static readonly float[] _preDelayTimes = new float[5] { // Room 12.5f, @@ -74,7 +74,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State // Cathedral 50.0f, // Disabled - 0.0f + 0.0f, }; public DelayLine[] FdnDelayLines { get; } @@ -93,14 +93,14 @@ namespace Ryujinx.Audio.Renderer.Dsp.State private const int FixedPointPrecision = 14; - private ReadOnlySpan GetFdnDelayTimesByLateMode(ReverbLateMode lateMode) + private static ReadOnlySpan GetFdnDelayTimesByLateMode(ReverbLateMode lateMode) { - return FdnDelayTimes.AsSpan((int)lateMode * 4, 4); + return _fdnDelayTimes.AsSpan((int)lateMode * 4, 4); } - private ReadOnlySpan GetDecayDelayTimesByLateMode(ReverbLateMode lateMode) + private static ReadOnlySpan GetDecayDelayTimesByLateMode(ReverbLateMode lateMode) { - return DecayDelayTimes.AsSpan((int)lateMode * 4, 4); + return _decayDelayTimes.AsSpan((int)lateMode * 4, 4); } public ReverbState(ref ReverbParameter parameter, ulong workBuffer, bool isLongSizePreDelaySupported) @@ -148,8 +148,8 @@ namespace Ryujinx.Audio.Renderer.Dsp.State for (int i = 0; i < 10; i++) { - EarlyDelayTime[i] = Math.Min(IDelayLine.GetSampleCount(sampleRate, EarlyDelayTimes[i] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax) + 1; - EarlyGain[i] = EarlyGainBase[i] * earlyGain; + EarlyDelayTime[i] = Math.Min(IDelayLine.GetSampleCount(sampleRate, _earlyDelayTimes[i] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax) + 1; + EarlyGain[i] = _earlyGainBase[i] * earlyGain; } if (parameter.ChannelCount == 2) @@ -158,7 +158,7 @@ namespace Ryujinx.Audio.Renderer.Dsp.State EarlyGain[5] = EarlyGain[5] * 0.5f; } - PreDelayLineDelayTime = Math.Min(IDelayLine.GetSampleCount(sampleRate, PreDelayTimes[(int)parameter.EarlyMode] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax); + PreDelayLineDelayTime = Math.Min(IDelayLine.GetSampleCount(sampleRate, _preDelayTimes[(int)parameter.EarlyMode] + preDelayTimeInMilliseconds), PreDelayLine.SampleCountMax); ReadOnlySpan fdnDelayTimes = GetFdnDelayTimesByLateMode(parameter.LateMode); ReadOnlySpan decayDelayTimes = GetDecayDelayTimesByLateMode(parameter.LateMode); @@ -201,4 +201,4 @@ namespace Ryujinx.Audio.Renderer.Dsp.State } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs b/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs index 6cdab5a7b..5732cdb21 100644 --- a/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Dsp/UpsamplerHelper.cs @@ -13,11 +13,11 @@ namespace Ryujinx.Audio.Renderer.Dsp private const int FilterBankLength = 20; // Bank0 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; private const int Bank0CenterIndex = 9; - private static readonly Array20 Bank1 = PrecomputeFilterBank(1.0f / 6.0f); - private static readonly Array20 Bank2 = PrecomputeFilterBank(2.0f / 6.0f); - private static readonly Array20 Bank3 = PrecomputeFilterBank(3.0f / 6.0f); - private static readonly Array20 Bank4 = PrecomputeFilterBank(4.0f / 6.0f); - private static readonly Array20 Bank5 = PrecomputeFilterBank(5.0f / 6.0f); + private static readonly Array20 _bank1 = PrecomputeFilterBank(1.0f / 6.0f); + private static readonly Array20 _bank2 = PrecomputeFilterBank(2.0f / 6.0f); + private static readonly Array20 _bank3 = PrecomputeFilterBank(3.0f / 6.0f); + private static readonly Array20 _bank4 = PrecomputeFilterBank(4.0f / 6.0f); + private static readonly Array20 _bank5 = PrecomputeFilterBank(5.0f / 6.0f); private static Array20 PrecomputeFilterBank(float offset) { @@ -32,14 +32,14 @@ namespace Ryujinx.Audio.Renderer.Dsp float BlackmanWindow(float x) { - const float a = 0.18f; - const float a0 = 0.5f - 0.5f * a; - const float a1 = -0.5f; - const float a2 = 0.5f * a; - return a0 + a1 * MathF.Cos(2 * MathF.PI * x) + a2 * MathF.Cos(4 * MathF.PI * x); + const float A = 0.18f; + const float A0 = 0.5f - 0.5f * A; + const float A1 = -0.5f; + const float A2 = 0.5f * A; + return A0 + A1 * MathF.Cos(2 * MathF.PI * x) + A2 * MathF.Cos(4 * MathF.PI * x); } - - Array20 result = new Array20(); + + Array20 result = new(); for (int i = 0; i < FilterBankLength; i++) { @@ -58,10 +58,10 @@ namespace Ryujinx.Audio.Renderer.Dsp { state.Scale = inputSampleCount switch { - 40 => 6.0f, - 80 => 3.0f, + 40 => 6.0f, + 80 => 3.0f, 160 => 1.5f, - _ => throw new ArgumentOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(inputSampleCount), inputSampleCount, null), }; state.Initialized = true; } @@ -105,14 +105,14 @@ namespace Ryujinx.Audio.Renderer.Dsp [MethodImpl(MethodImplOptions.AggressiveInlining)] void NextInput(ref UpsamplerBufferState state, float input) { - state.History.AsSpan().Slice(1).CopyTo(state.History.AsSpan()); + state.History.AsSpan()[1..].CopyTo(state.History.AsSpan()); state.History[HistoryLength - 1] = input; } int inputBufferIndex = 0; switch (state.Scale) - { + { case 6.0f: for (int i = 0; i < outputSampleCount; i++) { @@ -123,19 +123,19 @@ namespace Ryujinx.Audio.Renderer.Dsp outputBuffer[i] = state.History[Bank0CenterIndex]; break; case 1: - outputBuffer[i] = DoFilterBank(ref state, Bank1); + outputBuffer[i] = DoFilterBank(ref state, _bank1); break; case 2: - outputBuffer[i] = DoFilterBank(ref state, Bank2); + outputBuffer[i] = DoFilterBank(ref state, _bank2); break; case 3: - outputBuffer[i] = DoFilterBank(ref state, Bank3); + outputBuffer[i] = DoFilterBank(ref state, _bank3); break; case 4: - outputBuffer[i] = DoFilterBank(ref state, Bank4); + outputBuffer[i] = DoFilterBank(ref state, _bank4); break; case 5: - outputBuffer[i] = DoFilterBank(ref state, Bank5); + outputBuffer[i] = DoFilterBank(ref state, _bank5); break; } @@ -152,10 +152,10 @@ namespace Ryujinx.Audio.Renderer.Dsp outputBuffer[i] = state.History[Bank0CenterIndex]; break; case 1: - outputBuffer[i] = DoFilterBank(ref state, Bank2); + outputBuffer[i] = DoFilterBank(ref state, _bank2); break; case 2: - outputBuffer[i] = DoFilterBank(ref state, Bank4); + outputBuffer[i] = DoFilterBank(ref state, _bank4); break; } @@ -173,11 +173,11 @@ namespace Ryujinx.Audio.Renderer.Dsp outputBuffer[i] = state.History[Bank0CenterIndex]; break; case 1: - outputBuffer[i] = DoFilterBank(ref state, Bank4); + outputBuffer[i] = DoFilterBank(ref state, _bank4); break; case 2: NextInput(ref state, inputBuffer[inputBufferIndex++]); - outputBuffer[i] = DoFilterBank(ref state, Bank2); + outputBuffer[i] = DoFilterBank(ref state, _bank2); break; } @@ -185,8 +185,8 @@ namespace Ryujinx.Audio.Renderer.Dsp } break; default: - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(state), state.Scale, null); } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs b/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs index 359cd4c02..491a05c86 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/AudioRendererConfiguration.cs @@ -60,7 +60,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused /// - private byte _reserved; + private readonly byte _reserved; /// /// The target rendering device. @@ -96,4 +96,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public int Revision; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs index aba7dcd61..5a0565dc6 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/BehaviourErrorInfoOutStatus.cs @@ -27,4 +27,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs index ef86015fe..f1492b0b1 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/BiquadFilterParameter.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private byte _reserved; + private readonly byte _reserved; /// /// Biquad filter numerator (b0, b1, b2). @@ -31,4 +31,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// a0 = 1 public Array2 Denominator; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs index 36f286775..65f265a32 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/AuxiliaryBufferParameter.cs @@ -81,4 +81,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// This is unused. public uint MixBufferSampleCount; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs index 73e0e9bbc..b12a941a5 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BiquadFilterEffectParameter.cs @@ -41,4 +41,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// public UsageState Status; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs index b03559eba..49b70e501 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/BufferMixerParameter.cs @@ -29,4 +29,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// public uint MixesCount; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs index 0be376088..1a936b0df 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/CompressorParameter.cs @@ -98,7 +98,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -107,7 +107,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs index 72332c170..99c97d9d9 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/DelayParameter.cs @@ -84,7 +84,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -93,9 +93,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs index 0bce94a27..23ccb8c88 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterParameter.cs @@ -115,13 +115,13 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// /// Reserved/padding. /// - private byte _reserved; + private readonly byte _reserved; /// /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -130,9 +130,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs index f353f18d1..97e2f39fc 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/LimiterStatistics.cs @@ -24,8 +24,8 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// public void Reset() { - InputMax.AsSpan().Fill(0.0f); + InputMax.AsSpan().Clear(); CompressionGainMin.AsSpan().Fill(1.0f); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs index c78ce5951..d2cd78707 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/Reverb3dParameter.cs @@ -33,7 +33,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// /// Reserved/unused. /// - private uint _reserved; + private readonly uint _reserved; /// /// The target sample rate. @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -119,9 +119,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs index baf049fbd..51ab156d2 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Effect/ReverbParameter.cs @@ -102,7 +102,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountValid() + public readonly bool IsChannelCountValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCount); } @@ -111,9 +111,9 @@ namespace Ryujinx.Audio.Renderer.Parameter.Effect /// Check if the is valid. /// /// Returns true if the is valid. - public bool IsChannelCountMaxValid() + public readonly bool IsChannelCountMaxValid() { return EffectInParameterVersion1.IsChannelCountValid(ChannelCountMax); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs index e5419f70a..46686e3b4 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion1.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private byte _reserved1; + private readonly byte _reserved1; /// /// The target mix id of the effect. @@ -58,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _reserved2; + private readonly uint _reserved2; /// /// Specific data storage. @@ -70,19 +70,19 @@ namespace Ryujinx.Audio.Renderer.Parameter public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); - EffectType IEffectInParameter.Type => Type; + readonly EffectType IEffectInParameter.Type => Type; - bool IEffectInParameter.IsNew => IsNew; + readonly bool IEffectInParameter.IsNew => IsNew; - bool IEffectInParameter.IsEnabled => IsEnabled; + readonly bool IEffectInParameter.IsEnabled => IsEnabled; - int IEffectInParameter.MixId => MixId; + readonly int IEffectInParameter.MixId => MixId; - ulong IEffectInParameter.BufferBase => BufferBase; + readonly ulong IEffectInParameter.BufferBase => BufferBase; - ulong IEffectInParameter.BufferSize => BufferSize; + readonly ulong IEffectInParameter.BufferSize => BufferSize; - uint IEffectInParameter.ProcessingOrder => ProcessingOrder; + readonly uint IEffectInParameter.ProcessingOrder => ProcessingOrder; /// /// Check if the given channel count is valid. @@ -94,4 +94,4 @@ namespace Ryujinx.Audio.Renderer.Parameter return channelCount == 1 || channelCount == 2 || channelCount == 4 || channelCount == 6; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs index 250012d16..3854c7148 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectInParameterVersion2.cs @@ -31,7 +31,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private byte _reserved1; + private readonly byte _reserved1; /// /// The target mix id of the effect. @@ -58,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _reserved2; + private readonly uint _reserved2; /// /// Specific data storage. @@ -70,19 +70,19 @@ namespace Ryujinx.Audio.Renderer.Parameter public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); - EffectType IEffectInParameter.Type => Type; + readonly EffectType IEffectInParameter.Type => Type; - bool IEffectInParameter.IsNew => IsNew; + readonly bool IEffectInParameter.IsNew => IsNew; - bool IEffectInParameter.IsEnabled => IsEnabled; + readonly bool IEffectInParameter.IsEnabled => IsEnabled; - int IEffectInParameter.MixId => MixId; + readonly int IEffectInParameter.MixId => MixId; - ulong IEffectInParameter.BufferBase => BufferBase; + readonly ulong IEffectInParameter.BufferBase => BufferBase; - ulong IEffectInParameter.BufferSize => BufferSize; + readonly ulong IEffectInParameter.BufferSize => BufferSize; - uint IEffectInParameter.ProcessingOrder => ProcessingOrder; + readonly uint IEffectInParameter.ProcessingOrder => ProcessingOrder; /// /// Check if the given channel count is valid. @@ -94,4 +94,4 @@ namespace Ryujinx.Audio.Renderer.Parameter return channelCount == 1 || channelCount == 2 || channelCount == 4 || channelCount == 6; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs index 5e6a33ace..3c3e95538 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion1.cs @@ -18,6 +18,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed byte _reserved[15]; - EffectState IEffectOutStatus.State { get => State; set => State = value; } + EffectState IEffectOutStatus.State { readonly get => State; set => State = value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs index f2c9768b3..ee058d3ae 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectOutStatusVersion2.cs @@ -23,6 +23,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public EffectResultState ResultState; - EffectState IEffectOutStatus.State { get => State; set => State = value; } + EffectState IEffectOutStatus.State { readonly get => State; set => State = value; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs index bd96c22bf..b3a4bae12 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectResultState.cs @@ -23,4 +23,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs b/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs index 911ba6d84..c4d06f122 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/EffectState.cs @@ -13,6 +13,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// The effect is disabled. /// - Disabled = 4 + Disabled = 4, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs index bdd1ca45e..703c3e6db 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/IEffectInParameter.cs @@ -50,4 +50,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Span SpecificData { get; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs index a5addbcb7..74d132209 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/IEffectOutStatus.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// EffectState State { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs index 242e3843c..602508589 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolInParameter.cs @@ -30,4 +30,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs index 29a6e261f..a78937d01 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MemoryPoolOutStatus.cs @@ -19,4 +19,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs b/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs index c0954cda0..733b5ad76 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MixInParameterDirtyOnlyUpdate.cs @@ -24,4 +24,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed byte _reserved[24]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs index 5b9a969a0..2eec04a21 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/MixParameter.cs @@ -41,7 +41,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private ushort _reserved1; + private readonly ushort _reserved1; /// /// The id of the mix. @@ -61,7 +61,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private ulong _reserved2; + private readonly ulong _reserved2; /// /// Mix buffer volumes storage. @@ -81,7 +81,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _reserved3; + private readonly uint _reserved3; [StructLayout(LayoutKind.Sequential, Size = 4 * Constants.MixBufferCountMax * Constants.MixBufferCountMax, Pack = 1)] private struct MixVolumeArray { } @@ -92,4 +92,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Used when no splitter id is specified. public Span MixBufferVolume => SpanHelpers.AsSpan(ref _mixBufferVolumeArray); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs index 0f9a3aa3e..806f7fa89 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceInParameter.cs @@ -18,4 +18,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Performance /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs index 64bbe080a..839d6eb6b 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Performance/PerformanceOutStatus.cs @@ -18,4 +18,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Performance /// private unsafe fixed uint _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs index a42ea833f..c97ce2965 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/RendererInfoOutStatus.cs @@ -16,6 +16,6 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/Unused. /// - private ulong _reserved; + private readonly ulong _reserved; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs index 7c02d65ff..0d4b276ef 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Sink/CircularBufferParameter.cs @@ -2,7 +2,6 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; using Ryujinx.Common.Memory; using System.Runtime.InteropServices; - using CpuAddress = System.UInt64; namespace Ryujinx.Audio.Renderer.Parameter.Sink @@ -41,7 +40,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// The target . /// - /// Only is supported. + /// Only is supported. public SampleFormat SampleFormat; /// @@ -57,6 +56,6 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// Reserved/padding. /// - private ushort _reserved2; + private readonly ushort _reserved2; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs index abeadaccf..652d02a63 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/Sink/DeviceParameter.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// Reserved/padding. /// - private byte _padding; + private readonly byte _padding; /// /// The total count of channels to output to the device. @@ -34,7 +34,7 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// /// Reserved/padding. /// - private byte _reserved; + private readonly byte _reserved; /// /// Set to true if the user controls Surround to Stereo downmixing coefficients. @@ -55,4 +55,4 @@ namespace Ryujinx.Audio.Renderer.Parameter.Sink /// public Span DeviceName => SpanHelpers.AsSpan(ref _deviceName); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs index 1ee4eb532..3c1ac09c0 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SinkInParameter.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private ushort _reserved1; + private readonly ushort _reserved1; /// /// The node id of the sink. @@ -50,4 +50,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// public Span SpecificData => SpanHelpers.AsSpan(ref _specificDataStart); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs index 426b861ca..dd0f867b5 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SinkOutStatus.cs @@ -16,11 +16,11 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/padding. /// - private uint _padding; + private readonly uint _padding; /// /// Reserved/padding. /// private unsafe fixed ulong _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs index 96c43092b..b74b67be0 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SplitterDestinationInParameter.cs @@ -59,9 +59,9 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Check if the magic is valid. /// /// Returns true if the magic is valid. - public bool IsMagicValid() + public readonly bool IsMagicValid() { return Magic == ValidMagic; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs index 0220497de..2567b15a8 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameter.cs @@ -38,9 +38,9 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Check if the magic is valid. /// /// Returns true if the magic is valid. - public bool IsMagicValid() + public readonly bool IsMagicValid() { return Magic == ValidMagic; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs index dbae17a9a..10fa866e7 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/SplitterInParameterHeader.cs @@ -37,9 +37,9 @@ namespace Ryujinx.Audio.Renderer.Parameter /// Check if the magic is valid. /// /// Returns true if the magic is valid. - public bool IsMagicValid() + public readonly bool IsMagicValid() { return Magic == ValidMagic; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs index 6a863237d..6cff1a251 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/VoiceChannelResourceInParameter.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Audio.Renderer.Parameter [MarshalAs(UnmanagedType.I1)] public bool IsUsed; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs b/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs index c4b4ba312..86f92442b 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/VoiceInParameter.cs @@ -94,7 +94,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused. /// - private uint _reserved1; + private readonly uint _reserved1; /// /// User state address required by the data source. @@ -143,7 +143,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused. /// - private ushort _reserved2; + private readonly ushort _reserved2; /// /// Change the behaviour of the voice. @@ -222,7 +222,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Reserved/unused. /// - private byte _reserved; + private readonly byte _reserved; /// /// If set to anything other than 0, specifies how many times to loop the wavebuffer. @@ -260,7 +260,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// The PCM sample type /// Returns true if the sample offset are in range of the size. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool IsSampleOffsetInRangeForPcm() where T : unmanaged + private readonly bool IsSampleOffsetInRangeForPcm() where T : unmanaged { uint dataTypeSize = (uint)Unsafe.SizeOf(); @@ -273,27 +273,15 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// The target /// Returns true if the sample offset are in range of the size. - public bool IsSampleOffsetValid(SampleFormat format) + public readonly bool IsSampleOffsetValid(SampleFormat format) { - bool result; - - switch (format) + return format switch { - case SampleFormat.PcmInt16: - result = IsSampleOffsetInRangeForPcm(); - break; - case SampleFormat.PcmFloat: - result = IsSampleOffsetInRangeForPcm(); - break; - case SampleFormat.Adpcm: - result = AdpcmHelper.GetAdpcmDataSize((int)StartSampleOffset) <= Size && - AdpcmHelper.GetAdpcmDataSize((int)EndSampleOffset) <= Size; - break; - default: - throw new NotImplementedException($"{format} not implemented!"); - } - - return result; + SampleFormat.PcmInt16 => IsSampleOffsetInRangeForPcm(), + SampleFormat.PcmFloat => IsSampleOffsetInRangeForPcm(), + SampleFormat.Adpcm => AdpcmHelper.GetAdpcmDataSize((int)StartSampleOffset) <= Size && AdpcmHelper.GetAdpcmDataSize((int)EndSampleOffset) <= Size, + _ => throw new NotImplementedException($"{format} not implemented!"), + }; } } @@ -316,7 +304,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Skip pitch and Sample Rate Conversion (SRC). /// - SkipPitchAndSampleRateConversion = 2 + SkipPitchAndSampleRateConversion = 2, } /// @@ -338,7 +326,7 @@ namespace Ryujinx.Audio.Renderer.Parameter /// /// Resample interpolating 1 samples per output sample. /// - Low + Low, } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs b/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs index be9d35849..a7c749835 100644 --- a/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs +++ b/src/Ryujinx.Audio/Renderer/Parameter/VoiceOutStatus.cs @@ -32,4 +32,4 @@ namespace Ryujinx.Audio.Renderer.Parameter /// private unsafe fixed byte _reserved[3]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs b/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs index 1ad7b8590..7bb8ae5ba 100644 --- a/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs +++ b/src/Ryujinx.Audio/Renderer/Server/AudioRenderSystem.cs @@ -19,30 +19,31 @@ using System; using System.Buffers; using System.Diagnostics; using System.Threading; - using CpuAddress = System.UInt64; namespace Ryujinx.Audio.Renderer.Server { public class AudioRenderSystem : IDisposable { - private object _lock = new object(); + private readonly object _lock = new(); private AudioRendererRenderingDevice _renderingDevice; private AudioRendererExecutionMode _executionMode; - private IWritableEvent _systemEvent; + private readonly IWritableEvent _systemEvent; private MemoryPoolState _dspMemoryPoolState; - private VoiceContext _voiceContext; - private MixContext _mixContext; - private SinkContext _sinkContext; - private SplitterContext _splitterContext; - private EffectContext _effectContext; + private readonly VoiceContext _voiceContext; + private readonly MixContext _mixContext; + private readonly SinkContext _sinkContext; + private readonly SplitterContext _splitterContext; + private readonly EffectContext _effectContext; private PerformanceManager _performanceManager; private UpsamplerManager _upsamplerManager; private bool _isActive; private BehaviourContext _behaviourContext; +#pragma warning disable IDE0052 // Remove unread private member private ulong _totalElapsedTicksUpdating; private ulong _totalElapsedTicks; +#pragma warning restore IDE0052 private int _sessionId; private Memory _memoryPools; @@ -75,7 +76,7 @@ namespace Ryujinx.Audio.Renderer.Server private ulong _elapsedFrameCount; private ulong _renderingStartTick; - private AudioRendererManager _manager; + private readonly AudioRendererManager _manager; private int _disposeState; @@ -143,12 +144,12 @@ namespace Ryujinx.Audio.Renderer.Server WorkBufferAllocator workBufferAllocator; - workBufferMemory.Span.Fill(0); + workBufferMemory.Span.Clear(); _workBufferMemoryPin = workBufferMemory.Pin(); workBufferAllocator = new WorkBufferAllocator(workBufferMemory); - PoolMapper poolMapper = new PoolMapper(processHandle, false); + PoolMapper poolMapper = new(processHandle, false); poolMapper.InitializeSystemPool(ref _dspMemoryPoolState, workBuffer, workBufferSize); _mixBuffer = workBufferAllocator.Allocate(_sampleCount * (_voiceChannelCountMax + _mixBufferCount), 0x10); @@ -244,9 +245,9 @@ namespace Ryujinx.Audio.Renderer.Server foreach (ref MixState mix in mixes.Span) { - mix = new MixState(effectProcessingOrderArray.Slice(0, (int)parameter.EffectCount), ref _behaviourContext); + mix = new MixState(effectProcessingOrderArray[..(int)parameter.EffectCount], ref _behaviourContext); - effectProcessingOrderArray = effectProcessingOrderArray.Slice((int)parameter.EffectCount); + effectProcessingOrderArray = effectProcessingOrderArray[(int)parameter.EffectCount..]; } } @@ -341,26 +342,15 @@ namespace Ryujinx.Audio.Renderer.Server _elapsedFrameCount = 0; _voiceDropParameter = 1.0f; - switch (_behaviourContext.GetCommandProcessingTimeEstimatorVersion()) + _commandProcessingTimeEstimator = _behaviourContext.GetCommandProcessingTimeEstimatorVersion() switch { - case 1: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion1(_sampleCount, _mixBufferCount); - break; - case 2: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion2(_sampleCount, _mixBufferCount); - break; - case 3: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion3(_sampleCount, _mixBufferCount); - break; - case 4: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion4(_sampleCount, _mixBufferCount); - break; - case 5: - _commandProcessingTimeEstimator = new CommandProcessingTimeEstimatorVersion5(_sampleCount, _mixBufferCount); - break; - default: - throw new NotImplementedException($"Unsupported processing time estimator version {_behaviourContext.GetCommandProcessingTimeEstimatorVersion()}."); - } + 1 => new CommandProcessingTimeEstimatorVersion1(_sampleCount, _mixBufferCount), + 2 => new CommandProcessingTimeEstimatorVersion2(_sampleCount, _mixBufferCount), + 3 => new CommandProcessingTimeEstimatorVersion3(_sampleCount, _mixBufferCount), + 4 => new CommandProcessingTimeEstimatorVersion4(_sampleCount, _mixBufferCount), + 5 => new CommandProcessingTimeEstimatorVersion5(_sampleCount, _mixBufferCount), + _ => throw new NotImplementedException($"Unsupported processing time estimator version {_behaviourContext.GetCommandProcessingTimeEstimatorVersion()}."), + }; return ResultCode.Success; } @@ -402,9 +392,9 @@ namespace Ryujinx.Audio.Renderer.Server { ulong updateStartTicks = GetSystemTicks(); - output.Span.Fill(0); + output.Span.Clear(); - StateUpdater stateUpdater = new StateUpdater(input, output, _processHandle, _behaviourContext); + StateUpdater stateUpdater = new(input, output, _processHandle, _behaviourContext); ResultCode result; @@ -609,9 +599,9 @@ namespace Ryujinx.Audio.Renderer.Server _renderingStartTick = 0; } - CommandBuffer commandBuffer = new CommandBuffer(commandList, _commandProcessingTimeEstimator); + CommandBuffer commandBuffer = new(commandList, _commandProcessingTimeEstimator); - CommandGenerator commandGenerator = new CommandGenerator(commandBuffer, GetContext(), _voiceContext, _mixContext, _effectContext, _sinkContext, _splitterContext, _performanceManager); + CommandGenerator commandGenerator = new(commandBuffer, GetContext(), _voiceContext, _mixContext, _effectContext, _sinkContext, _splitterContext, _performanceManager); _voiceContext.Sort(); commandGenerator.GenerateVoices(); @@ -731,7 +721,7 @@ namespace Ryujinx.Audio.Renderer.Server DepopBuffer = _depopBuffer, MixBufferCount = GetMixBufferCount(), SessionId = _sessionId, - UpsamplerManager = _upsamplerManager + UpsamplerManager = _upsamplerManager, }; } @@ -742,7 +732,7 @@ namespace Ryujinx.Audio.Renderer.Server public static ulong GetWorkBufferSize(ref AudioRendererConfiguration parameter) { - BehaviourContext behaviourContext = new BehaviourContext(); + BehaviourContext behaviourContext = new(); behaviourContext.SetUserRevision(parameter.Revision); @@ -813,6 +803,8 @@ namespace Ryujinx.Audio.Renderer.Server public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -828,7 +820,7 @@ namespace Ryujinx.Audio.Renderer.Server Stop(); } - PoolMapper mapper = new PoolMapper(_processHandle, false); + PoolMapper mapper = new(_processHandle, false); mapper.Unmap(ref _dspMemoryPoolState); PoolMapper.ClearUsageState(_memoryPools); @@ -876,4 +868,4 @@ namespace Ryujinx.Audio.Renderer.Server return ResultCode.UnsupportedOperation; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs b/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs index 4de0ad166..0dbbd26c8 100644 --- a/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs +++ b/src/Ryujinx.Audio/Renderer/Server/AudioRendererManager.cs @@ -19,17 +19,17 @@ namespace Ryujinx.Audio.Renderer.Server /// /// Lock used for session allocation. /// - private object _sessionLock = new object(); + private readonly object _sessionLock = new(); /// /// Lock used to control the running state. /// - private object _audioProcessorLock = new object(); + private readonly object _audioProcessorLock = new(); /// /// The session ids allocation table. /// - private int[] _sessionIds; + private readonly int[] _sessionIds; /// /// The events linked to each session. @@ -39,7 +39,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// The sessions instances. /// - private AudioRenderSystem[] _sessions; + private readonly AudioRenderSystem[] _sessions; /// /// The count of active sessions. @@ -186,7 +186,7 @@ namespace Ryujinx.Audio.Renderer.Server _workerThread = new Thread(SendCommands) { - Name = "AudioRendererManager.Worker" + Name = "AudioRendererManager.Worker", }; _workerThread.Start(); @@ -317,7 +317,7 @@ namespace Ryujinx.Audio.Renderer.Server { int sessionId = AcquireSessionId(); - AudioRenderSystem audioRenderer = new AudioRenderSystem(this, _sessionsSystemEvent[sessionId]); + AudioRenderSystem audioRenderer = new(this, _sessionsSystemEvent[sessionId]); // TODO: Eventually, we should try to use the guest supplied work buffer instead of allocating // our own. However, it was causing problems on some applications that would unmap the memory @@ -367,6 +367,8 @@ namespace Ryujinx.Audio.Renderer.Server public void Dispose() { + GC.SuppressFinalize(this); + if (Interlocked.CompareExchange(ref _disposeState, 1, 0) == 0) { Dispose(true); @@ -402,4 +404,4 @@ namespace Ryujinx.Audio.Renderer.Server } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs b/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs index 821947a98..3297b5d9f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/BehaviourContext.cs @@ -125,7 +125,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// Error storage. /// - private ErrorInfo[] _errorInfos; + private readonly ErrorInfo[] _errorInfos; /// /// Current position in the array. @@ -254,7 +254,8 @@ namespace Ryujinx.Audio.Renderer.Server { return 0.80f; } - else if (CheckFeatureSupported(UserRevision, BaseRevisionMagic + Revision4)) + + if (CheckFeatureSupported(UserRevision, BaseRevisionMagic + Revision4)) { return 0.75f; } @@ -299,10 +300,8 @@ namespace Ryujinx.Audio.Renderer.Server { return 2; } - else - { - return 1; - } + + return 1; } /// @@ -436,7 +435,7 @@ namespace Ryujinx.Audio.Renderer.Server errorInfos[i] = new ErrorInfo { ErrorCode = 0, - ExtraErrorInfo = 0 + ExtraErrorInfo = 0, }; } } @@ -450,4 +449,4 @@ namespace Ryujinx.Audio.Renderer.Server _errorIndex = 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs b/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs index 905cb2054..f4174a913 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandBuffer.cs @@ -20,7 +20,7 @@ namespace Ryujinx.Audio.Renderer.Server /// /// The command processing time estimator in use. /// - private ICommandProcessingTimeEstimator _commandProcessingTimeEstimator; + private readonly ICommandProcessingTimeEstimator _commandProcessingTimeEstimator; /// /// The estimated total processing time. @@ -61,7 +61,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateClearMixBuffer(int nodeId) { - ClearMixBufferCommand command = new ClearMixBufferCommand(nodeId); + ClearMixBufferCommand command = new(nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -79,7 +79,7 @@ namespace Ryujinx.Audio.Renderer.Server /// Set to true if the voice was playing previously. public void GenerateDepopPrepare(Memory state, Memory depopBuffer, uint bufferCount, uint bufferOffset, int nodeId, bool wasPlaying) { - DepopPrepareCommand command = new DepopPrepareCommand(state, depopBuffer, bufferCount, bufferOffset, nodeId, wasPlaying); + DepopPrepareCommand command = new(state, depopBuffer, bufferCount, bufferOffset, nodeId, wasPlaying); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -94,7 +94,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GeneratePerformance(ref PerformanceEntryAddresses performanceEntryAddresses, PerformanceCommand.Type type, int nodeId) { - PerformanceCommand command = new PerformanceCommand(ref performanceEntryAddresses, type, nodeId); + PerformanceCommand command = new(ref performanceEntryAddresses, type, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -110,7 +110,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateVolumeRamp(float previousVolume, float volume, uint bufferIndex, int nodeId) { - VolumeRampCommand command = new VolumeRampCommand(previousVolume, volume, bufferIndex, nodeId); + VolumeRampCommand command = new(previousVolume, volume, bufferIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -127,7 +127,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateDataSourceVersion2(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { - DataSourceVersion2Command command = new DataSourceVersion2Command(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); + DataSourceVersion2Command command = new(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -144,7 +144,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GeneratePcmInt16DataSourceVersion1(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { - PcmInt16DataSourceCommandVersion1 command = new PcmInt16DataSourceCommandVersion1(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); + PcmInt16DataSourceCommandVersion1 command = new(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -161,7 +161,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GeneratePcmFloatDataSourceVersion1(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, ushort channelIndex, int nodeId) { - PcmFloatDataSourceCommandVersion1 command = new PcmFloatDataSourceCommandVersion1(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); + PcmFloatDataSourceCommandVersion1 command = new(ref voiceState, state, outputBufferIndex, channelIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -177,7 +177,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateAdpcmDataSourceVersion1(ref VoiceState voiceState, Memory state, ushort outputBufferIndex, int nodeId) { - AdpcmDataSourceCommandVersion1 command = new AdpcmDataSourceCommandVersion1(ref voiceState, state, outputBufferIndex, nodeId); + AdpcmDataSourceCommandVersion1 command = new(ref voiceState, state, outputBufferIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -196,7 +196,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateBiquadFilter(int baseIndex, ref BiquadFilterParameter filter, Memory biquadFilterStateMemory, int inputBufferOffset, int outputBufferOffset, bool needInitialization, int nodeId) { - BiquadFilterCommand command = new BiquadFilterCommand(baseIndex, ref filter, biquadFilterStateMemory, inputBufferOffset, outputBufferOffset, needInitialization, nodeId); + BiquadFilterCommand command = new(baseIndex, ref filter, biquadFilterStateMemory, inputBufferOffset, outputBufferOffset, needInitialization, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -215,7 +215,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateGroupedBiquadFilter(int baseIndex, ReadOnlySpan filters, Memory biquadFilterStatesMemory, int inputBufferOffset, int outputBufferOffset, ReadOnlySpan isInitialized, int nodeId) { - GroupedBiquadFilterCommand command = new GroupedBiquadFilterCommand(baseIndex, filters, biquadFilterStatesMemory, inputBufferOffset, outputBufferOffset, isInitialized, nodeId); + GroupedBiquadFilterCommand command = new(baseIndex, filters, biquadFilterStatesMemory, inputBufferOffset, outputBufferOffset, isInitialized, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -234,7 +234,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateMixRampGrouped(uint mixBufferCount, uint inputBufferIndex, uint outputBufferIndex, Span previousVolume, Span volume, Memory state, int nodeId) { - MixRampGroupedCommand command = new MixRampGroupedCommand(mixBufferCount, inputBufferIndex, outputBufferIndex, previousVolume, volume, state, nodeId); + MixRampGroupedCommand command = new(mixBufferCount, inputBufferIndex, outputBufferIndex, previousVolume, volume, state, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -253,7 +253,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateMixRamp(float previousVolume, float volume, uint inputBufferIndex, uint outputBufferIndex, int lastSampleIndex, Memory state, int nodeId) { - MixRampCommand command = new MixRampCommand(previousVolume, volume, inputBufferIndex, outputBufferIndex, lastSampleIndex, state, nodeId); + MixRampCommand command = new(previousVolume, volume, inputBufferIndex, outputBufferIndex, lastSampleIndex, state, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -270,7 +270,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The target sample rate in use. public void GenerateDepopForMixBuffersCommand(Memory depopBuffer, uint bufferOffset, uint bufferCount, int nodeId, uint sampleRate) { - DepopForMixBuffersCommand command = new DepopForMixBuffersCommand(depopBuffer, bufferOffset, bufferCount, nodeId, sampleRate); + DepopForMixBuffersCommand command = new(depopBuffer, bufferOffset, bufferCount, nodeId, sampleRate); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -285,7 +285,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateCopyMixBuffer(uint inputBufferIndex, uint outputBufferIndex, int nodeId) { - CopyMixBufferCommand command = new CopyMixBufferCommand(inputBufferIndex, outputBufferIndex, nodeId); + CopyMixBufferCommand command = new(inputBufferIndex, outputBufferIndex, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -301,7 +301,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The mix volume. public void GenerateMix(uint inputBufferIndex, uint outputBufferIndex, int nodeId, float volume) { - MixCommand command = new MixCommand(inputBufferIndex, outputBufferIndex, nodeId, volume); + MixCommand command = new(inputBufferIndex, outputBufferIndex, nodeId, volume); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -323,7 +323,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - ReverbCommand command = new ReverbCommand(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, isLongSizePreDelaySupported, newEffectChannelMappingSupported); + ReverbCommand command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, isLongSizePreDelaySupported, newEffectChannelMappingSupported); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -345,7 +345,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - Reverb3dCommand command = new Reverb3dCommand(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); + Reverb3dCommand command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -368,7 +368,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - DelayCommand command = new DelayCommand(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); + DelayCommand command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId, newEffectChannelMappingSupported); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -389,7 +389,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - LimiterCommandVersion1 command = new LimiterCommandVersion1(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId); + LimiterCommandVersion1 command = new(bufferOffset, parameter, state, isEnabled, workBuffer, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -411,7 +411,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - LimiterCommandVersion2 command = new LimiterCommandVersion2(bufferOffset, parameter, state, effectResultState, isEnabled, workBuffer, nodeId); + LimiterCommandVersion2 command = new(bufferOffset, parameter, state, effectResultState, isEnabled, workBuffer, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -437,7 +437,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (state.SendBufferInfoBase != 0 && state.ReturnBufferInfoBase != 0) { - AuxiliaryBufferCommand command = new AuxiliaryBufferCommand(bufferOffset, inputBufferOffset, outputBufferOffset, ref state, isEnabled, countMax, outputBuffer, inputBuffer, updateCount, writeOffset, nodeId); + AuxiliaryBufferCommand command = new(bufferOffset, inputBufferOffset, outputBufferOffset, ref state, isEnabled, countMax, outputBuffer, inputBuffer, updateCount, writeOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -461,7 +461,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (sendBufferInfo != 0) { - CaptureBufferCommand command = new CaptureBufferCommand(bufferOffset, inputBufferOffset, sendBufferInfo, isEnabled, countMax, outputBuffer, updateCount, writeOffset, nodeId); + CaptureBufferCommand command = new(bufferOffset, inputBufferOffset, sendBufferInfo, isEnabled, countMax, outputBuffer, updateCount, writeOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -473,7 +473,7 @@ namespace Ryujinx.Audio.Renderer.Server { if (parameter.IsChannelCountValid()) { - CompressorCommand command = new CompressorCommand(bufferOffset, parameter, state, isEnabled, nodeId); + CompressorCommand command = new(bufferOffset, parameter, state, isEnabled, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -489,7 +489,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateVolume(float volume, uint bufferOffset, int nodeId) { - VolumeCommand command = new VolumeCommand(volume, bufferOffset, nodeId); + VolumeCommand command = new(volume, bufferOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -504,7 +504,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateCircularBuffer(uint bufferOffset, CircularBufferSink sink, int nodeId) { - CircularBufferSinkCommand command = new CircularBufferSinkCommand(bufferOffset, ref sink.Parameter, ref sink.CircularBufferAddressInfo, sink.CurrentWriteOffset, nodeId); + CircularBufferSinkCommand command = new(bufferOffset, ref sink.Parameter, ref sink.CircularBufferAddressInfo, sink.CurrentWriteOffset, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -521,7 +521,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateDownMixSurroundToStereo(uint bufferOffset, Span inputBufferOffset, Span outputBufferOffset, float[] downMixParameter, int nodeId) { - DownMixSurroundToStereoCommand command = new DownMixSurroundToStereoCommand(bufferOffset, inputBufferOffset, outputBufferOffset, downMixParameter, nodeId); + DownMixSurroundToStereoCommand command = new(bufferOffset, inputBufferOffset, outputBufferOffset, downMixParameter, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -541,7 +541,7 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateUpsample(uint bufferOffset, UpsamplerState upsampler, uint inputCount, Span inputBufferOffset, uint bufferCountPerSample, uint sampleCount, uint sampleRate, int nodeId) { - UpsampleCommand command = new UpsampleCommand(bufferOffset, upsampler, inputCount, inputBufferOffset, bufferCountPerSample, sampleCount, sampleRate, nodeId); + UpsampleCommand command = new(bufferOffset, upsampler, inputCount, inputBufferOffset, bufferCountPerSample, sampleCount, sampleRate, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); @@ -558,11 +558,11 @@ namespace Ryujinx.Audio.Renderer.Server /// The node id associated to this command. public void GenerateDeviceSink(uint bufferOffset, DeviceSink sink, int sessionId, Memory buffer, int nodeId) { - DeviceSinkCommand command = new DeviceSinkCommand(bufferOffset, sink, sessionId, buffer, nodeId); + DeviceSinkCommand command = new(bufferOffset, sink, sessionId, buffer, nodeId); command.EstimatedProcessingTime = _commandProcessingTimeEstimator.Estimate(command); AddCommand(command); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs b/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs index afc1e39b7..ae8f699f3 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandGenerator.cs @@ -17,14 +17,14 @@ namespace Ryujinx.Audio.Renderer.Server { public class CommandGenerator { - private CommandBuffer _commandBuffer; - private RendererSystemContext _rendererContext; - private VoiceContext _voiceContext; - private MixContext _mixContext; - private EffectContext _effectContext; - private SinkContext _sinkContext; - private SplitterContext _splitterContext; - private PerformanceManager _performanceManager; + private readonly CommandBuffer _commandBuffer; + private readonly RendererSystemContext _rendererContext; + private readonly VoiceContext _voiceContext; + private readonly MixContext _mixContext; + private readonly EffectContext _effectContext; + private readonly SinkContext _sinkContext; + private readonly SplitterContext _splitterContext; + private readonly PerformanceManager _performanceManager; public CommandGenerator(CommandBuffer commandBuffer, RendererSystemContext rendererContext, VoiceContext voiceContext, MixContext mixContext, EffectContext effectContext, SinkContext sinkContext, SplitterContext splitterContext, PerformanceManager performanceManager) { @@ -138,7 +138,7 @@ namespace Ryujinx.Audio.Renderer.Server if (supportsOptimizedPath && voiceState.BiquadFilters[0].Enable && voiceState.BiquadFilters[1].Enable) { - Memory biquadStateRawMemory = SpanMemoryManager.Cast(state).Slice(VoiceUpdateState.BiquadStateOffset, VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount); + Memory biquadStateRawMemory = SpanMemoryManager.Cast(state)[..(VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount)]; Memory stateMemory = SpanMemoryManager.Cast(biquadStateRawMemory); _commandBuffer.GenerateGroupedBiquadFilter(baseIndex, voiceState.BiquadFilters.AsSpan(), stateMemory, bufferOffset, bufferOffset, voiceState.BiquadFilterNeedInitialization, nodeId); @@ -151,7 +151,7 @@ namespace Ryujinx.Audio.Renderer.Server if (filter.Enable) { - Memory biquadStateRawMemory = SpanMemoryManager.Cast(state).Slice(VoiceUpdateState.BiquadStateOffset, VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount); + Memory biquadStateRawMemory = SpanMemoryManager.Cast(state)[..(VoiceUpdateState.BiquadStateSize * Constants.VoiceBiquadFilterCount)]; Memory stateMemory = SpanMemoryManager.Cast(biquadStateRawMemory); @@ -224,7 +224,7 @@ namespace Ryujinx.Audio.Renderer.Server bool performanceInitialized = false; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); if (_performanceManager != null && _performanceManager.IsTargetNodeId(nodeId) && _performanceManager.GetNextEntry(out performanceEntry, dataSourceDetailType, PerformanceEntryType.Voice, nodeId)) { @@ -371,7 +371,7 @@ namespace Ryujinx.Audio.Renderer.Server { int nodeId = sortedState.NodeId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -502,9 +502,11 @@ namespace Ryujinx.Audio.Renderer.Server bool needInitialization = effect.Parameter.Status == UsageState.Invalid || (effect.Parameter.Status == UsageState.New && !_rendererContext.BehaviourContext.IsBiquadFilterEffectStateClearBugFixed()); - BiquadFilterParameter parameter = new BiquadFilterParameter(); + BiquadFilterParameter parameter = new() + { + Enable = true, + }; - parameter.Enable = true; effect.Parameter.Denominator.AsSpan().CopyTo(parameter.Denominator.AsSpan()); effect.Parameter.Numerator.AsSpan().CopyTo(parameter.Numerator.AsSpan()); @@ -623,7 +625,7 @@ namespace Ryujinx.Audio.Renderer.Server bool isFinalMix = mix.MixId == Constants.FinalMixId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -789,7 +791,7 @@ namespace Ryujinx.Audio.Renderer.Server GenerateEffects(ref subMix); - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); int nodeId = subMix.NodeId; @@ -820,7 +822,7 @@ namespace Ryujinx.Audio.Renderer.Server { int nodeId = sortedState.NodeId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -853,7 +855,7 @@ namespace Ryujinx.Audio.Renderer.Server GenerateEffects(ref finalMix); - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); int nodeId = finalMix.NodeId; @@ -901,7 +903,7 @@ namespace Ryujinx.Audio.Renderer.Server { int nodeId = _mixContext.GetFinalState().NodeId; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); bool performanceInitialized = false; @@ -977,7 +979,7 @@ namespace Ryujinx.Audio.Renderer.Server { bool performanceInitialized = false; - PerformanceEntryAddresses performanceEntry = new PerformanceEntryAddresses(); + PerformanceEntryAddresses performanceEntry = new(); if (_performanceManager != null && _performanceManager.GetNextEntry(out performanceEntry, PerformanceEntryType.Sink, sink.NodeId)) { @@ -1025,4 +1027,4 @@ namespace Ryujinx.Audio.Renderer.Server } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs index 63dc9ca96..d95e9aa71 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion1.cs @@ -8,8 +8,8 @@ namespace Ryujinx.Audio.Renderer.Server /// public class CommandProcessingTimeEstimatorVersion1 : ICommandProcessingTimeEstimator { - private uint _sampleCount; - private uint _bufferCount; + private readonly uint _sampleCount; + private readonly uint _bufferCount; public CommandProcessingTimeEstimatorVersion1(uint sampleCount, uint bufferCount) { @@ -185,4 +185,4 @@ namespace Ryujinx.Audio.Renderer.Server return 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs index 7ee491cd6..929aaf383 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion2.cs @@ -9,8 +9,8 @@ namespace Ryujinx.Audio.Renderer.Server /// public class CommandProcessingTimeEstimatorVersion2 : ICommandProcessingTimeEstimator { - private uint _sampleCount; - private uint _bufferCount; + private readonly uint _sampleCount; + private readonly uint _bufferCount; public CommandProcessingTimeEstimatorVersion2(uint sampleCount, uint bufferCount) { @@ -60,7 +60,7 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(MixRampGroupedCommand command) { - const float costPerSample = 7.245f; + const float CostPerSample = 7.245f; Debug.Assert(_sampleCount == 160 || _sampleCount == 240); @@ -74,7 +74,7 @@ namespace Ryujinx.Audio.Renderer.Server } } - return (uint)(_sampleCount * costPerSample * volumeCount); + return (uint)(_sampleCount * CostPerSample * volumeCount); } public uint Estimate(MixRampCommand command) @@ -189,71 +189,47 @@ namespace Ryujinx.Audio.Renderer.Server { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)41636.0f; - case 2: - return (uint)97861.0f; - case 4: - return (uint)192520.0f; - case 6: - return (uint)301760.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)41636.0f, + 2 => (uint)97861.0f, + 4 => (uint)192520.0f, + 6 => (uint)301760.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)578.53f; - case 2: - return (uint)663.06f; - case 4: - return (uint)703.98f; - case 6: - return (uint)760.03f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)578.53f, + 2 => (uint)663.06f, + 4 => (uint)703.98f, + 6 => (uint)760.03f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)8770.3f; - case 2: - return (uint)25741.0f; - case 4: - return (uint)47551.0f; - case 6: - return (uint)81629.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)8770.3f, + 2 => (uint)25741.0f, + 4 => (uint)47551.0f, + 6 => (uint)81629.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)521.28f; - case 2: - return (uint)585.4f; - case 4: - return (uint)629.88f; - case 6: - return (uint)713.57f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)521.28f, + 2 => (uint)585.4f, + 4 => (uint)629.88f, + 6 => (uint)713.57f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(ReverbCommand command) @@ -264,71 +240,47 @@ namespace Ryujinx.Audio.Renderer.Server { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)97192.0f; - case 2: - return (uint)103280.0f; - case 4: - return (uint)109580.0f; - case 6: - return (uint)115070.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)97192.0f, + 2 => (uint)103280.0f, + 4 => (uint)109580.0f, + 6 => (uint)115070.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)492.01f; - case 2: - return (uint)554.46f; - case 4: - return (uint)595.86f; - case 6: - return (uint)656.62f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)492.01f, + 2 => (uint)554.46f, + 4 => (uint)595.86f, + 6 => (uint)656.62f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)136460.0f; - case 2: - return (uint)145750.0f; - case 4: - return (uint)154800.0f; - case 6: - return (uint)161970.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)136460.0f, + 2 => (uint)145750.0f, + 4 => (uint)154800.0f, + 6 => (uint)161970.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)495.79f; - case 2: - return (uint)527.16f; - case 4: - return (uint)598.75f; - case 6: - return (uint)666.03f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)495.79f, + 2 => (uint)527.16f, + 4 => (uint)598.75f, + 6 => (uint)666.03f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(Reverb3dCommand command) @@ -339,70 +291,46 @@ namespace Ryujinx.Audio.Renderer.Server { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)138840.0f; - case 2: - return (uint)135430.0f; - case 4: - return (uint)199180.0f; - case 6: - return (uint)247350.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)138840.0f, + 2 => (uint)135430.0f, + 4 => (uint)199180.0f, + 6 => (uint)247350.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)718.7f; - case 2: - return (uint)751.3f; - case 4: - return (uint)797.46f; - case 6: - return (uint)867.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)718.7f, + 2 => (uint)751.3f, + 4 => (uint)797.46f, + 6 => (uint)867.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)199950.0f; - case 2: - return (uint)195200.0f; - case 4: - return (uint)290580.0f; - case 6: - return (uint)363490.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)199950.0f, + 2 => (uint)195200.0f, + 4 => (uint)290580.0f, + 6 => (uint)363490.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)534.24f; - case 2: - return (uint)570.87f; - case 4: - return (uint)660.93f; - case 6: - return (uint)694.6f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)534.24f, + 2 => (uint)570.87f, + 4 => (uint)660.93f, + 6 => (uint)694.6f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(AuxiliaryBufferCommand command) @@ -549,4 +477,4 @@ namespace Ryujinx.Audio.Renderer.Server return 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs index b79ca1369..8ae4bc059 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion3.cs @@ -12,20 +12,20 @@ namespace Ryujinx.Audio.Renderer.Server /// public class CommandProcessingTimeEstimatorVersion3 : ICommandProcessingTimeEstimator { - protected uint _sampleCount; - protected uint _bufferCount; + protected uint SampleCount; + protected uint BufferCount; public CommandProcessingTimeEstimatorVersion3(uint sampleCount, uint bufferCount) { - _sampleCount = sampleCount; - _bufferCount = bufferCount; + SampleCount = sampleCount; + BufferCount = bufferCount; } public uint Estimate(PerformanceCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)498.17f; } @@ -35,24 +35,24 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(ClearMixBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerBuffer = 440.68f; float baseCost = 0; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerBuffer = 266.65f; } - return (uint)(baseCost + costPerBuffer * _bufferCount); + return (uint)(baseCost + costPerBuffer * BufferCount); } public uint Estimate(BiquadFilterCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)4173.2f; } @@ -64,9 +64,9 @@ namespace Ryujinx.Audio.Renderer.Server { float costPerSample = 6.4434f; - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 6.708f; } @@ -81,14 +81,14 @@ namespace Ryujinx.Audio.Renderer.Server } } - return (uint)(_sampleCount * costPerSample * volumeCount); + return (uint)(SampleCount * costPerSample * volumeCount); } public uint Estimate(MixRampCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1968.7f; } @@ -103,9 +103,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(VolumeRampCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1425.3f; } @@ -115,41 +115,41 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(PcmInt16DataSourceCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerSample = 710.143f; float baseCost = 7853.286f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 427.52f; baseCost = 6329.442f; } - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f)))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f)))); } public uint Estimate(AdpcmDataSourceCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerSample = 3564.1f; float baseCost = 9736.702f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 2125.6f; baseCost = 7913.808f; } - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f)))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f)))); } public uint Estimate(DepopForMixBuffersCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)739.64f; } @@ -159,9 +159,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(CopyMixBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)842.59f; } @@ -171,9 +171,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(MixCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1402.8f; } @@ -183,231 +183,159 @@ namespace Ryujinx.Audio.Renderer.Server public virtual uint Estimate(DelayCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)8929.04f; - case 2: - return (uint)25500.75f; - case 4: - return (uint)47759.62f; - case 6: - return (uint)82203.07f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)8929.04f, + 2 => (uint)25500.75f, + 4 => (uint)47759.62f, + 6 => (uint)82203.07f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)1295.20f; - case 2: - return (uint)1213.60f; - case 4: - return (uint)942.03f; - case 6: - return (uint)1001.55f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)1295.20f, + 2 => (uint)1213.60f, + 4 => (uint)942.03f, + 6 => (uint)1001.55f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)11941.05f; - case 2: - return (uint)37197.37f; - case 4: - return (uint)69749.84f; - case 6: - return (uint)120042.40f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)11941.05f, + 2 => (uint)37197.37f, + 4 => (uint)69749.84f, + 6 => (uint)120042.40f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)997.67f; - case 2: - return (uint)977.63f; - case 4: - return (uint)792.30f; - case 6: - return (uint)875.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)997.67f, + 2 => (uint)977.63f, + 4 => (uint)792.30f, + 6 => (uint)875.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public virtual uint Estimate(ReverbCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)81475.05f; - case 2: - return (uint)84975.0f; - case 4: - return (uint)91625.15f; - case 6: - return (uint)95332.27f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)81475.05f, + 2 => (uint)84975.0f, + 4 => (uint)91625.15f, + 6 => (uint)95332.27f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)536.30f; - case 2: - return (uint)588.70f; - case 4: - return (uint)643.70f; - case 6: - return (uint)706.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)536.30f, + 2 => (uint)588.70f, + 4 => (uint)643.70f, + 6 => (uint)706.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)120174.47f; - case 2: - return (uint)25262.22f; - case 4: - return (uint)135751.23f; - case 6: - return (uint)141129.23f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)120174.47f, + 2 => (uint)25262.22f, + 4 => (uint)135751.23f, + 6 => (uint)141129.23f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)617.64f; - case 2: - return (uint)659.54f; - case 4: - return (uint)711.43f; - case 6: - return (uint)778.07f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)617.64f, + 2 => (uint)659.54f, + 4 => (uint)711.43f, + 6 => (uint)778.07f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public virtual uint Estimate(Reverb3dCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)116754.0f; - case 2: - return (uint)125912.05f; - case 4: - return (uint)146336.03f; - case 6: - return (uint)165812.66f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)116754.0f, + 2 => (uint)125912.05f, + 4 => (uint)146336.03f, + 6 => (uint)165812.66f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)734.0f; - case 2: - return (uint)766.62f; - case 4: - return (uint)797.46f; - case 6: - return (uint)867.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)734.0f, + 2 => (uint)766.62f, + 4 => (uint)797.46f, + 6 => (uint)867.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)170292.34f; - case 2: - return (uint)183875.63f; - case 4: - return (uint)214696.19f; - case 6: - return (uint)243846.77f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)170292.34f, + 2 => (uint)183875.63f, + 4 => (uint)214696.19f, + 6 => (uint)243846.77f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)508.47f; - case 2: - return (uint)582.45f; - case 4: - return (uint)626.42f; - case 6: - return (uint)682.47f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)508.47f, + 2 => (uint)582.45f, + 4 => (uint)626.42f, + 6 => (uint)682.47f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public uint Estimate(AuxiliaryBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { @@ -427,9 +355,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(VolumeCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)1311.1f; } @@ -439,12 +367,12 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(CircularBufferSinkCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerBuffer = 770.26f; float baseCost = 0f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerBuffer = 531.07f; } @@ -454,9 +382,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(DownMixSurroundToStereoCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)9949.7f; } @@ -466,9 +394,9 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(UpsampleCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)312990.0f; } @@ -478,12 +406,12 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(DeviceSinkCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); Debug.Assert(command.InputCount == 2 || command.InputCount == 6); if (command.InputCount == 2) { - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)8980.0f; } @@ -491,7 +419,7 @@ namespace Ryujinx.Audio.Renderer.Server return (uint)9221.9f; } - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)9177.9f; } @@ -501,27 +429,27 @@ namespace Ryujinx.Audio.Renderer.Server public uint Estimate(PcmFloatDataSourceCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); float costPerSample = 3490.9f; float baseCost = 10090.9f; - if (_sampleCount == 160) + if (SampleCount == 160) { costPerSample = 2310.4f; baseCost = 7845.25f; } - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f)))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f)))); } public uint Estimate(DataSourceVersion2Command command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - (float baseCost, float costPerSample) = GetCostByFormat(_sampleCount, command.SampleFormat, command.SrcQuality); + (float baseCost, float costPerSample) = GetCostByFormat(SampleCount, command.SampleFormat, command.SrcQuality); - return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / _sampleCount) * (command.Pitch * 0.000030518f) - 1.0f))); + return (uint)(baseCost + (costPerSample * (((command.SampleRate / 200.0f) / SampleCount) * (command.Pitch * 0.000030518f) - 1.0f))); } private static (float, float) GetCostByFormat(uint sampleCount, SampleFormat format, SampleRateConversionQuality quality) @@ -618,124 +546,90 @@ namespace Ryujinx.Audio.Renderer.Server private uint EstimateLimiterCommandCommon(LimiterParameter parameter, bool enabled) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (enabled) { - switch (parameter.ChannelCount) + return parameter.ChannelCount switch { - case 1: - return (uint)21392.0f; - case 2: - return (uint)26829.0f; - case 4: - return (uint)32405.0f; - case 6: - return (uint)52219.0f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } + 1 => (uint)21392.0f, + 2 => (uint)26829.0f, + 4 => (uint)32405.0f, + 6 => (uint)52219.0f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } - else + + return parameter.ChannelCount switch { - switch (parameter.ChannelCount) - { - case 1: - return (uint)897.0f; - case 2: - return (uint)931.55f; - case 4: - return (uint)975.39f; - case 6: - return (uint)1016.8f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } - } + 1 => (uint)897.0f, + 2 => (uint)931.55f, + 4 => (uint)975.39f, + 6 => (uint)1016.8f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } if (enabled) { - switch (parameter.ChannelCount) + return parameter.ChannelCount switch { - case 1: - return (uint)30556.0f; - case 2: - return (uint)39011.0f; - case 4: - return (uint)48270.0f; - case 6: - return (uint)76712.0f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } + 1 => (uint)30556.0f, + 2 => (uint)39011.0f, + 4 => (uint)48270.0f, + 6 => (uint)76712.0f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } - else + + return parameter.ChannelCount switch { - switch (parameter.ChannelCount) - { - case 1: - return (uint)874.43f; - case 2: - return (uint)921.55f; - case 4: - return (uint)945.26f; - case 6: - return (uint)992.26f; - default: - throw new NotImplementedException($"{parameter.ChannelCount}"); - } - } + 1 => (uint)874.43f, + 2 => (uint)921.55f, + 4 => (uint)945.26f, + 6 => (uint)992.26f, + _ => throw new NotImplementedException($"{parameter.ChannelCount}"), + }; } public uint Estimate(LimiterCommandVersion1 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); return EstimateLimiterCommandCommon(command.Parameter, command.IsEffectEnabled); } public uint Estimate(LimiterCommandVersion2 command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); if (!command.Parameter.StatisticsEnabled || !command.IsEffectEnabled) { return EstimateLimiterCommandCommon(command.Parameter, command.IsEffectEnabled); } - if (_sampleCount == 160) + if (SampleCount == 160) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)23309.0f; - case 2: - return (uint)29954.0f; - case 4: - return (uint)35807.0f; - case 6: - return (uint)58340.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)23309.0f, + 2 => (uint)29954.0f, + 4 => (uint)35807.0f, + 6 => (uint)58340.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return (uint)33526.0f; - case 2: - return (uint)43549.0f; - case 4: - return (uint)52190.0f; - case 6: - return (uint)85527.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => (uint)33526.0f, + 2 => (uint)43549.0f, + 4 => (uint)52190.0f, + 6 => (uint)85527.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public virtual uint Estimate(GroupedBiquadFilterCommand command) @@ -753,4 +647,4 @@ namespace Ryujinx.Audio.Renderer.Server return 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs index c60d8ebcb..25bc67cd9 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion4.cs @@ -12,9 +12,9 @@ namespace Ryujinx.Audio.Renderer.Server public override uint Estimate(GroupedBiquadFilterCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { return (uint)7424.5f; } @@ -24,9 +24,9 @@ namespace Ryujinx.Audio.Renderer.Server public override uint Estimate(CaptureBufferCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { @@ -44,4 +44,4 @@ namespace Ryujinx.Audio.Renderer.Server return (uint)435.2f; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs index 2ed7e6a5b..7135c1c4f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs +++ b/src/Ryujinx.Audio/Renderer/Server/CommandProcessingTimeEstimatorVersion5.cs @@ -13,298 +13,202 @@ namespace Ryujinx.Audio.Renderer.Server public override uint Estimate(DelayCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 8929; - case 2: - return 25501; - case 4: - return 47760; - case 6: - return 82203; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 8929, + 2 => 25501, + 4 => 47760, + 6 => 82203, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)1295.20f; - case 2: - return (uint)1213.60f; - case 4: - return (uint)942.03f; - case 6: - return (uint)1001.6f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)1295.20f, + 2 => (uint)1213.60f, + 4 => (uint)942.03f, + 6 => (uint)1001.6f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 11941; - case 2: - return 37197; - case 4: - return 69750; - case 6: - return 12004; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 11941, + 2 => 37197, + 4 => 69750, + 6 => 12004, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)997.67f; - case 2: - return (uint)977.63f; - case 4: - return (uint)792.31f; - case 6: - return (uint)875.43f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)997.67f, + 2 => (uint)977.63f, + 4 => (uint)792.31f, + 6 => (uint)875.43f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public override uint Estimate(ReverbCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 81475; - case 2: - return 84975; - case 4: - return 91625; - case 6: - return 95332; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 81475, + 2 => 84975, + 4 => 91625, + 6 => 95332, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)536.30f; - case 2: - return (uint)588.80f; - case 4: - return (uint)643.70f; - case 6: - return (uint)706.0f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)536.30f, + 2 => (uint)588.80f, + 4 => (uint)643.70f, + 6 => (uint)706.0f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 120170; - case 2: - return 125260; - case 4: - return 135750; - case 6: - return 141130; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 120170, + 2 => 125260, + 4 => 135750, + 6 => 141130, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)617.64f; - case 2: - return (uint)659.54f; - case 4: - return (uint)711.44f; - case 6: - return (uint)778.07f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)617.64f, + 2 => (uint)659.54f, + 4 => (uint)711.44f, + 6 => (uint)778.07f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public override uint Estimate(Reverb3dCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 116750; - case 2: - return 125910; - case 4: - return 146340; - case 6: - return 165810; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 116750, + 2 => 125910, + 4 => 146340, + 6 => 165810, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return 735; - case 2: - return (uint)766.62f; - case 4: - return (uint)834.07f; - case 6: - return (uint)875.44f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => 735, + 2 => (uint)766.62f, + 4 => (uint)834.07f, + 6 => (uint)875.44f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 170290; - case 2: - return 183880; - case 4: - return 214700; - case 6: - return 243850; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 170290, + 2 => 183880, + 4 => 214700, + 6 => 243850, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)508.47f; - case 2: - return (uint)582.45f; - case 4: - return (uint)626.42f; - case 6: - return (uint)682.47f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)508.47f, + 2 => (uint)582.45f, + 4 => (uint)626.42f, + 6 => (uint)682.47f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } public override uint Estimate(CompressorCommand command) { - Debug.Assert(_sampleCount == 160 || _sampleCount == 240); + Debug.Assert(SampleCount == 160 || SampleCount == 240); - if (_sampleCount == 160) + if (SampleCount == 160) { if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 34431; - case 2: - return 44253; - case 4: - return 63827; - case 6: - return 83361; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 34431, + 2 => 44253, + 4 => 63827, + 6 => 83361, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)630.12f; - case 2: - return (uint)638.27f; - case 4: - return (uint)705.86f; - case 6: - return (uint)782.02f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)630.12f, + 2 => (uint)638.27f, + 4 => (uint)705.86f, + 6 => (uint)782.02f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } if (command.Enabled) { - switch (command.Parameter.ChannelCount) + return command.Parameter.ChannelCount switch { - case 1: - return 51095; - case 2: - return 65693; - case 4: - return 95383; - case 6: - return 124510; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } + 1 => 51095, + 2 => 65693, + 4 => 95383, + 6 => 124510, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } - else + + return command.Parameter.ChannelCount switch { - switch (command.Parameter.ChannelCount) - { - case 1: - return (uint)840.14f; - case 2: - return (uint)826.1f; - case 4: - return (uint)901.88f; - case 6: - return (uint)965.29f; - default: - throw new NotImplementedException($"{command.Parameter.ChannelCount}"); - } - } + 1 => (uint)840.14f, + 2 => (uint)826.1f, + 4 => (uint)901.88f, + 6 => (uint)965.29f, + _ => throw new NotImplementedException($"{command.Parameter.ChannelCount}"), + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs index 164065271..57ca266f4 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/AuxiliaryBufferEffect.cs @@ -58,7 +58,7 @@ namespace Ryujinx.Audio.Renderer.Server.Effect { ulong bufferSize = (ulong)Unsafe.SizeOf() * Parameter.BufferStorageSize + (ulong)Unsafe.SizeOf(); - bool sendBufferUnmapped = !mapper.TryAttachBuffer(out updateErrorInfo, ref WorkBuffers[0], Parameter.SendBufferInfoAddress, bufferSize); + bool sendBufferUnmapped = !mapper.TryAttachBuffer(out _, ref WorkBuffers[0], Parameter.SendBufferInfoAddress, bufferSize); bool returnBufferUnmapped = !mapper.TryAttachBuffer(out updateErrorInfo, ref WorkBuffers[1], Parameter.ReturnBufferInfoAddress, bufferSize); BufferUnmapped = sendBufferUnmapped && returnBufferUnmapped; @@ -82,4 +82,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect UpdateUsageStateForCommandGeneration(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs index 825b3bf76..a9716db2a 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/BaseEffect.cs @@ -244,29 +244,19 @@ namespace Ryujinx.Audio.Renderer.Server.Effect /// The associated to the of this effect. public PerformanceDetailType GetPerformanceDetailType() { - switch (Type) + return Type switch { - case EffectType.BiquadFilter: - return PerformanceDetailType.BiquadFilter; - case EffectType.AuxiliaryBuffer: - return PerformanceDetailType.Aux; - case EffectType.Delay: - return PerformanceDetailType.Delay; - case EffectType.Reverb: - return PerformanceDetailType.Reverb; - case EffectType.Reverb3d: - return PerformanceDetailType.Reverb3d; - case EffectType.BufferMix: - return PerformanceDetailType.Mix; - case EffectType.Limiter: - return PerformanceDetailType.Limiter; - case EffectType.CaptureBuffer: - return PerformanceDetailType.CaptureBuffer; - case EffectType.Compressor: - return PerformanceDetailType.Compressor; - default: - throw new NotImplementedException($"{Type}"); - } + EffectType.BiquadFilter => PerformanceDetailType.BiquadFilter, + EffectType.AuxiliaryBuffer => PerformanceDetailType.Aux, + EffectType.Delay => PerformanceDetailType.Delay, + EffectType.Reverb => PerformanceDetailType.Reverb, + EffectType.Reverb3d => PerformanceDetailType.Reverb3d, + EffectType.BufferMix => PerformanceDetailType.Mix, + EffectType.Limiter => PerformanceDetailType.Limiter, + EffectType.CaptureBuffer => PerformanceDetailType.CaptureBuffer, + EffectType.Compressor => PerformanceDetailType.Compressor, + _ => throw new NotImplementedException($"{Type}"), + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs index de91046dc..b987f7c85 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/BiquadFilterEffect.cs @@ -64,4 +64,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.Status = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs index 82c0a055a..d6cb9cfa3 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/BufferMixEffect.cs @@ -46,4 +46,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect UpdateUsageStateForCommandGeneration(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs index c445798d4..5be4b4ed5 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/CaptureBufferEffect.cs @@ -79,4 +79,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect UpdateUsageStateForCommandGeneration(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs index 3f5d70bcf..43cabb7db 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/DelayEffect.cs @@ -90,4 +90,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.Status = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs index bfb6528b4..619f31100 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/EffectContext.cs @@ -120,4 +120,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs index 6e17ef3d1..3e2f7326d 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/LimiterEffect.cs @@ -92,4 +92,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect destState = srcState; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs index 473fddb84..f9d7f4943 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/Reverb3dEffect.cs @@ -89,4 +89,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.ParameterStatus = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs index e1543fd17..6fdf8fc23 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/ReverbEffect.cs @@ -92,4 +92,4 @@ namespace Ryujinx.Audio.Renderer.Server.Effect Parameter.Status = UsageState.Enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs b/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs index 8648aa2ca..da7172244 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Effect/UsageState.cs @@ -23,6 +23,6 @@ namespace Ryujinx.Audio.Renderer.Server.Effect /// /// The effect is disabled. /// - Disabled + Disabled, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs b/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs index 4872ddb3a..27b22363a 100644 --- a/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs +++ b/src/Ryujinx.Audio/Renderer/Server/ICommandProcessingTimeEstimator.cs @@ -37,4 +37,4 @@ namespace Ryujinx.Audio.Renderer.Server uint Estimate(CaptureBufferCommand command); uint Estimate(CompressorCommand command); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs index 5fd6b2b92..a7ec4cf51 100644 --- a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs +++ b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/AddressInfo.cs @@ -27,9 +27,9 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// public DspAddress ForceMappedDspAddress; - private unsafe ref MemoryPoolState MemoryPoolState => ref *_memoryPools; + private readonly unsafe ref MemoryPoolState MemoryPoolState => ref *_memoryPools; - public unsafe bool HasMemoryPoolState => (IntPtr)_memoryPools != IntPtr.Zero; + public readonly unsafe bool HasMemoryPoolState => (IntPtr)_memoryPools != IntPtr.Zero; /// /// Create an new empty . @@ -55,7 +55,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool CpuAddress = cpuAddress, _memoryPools = MemoryPoolState.Null, Size = size, - ForceMappedDspAddress = 0 + ForceMappedDspAddress = 0, }; } } @@ -105,7 +105,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// Check if the is mapped. /// /// Returns true if the is mapped. - public bool HasMappedMemoryPool() + public readonly bool HasMappedMemoryPool() { return HasMemoryPoolState && MemoryPoolState.IsMapped(); } @@ -115,7 +115,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// /// If true, mark the as used. /// Returns the DSP address associated to the . - public DspAddress GetReference(bool markUsed) + public readonly DspAddress GetReference(bool markUsed) { if (!HasMappedMemoryPool()) { @@ -130,4 +130,4 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool return MemoryPoolState.Translate(CpuAddress, Size); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs index 69466bab5..91bd5dbf5 100644 --- a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/MemoryPoolState.cs @@ -26,7 +26,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// /// located on the DSP side for system use. /// - Dsp + Dsp, } /// @@ -69,7 +69,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool CpuAddress = 0, DspAddress = 0, Size = 0, - Location = location + Location = location, }; } @@ -90,7 +90,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// The . /// The size. /// True if the is contained inside the . - public bool Contains(CpuAddress targetCpuAddress, ulong size) + public readonly bool Contains(CpuAddress targetCpuAddress, ulong size) { if (CpuAddress <= targetCpuAddress && size + targetCpuAddress <= Size + CpuAddress) { @@ -106,7 +106,7 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// The . /// The size. /// the target DSP address. - public DspAddress Translate(CpuAddress targetCpuAddress, ulong size) + public readonly DspAddress Translate(CpuAddress targetCpuAddress, ulong size) { if (Contains(targetCpuAddress, size) && IsMapped()) { @@ -122,9 +122,9 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// Is the mapped on the DSP? /// /// Returns true if the is mapped on the DSP. - public bool IsMapped() + public readonly bool IsMapped() { return DspAddress != 0; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs index 6c79da157..391b80f8d 100644 --- a/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs +++ b/src/Ryujinx.Audio/Renderer/Server/MemoryPool/PoolMapper.cs @@ -40,23 +40,23 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool /// /// unmapping failed. /// - UnmapError = 3 + UnmapError = 3, } /// /// The handle of the process owning the CPU memory manipulated. /// - private uint _processHandle; + private readonly uint _processHandle; /// /// The that will be manipulated. /// - private Memory _memoryPools; + private readonly Memory _memoryPools; /// /// If set to true, this will try to force map memory pool even if their state are considered invalid. /// - private bool _isForceMapEnabled; + private readonly bool _isForceMapEnabled; /// /// Create a new used for system mapping. @@ -125,7 +125,8 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool { return CurrentProcessPseudoHandle; } - else if (memoryPool.Location == MemoryPoolState.LocationType.Dsp) + + if (memoryPool.Location == MemoryPoolState.LocationType.Dsp) { return _processHandle; } @@ -234,13 +235,11 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool return true; } - else - { - errorInfo.ErrorCode = ResultCode.InvalidAddressInfo; - errorInfo.ExtraErrorInfo = addressInfo.CpuAddress; - return _isForceMapEnabled; - } + errorInfo.ErrorCode = ResultCode.InvalidAddressInfo; + errorInfo.ExtraErrorInfo = addressInfo.CpuAddress; + + return _isForceMapEnabled; } /// @@ -256,19 +255,19 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool MemoryPoolUserState outputState; - const uint pageSize = 0x1000; + const uint PageSize = 0x1000; if (inputState != MemoryPoolUserState.RequestAttach && inputState != MemoryPoolUserState.RequestDetach) { return UpdateResult.Success; } - if (inParameter.CpuAddress == 0 || (inParameter.CpuAddress % pageSize) != 0) + if (inParameter.CpuAddress == 0 || (inParameter.CpuAddress % PageSize) != 0) { return UpdateResult.InvalidParameter; } - if (inParameter.Size == 0 || (inParameter.Size % pageSize) != 0) + if (inParameter.Size == 0 || (inParameter.Size % PageSize) != 0) { return UpdateResult.InvalidParameter; } @@ -363,4 +362,4 @@ namespace Ryujinx.Audio.Renderer.Server.MemoryPool } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs b/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs index cda6f737c..8991ceaf9 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Mix/MixContext.cs @@ -206,7 +206,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix { UpdateDistancesFromFinalMix(); - int[] sortedMixesTemp = _sortedMixes.Slice(0, (int)GetCount()).ToArray(); + int[] sortedMixesTemp = _sortedMixes[..(int)GetCount()].ToArray(); Array.Sort(sortedMixesTemp, (a, b) => { @@ -248,12 +248,10 @@ namespace Ryujinx.Audio.Renderer.Server.Mix return isValid; } - else - { - UpdateMixBufferOffset(); - return true; - } + UpdateMixBufferOffset(); + + return true; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs b/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs index 146e67811..88ae44831 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Mix/MixState.cs @@ -7,7 +7,6 @@ using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - using static Ryujinx.Audio.Constants; namespace Ryujinx.Audio.Renderer.Server.Mix @@ -66,7 +65,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// /// The effect processing order storage. /// - private IntPtr _effectProcessingOrderArrayPointer; + private readonly IntPtr _effectProcessingOrderArrayPointer; /// /// The max element count that can be found in the effect processing order storage. @@ -120,7 +119,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// /// The array used to order effects associated to this mix. /// - public Span EffectProcessingOrderArray + public readonly Span EffectProcessingOrderArray { get { @@ -175,7 +174,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// /// Clear the to its default state. /// - public void ClearEffectProcessingOrder() + public readonly void ClearEffectProcessingOrder() { EffectProcessingOrderArray.Fill(-1); } @@ -184,7 +183,7 @@ namespace Ryujinx.Audio.Renderer.Server.Mix /// Return true if the mix has any destinations. /// /// True if the mix has any destinations. - public bool HasAnyDestination() + public readonly bool HasAnyDestination() { return DestinationMixId != UnusedMixId || DestinationSplitterId != UnusedSplitterId; } @@ -310,4 +309,4 @@ namespace Ryujinx.Audio.Renderer.Server.Mix return isDirty; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs index dbe59cb0d..ffabf4676 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceDetailEntry.cs @@ -49,4 +49,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// The type to use. void SetDetailType(PerformanceDetailType detailType); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs index 9888a4cc1..a0178187b 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceEntry.cs @@ -43,4 +43,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// The type to use. void SetEntryType(PerformanceEntryType type); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs index 21876b4b4..deacd8ccc 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/IPerformanceHeader.cs @@ -77,4 +77,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// The total count of detailed entries in this frame. void SetEntryDetailCount(int entryDetailCount); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs index 22704c0d1..a4024607c 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion1.cs @@ -34,22 +34,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -69,4 +69,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs index 05ecda9b6..f10e2937e 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceDetailVersion2.cs @@ -34,22 +34,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -69,4 +69,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs index 1b8d8668a..d24b96a27 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryAddresses.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance BaseMemory.Span[(int)ProcessingTimeOffset / 4] = (int)(endTimeNano / 1000) - BaseMemory.Span[(int)StartTimeOffset / 4]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs index fa2d32164..2c407670f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion1.cs @@ -29,22 +29,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs index 49d4b3ce0..eb96a3141 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceEntryVersion2.cs @@ -29,22 +29,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public PerformanceEntryType EntryType; - public int GetProcessingTime() + public readonly int GetProcessingTime() { return ProcessingTime; } - public int GetProcessingTimeOffset() + public readonly int GetProcessingTimeOffset() { return 8; } - public int GetStartTime() + public readonly int GetStartTime() { return StartTime; } - public int GetStartTimeOffset() + public readonly int GetStartTimeOffset() { return 4; } @@ -59,4 +59,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NodeId = nodeId; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs index 5fe6bff06..5aeb703c5 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion1.cs @@ -38,22 +38,22 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// public uint VoiceDropCount; - public int GetEntryCount() + public readonly int GetEntryCount() { return EntryCount; } - public int GetEntryCountOffset() + public readonly int GetEntryCountOffset() { return 4; } - public int GetEntryDetailCount() + public readonly int GetEntryDetailCount() { return EntryDetailCount; } - public void SetDspRunningBehind(bool isRunningBehind) + public readonly void SetDspRunningBehind(bool isRunningBehind) { // NOTE: Not present in version 1 } @@ -68,7 +68,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance EntryDetailCount = entryDetailCount; } - public void SetIndex(uint index) + public readonly void SetIndex(uint index) { // NOTE: Not present in version 1 } @@ -83,7 +83,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance NextOffset = nextOffset; } - public void SetStartRenderingTicks(ulong startTicks) + public readonly void SetStartRenderingTicks(ulong startTicks) { // NOTE: not present in version 1 } @@ -98,4 +98,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance VoiceDropCount = voiceCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs index a18229686..d6e0ffc8b 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceFrameHeaderVersion2.cs @@ -54,17 +54,17 @@ namespace Ryujinx.Audio.Renderer.Server.Performance [MarshalAs(UnmanagedType.I1)] public bool IsDspRunningBehind; - public int GetEntryCount() + public readonly int GetEntryCount() { return EntryCount; } - public int GetEntryCountOffset() + public readonly int GetEntryCountOffset() { return 4; } - public int GetEntryDetailCount() + public readonly int GetEntryDetailCount() { return EntryDetailCount; } @@ -114,4 +114,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance VoiceDropCount = voiceCount; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs index f996441c0..0a035916c 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManager.cs @@ -22,11 +22,12 @@ namespace Ryujinx.Audio.Renderer.Server.Performance PerformanceEntryVersion2, PerformanceDetailVersion2>.GetRequiredBufferSizeForPerformanceMetricsPerFrame(ref parameter); } - else if (version == 1) + + if (version == 1) { return (ulong)PerformanceManagerGeneric.GetRequiredBufferSizeForPerformanceMetricsPerFrame(ref parameter); + PerformanceEntryVersion1, + PerformanceDetailVersion1>.GetRequiredBufferSizeForPerformanceMetricsPerFrame(ref parameter); } throw new NotImplementedException($"Unknown Performance metrics data format version {version}"); @@ -90,17 +91,12 @@ namespace Ryujinx.Audio.Renderer.Server.Performance { uint version = behaviourContext.GetPerformanceMetricsDataFormat(); - switch (version) + return version switch { - case 1: - return new PerformanceManagerGeneric(performanceBuffer, - ref parameter); - case 2: - return new PerformanceManagerGeneric(performanceBuffer, - ref parameter); - default: - throw new NotImplementedException($"Unknown Performance metrics data format version {version}"); - } + 1 => new PerformanceManagerGeneric(performanceBuffer, ref parameter), + 2 => new PerformanceManagerGeneric(performanceBuffer, ref parameter), + _ => throw new NotImplementedException($"Unknown Performance metrics data format version {version}"), + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs index 18e77391d..5a70a1bcf 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Performance/PerformanceManagerGeneric.cs @@ -25,20 +25,20 @@ namespace Ryujinx.Audio.Renderer.Server.Performance /// private const int MaxFrameDetailCount = 100; - private Memory _buffer; - private Memory _historyBuffer; + private readonly Memory _buffer; + private readonly Memory _historyBuffer; - private Memory CurrentBuffer => _buffer.Slice(0, _frameSize); - private Memory CurrentBufferData => CurrentBuffer.Slice(Unsafe.SizeOf()); + private Memory CurrentBuffer => _buffer[.._frameSize]; + private Memory CurrentBufferData => CurrentBuffer[Unsafe.SizeOf()..]; private ref THeader CurrentHeader => ref MemoryMarshal.Cast(CurrentBuffer.Span)[0]; - private Span Entries => MemoryMarshal.Cast(CurrentBufferData.Span.Slice(0, GetEntriesSize())); + private Span Entries => MemoryMarshal.Cast(CurrentBufferData.Span[..GetEntriesSize()]); private Span EntriesDetail => MemoryMarshal.Cast(CurrentBufferData.Span.Slice(GetEntriesSize(), GetEntriesDetailSize())); - private int _frameSize; - private int _availableFrameCount; - private int _entryCountPerFrame; + private readonly int _frameSize; + private readonly int _availableFrameCount; + private readonly int _entryCountPerFrame; private int _detailTarget; private int _entryIndex; private int _entryDetailIndex; @@ -56,7 +56,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance _historyFrameIndex = 0; - _historyBuffer = _buffer.Slice(_frameSize); + _historyBuffer = _buffer[_frameSize..]; SetupNewHeader(); } @@ -130,7 +130,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance Span inputEntries = GetEntriesFromBuffer(_historyBuffer.Span, _indexHistoryRead); Span inputEntriesDetail = GetEntriesDetailFromBuffer(_historyBuffer.Span, _indexHistoryRead); - Span targetSpan = performanceOutput.Slice(nextOffset); + Span targetSpan = performanceOutput[nextOffset..]; // NOTE: We check for the space for two headers for the final blank header. int requiredSpace = Unsafe.SizeOf() + Unsafe.SizeOf() * inputHeader.GetEntryCount() @@ -146,7 +146,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance nextOffset += Unsafe.SizeOf(); - Span outputEntries = MemoryMarshal.Cast(performanceOutput.Slice(nextOffset)); + Span outputEntries = MemoryMarshal.Cast(performanceOutput[nextOffset..]); int totalProcessingTime = 0; @@ -168,7 +168,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance } } - Span outputEntriesDetail = MemoryMarshal.Cast(performanceOutput.Slice(nextOffset)); + Span outputEntriesDetail = MemoryMarshal.Cast(performanceOutput[nextOffset..]); int effectiveEntryDetailCount = 0; @@ -198,7 +198,7 @@ namespace Ryujinx.Audio.Renderer.Server.Performance if (nextOffset < performanceOutput.Length && (performanceOutput.Length - nextOffset) >= Unsafe.SizeOf()) { - ref THeader outputHeader = ref MemoryMarshal.Cast(performanceOutput.Slice(nextOffset))[0]; + ref THeader outputHeader = ref MemoryMarshal.Cast(performanceOutput[nextOffset..])[0]; outputHeader = default; } @@ -208,9 +208,11 @@ namespace Ryujinx.Audio.Renderer.Server.Performance public override bool GetNextEntry(out PerformanceEntryAddresses performanceEntry, PerformanceEntryType entryType, int nodeId) { - performanceEntry = new PerformanceEntryAddresses(); - performanceEntry.BaseMemory = SpanMemoryManager.Cast(CurrentBuffer); - performanceEntry.EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(); + performanceEntry = new PerformanceEntryAddresses + { + BaseMemory = SpanMemoryManager.Cast(CurrentBuffer), + EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(), + }; uint baseEntryOffset = (uint)(Unsafe.SizeOf() + Unsafe.SizeOf() * _entryIndex); @@ -237,9 +239,11 @@ namespace Ryujinx.Audio.Renderer.Server.Performance return false; } - performanceEntry = new PerformanceEntryAddresses(); - performanceEntry.BaseMemory = SpanMemoryManager.Cast(CurrentBuffer); - performanceEntry.EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(); + performanceEntry = new PerformanceEntryAddresses + { + BaseMemory = SpanMemoryManager.Cast(CurrentBuffer), + EntryCountOffset = (uint)CurrentHeader.GetEntryCountOffset(), + }; uint baseEntryOffset = (uint)(Unsafe.SizeOf() + GetEntriesSize() + Unsafe.SizeOf() * _entryDetailIndex); @@ -301,4 +305,4 @@ namespace Ryujinx.Audio.Renderer.Server.Performance } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs b/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs index 164567806..090850018 100644 --- a/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/RendererSystemContext.cs @@ -45,4 +45,4 @@ namespace Ryujinx.Audio.Renderer.Server /// public Memory DepopBuffer; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs index f7b639975..d36c5e260 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/BaseSink.cs @@ -99,4 +99,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink errorInfo = new ErrorInfo(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs index 722d8c4b4..097757988 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/CircularBufferSink.cs @@ -106,4 +106,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink base.CleanUp(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs index de345d3ad..e03fe11d4 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/DeviceSink.cs @@ -72,4 +72,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink outStatus = new SinkOutStatus(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs b/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs index b57d39908..951984d8c 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Sink/SinkContext.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Server.Sink return ref _sinks[id]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs index 91877cdda..e408692ab 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterContext.cs @@ -101,10 +101,8 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter return size; } - else - { - return size; - } + + return size; } /// @@ -164,10 +162,10 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter { ref SplitterState splitter = ref GetState(parameter.Id); - splitter.Update(this, ref parameter, input.Slice(Unsafe.SizeOf())); + splitter.Update(this, ref parameter, input[Unsafe.SizeOf()..]); } - input = input.Slice(0x1C + (int)parameter.DestinationCount * 4); + input = input[(0x1C + parameter.DestinationCount * 4)..]; } } } @@ -194,7 +192,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter destination.Update(parameter); } - input = input.Slice(Unsafe.SizeOf()); + input = input[Unsafe.SizeOf()..]; } } } @@ -229,12 +227,10 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter return true; } - else - { - consumedSize = 0; - return false; - } + consumedSize = 0; + + return false; } /// @@ -300,4 +296,4 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs index c074e4a72..1faf7921f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterDestination.cs @@ -65,7 +65,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// /// Get the of the next element or if not present. /// - public Span Next + public readonly Span Next { get { @@ -138,7 +138,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// Return true if the is used and has a destination. /// /// True if the is used and has a destination. - public bool IsConfigured() + public readonly bool IsConfigured() { return IsUsed && DestinationId != Constants.UnusedMixId; } @@ -160,8 +160,8 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// public void ClearVolumes() { - MixBufferVolume.Fill(0); - PreviousMixBufferVolume.Fill(0); + MixBufferVolume.Clear(); + PreviousMixBufferVolume.Clear(); } /// @@ -190,4 +190,4 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs index 15a0c6ba4..e08ee9ea7 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Splitter/SplitterState.cs @@ -43,7 +43,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// /// Span to the first element of the linked list of . /// - public Span Destinations + public readonly Span Destinations { get { @@ -63,7 +63,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter Id = id; } - public Span GetData(int index) + public readonly Span GetData(int index) { int i = 0; @@ -95,7 +95,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// Utility function to apply a given to all . /// /// The action to execute on each elements. - private void ForEachDestination(SpanAction action) + private readonly void ForEachDestination(SpanAction action) { Span temp = Destinations; @@ -183,7 +183,7 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter /// /// Update the internal state of this instance. /// - public void UpdateInternalState() + public readonly void UpdateInternalState() { ForEachDestination((destination, _) => destination[0].UpdateInternalState()); } @@ -218,4 +218,4 @@ namespace Ryujinx.Audio.Renderer.Server.Splitter } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs b/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs index 5cf539c6d..22eebc7cc 100644 --- a/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs +++ b/src/Ryujinx.Audio/Renderer/Server/StateUpdater.cs @@ -22,15 +22,15 @@ namespace Ryujinx.Audio.Renderer.Server public class StateUpdater { private readonly ReadOnlyMemory _inputOrigin; - private ReadOnlyMemory _outputOrigin; + private readonly ReadOnlyMemory _outputOrigin; private ReadOnlyMemory _input; private Memory _output; - private uint _processHandle; + private readonly uint _processHandle; private BehaviourContext _behaviourContext; private UpdateDataHeader _inputHeader; - private Memory _outputHeader; + private readonly Memory _outputHeader; private ref UpdateDataHeader OutputHeader => ref _outputHeader.Span[0]; @@ -45,9 +45,9 @@ namespace Ryujinx.Audio.Renderer.Server _inputHeader = SpanIOHelper.Read(ref _input); - _outputHeader = SpanMemoryManager.Cast(_output.Slice(0, Unsafe.SizeOf())); + _outputHeader = SpanMemoryManager.Cast(_output[..Unsafe.SizeOf()]); OutputHeader.Initialize(_behaviourContext.UserRevision); - _output = _output.Slice(Unsafe.SizeOf()); + _output = _output[Unsafe.SizeOf()..]; } public ResultCode UpdateBehaviourContext() @@ -72,7 +72,7 @@ namespace Ryujinx.Audio.Renderer.Server public ResultCode UpdateMemoryPools(Span memoryPools) { - PoolMapper mapper = new PoolMapper(_processHandle, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, _behaviourContext.IsMemoryPoolForceMappingEnabled()); if (memoryPools.Length * Unsafe.SizeOf() != _inputHeader.MemoryPoolsSize) { @@ -136,11 +136,11 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.VoicesSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.VoicesSize].Span); - _input = _input.Slice((int)_inputHeader.VoicesSize); + _input = _input[(int)_inputHeader.VoicesSize..]; - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); // First make everything not in use. for (int i = 0; i < context.GetCount(); i++) @@ -151,7 +151,7 @@ namespace Ryujinx.Audio.Renderer.Server } Memory[] voiceUpdateStatesArray = ArrayPool>.Shared.Rent(Constants.VoiceChannelCountMax); - + Span> voiceUpdateStates = voiceUpdateStatesArray.AsSpan(0, Constants.VoiceChannelCountMax); // Start processing @@ -218,42 +218,20 @@ namespace Ryujinx.Audio.Renderer.Server { effect.ForceUnmapBuffers(mapper); - switch (parameter.Type) + effect = parameter.Type switch { - case EffectType.Invalid: - effect = new BaseEffect(); - break; - case EffectType.BufferMix: - effect = new BufferMixEffect(); - break; - case EffectType.AuxiliaryBuffer: - effect = new AuxiliaryBufferEffect(); - break; - case EffectType.Delay: - effect = new DelayEffect(); - break; - case EffectType.Reverb: - effect = new ReverbEffect(); - break; - case EffectType.Reverb3d: - effect = new Reverb3dEffect(); - break; - case EffectType.BiquadFilter: - effect = new BiquadFilterEffect(); - break; - case EffectType.Limiter: - effect = new LimiterEffect(); - break; - case EffectType.CaptureBuffer: - effect = new CaptureBufferEffect(); - break; - case EffectType.Compressor: - effect = new CompressorEffect(); - break; - - default: - throw new NotImplementedException($"EffectType {parameter.Type} not implemented!"); - } + EffectType.Invalid => new BaseEffect(), + EffectType.BufferMix => new BufferMixEffect(), + EffectType.AuxiliaryBuffer => new AuxiliaryBufferEffect(), + EffectType.Delay => new DelayEffect(), + EffectType.Reverb => new ReverbEffect(), + EffectType.Reverb3d => new Reverb3dEffect(), + EffectType.BiquadFilter => new BiquadFilterEffect(), + EffectType.Limiter => new LimiterEffect(), + EffectType.CaptureBuffer => new CaptureBufferEffect(), + EffectType.Compressor => new CompressorEffect(), + _ => throw new NotImplementedException($"EffectType {parameter.Type} not implemented!"), + }; } public ResultCode UpdateEffects(EffectContext context, bool isAudioRendererActive, Memory memoryPools) @@ -262,10 +240,8 @@ namespace Ryujinx.Audio.Renderer.Server { return UpdateEffectsVersion2(context, isAudioRendererActive, memoryPools); } - else - { - return UpdateEffectsVersion1(context, isAudioRendererActive, memoryPools); - } + + return UpdateEffectsVersion1(context, isAudioRendererActive, memoryPools); } public ResultCode UpdateEffectsVersion2(EffectContext context, bool isAudioRendererActive, Memory memoryPools) @@ -277,11 +253,11 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.EffectsSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.EffectsSize].Span); - _input = _input.Slice((int)_inputHeader.EffectsSize); + _input = _input[(int)_inputHeader.EffectsSize..]; - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); for (int i = 0; i < context.GetCount(); i++) { @@ -333,11 +309,11 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.EffectsSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.EffectsSize].Span); - _input = _input.Slice((int)_inputHeader.EffectsSize); + _input = _input[(int)_inputHeader.EffectsSize..]; - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); for (int i = 0; i < context.GetCount(); i++) { @@ -376,17 +352,15 @@ namespace Ryujinx.Audio.Renderer.Server { if (context.Update(_input.Span, out int consumedSize)) { - _input = _input.Slice(consumedSize); + _input = _input[consumedSize..]; return ResultCode.Success; } - else - { - return ResultCode.InvalidUpdateInfo; - } + + return ResultCode.InvalidUpdateInfo; } - private bool CheckMixParametersValidity(MixContext mixContext, uint mixBufferCount, uint inputMixCount, ReadOnlySpan parameters) + private static bool CheckMixParametersValidity(MixContext mixContext, uint mixBufferCount, uint inputMixCount, ReadOnlySpan parameters) { uint maxMixStateCount = mixContext.GetCount(); uint totalRequiredMixBufferCount = 0; @@ -439,12 +413,12 @@ namespace Ryujinx.Audio.Renderer.Server if (_behaviourContext.IsMixInParameterDirtyOnlyUpdateSupported()) { - _input = _input.Slice(Unsafe.SizeOf()); + _input = _input[Unsafe.SizeOf()..]; } - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Span.Slice(0, (int)inputMixSize)); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Span[..(int)inputMixSize]); - _input = _input.Slice((int)inputMixSize); + _input = _input[(int)inputMixSize..]; if (CheckMixParametersValidity(mixContext, mixBufferCount, mixCount, parameters)) { @@ -506,25 +480,18 @@ namespace Ryujinx.Audio.Renderer.Server { sink.CleanUp(); - switch (parameter.Type) + sink = parameter.Type switch { - case SinkType.Invalid: - sink = new BaseSink(); - break; - case SinkType.CircularBuffer: - sink = new CircularBufferSink(); - break; - case SinkType.Device: - sink = new DeviceSink(); - break; - default: - throw new NotImplementedException($"SinkType {parameter.Type} not implemented!"); - } + SinkType.Invalid => new BaseSink(), + SinkType.CircularBuffer => new CircularBufferSink(), + SinkType.Device => new DeviceSink(), + _ => throw new NotImplementedException($"SinkType {parameter.Type} not implemented!"), + }; } public ResultCode UpdateSinks(SinkContext context, Memory memoryPools) { - PoolMapper mapper = new PoolMapper(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); + PoolMapper mapper = new(_processHandle, memoryPools, _behaviourContext.IsMemoryPoolForceMappingEnabled()); if (context.GetCount() * Unsafe.SizeOf() != _inputHeader.SinksSize) { @@ -533,9 +500,9 @@ namespace Ryujinx.Audio.Renderer.Server int initialOutputSize = _output.Length; - ReadOnlySpan parameters = MemoryMarshal.Cast(_input.Slice(0, (int)_inputHeader.SinksSize).Span); + ReadOnlySpan parameters = MemoryMarshal.Cast(_input[..(int)_inputHeader.SinksSize].Span); - _input = _input.Slice((int)_inputHeader.SinksSize); + _input = _input[(int)_inputHeader.SinksSize..]; for (int i = 0; i < context.GetCount(); i++) { @@ -640,4 +607,4 @@ namespace Ryujinx.Audio.Renderer.Server return ResultCode.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs index 5d82ce0b6..0db61c5e6 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererExecutionMode.cs @@ -14,6 +14,6 @@ namespace Ryujinx.Audio.Renderer.Server.Types /// Audio renderer operation needs to be done manually via ExecuteAudioRenderer. /// /// This is not supported on the DSP and is as such stubbed. - Manual + Manual, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs index 5ad27b0b1..fd9e231cf 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Types/AudioRendererRenderingDevice.cs @@ -19,6 +19,6 @@ namespace Ryujinx.Audio.Renderer.Server.Types /// /// Only supports . /// - Cpu + Cpu, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs b/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs index 25cc34a8f..46aae05ab 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Types/PlayState.cs @@ -34,6 +34,6 @@ namespace Ryujinx.Audio.Renderer.Server.Types /// /// The user can resume to the state. /// - Paused + Paused, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs index a45fa8e5b..a3c442a45 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerBufferState.cs @@ -11,4 +11,4 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler public bool Initialized; public int Phase; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs index b37988fed..dbc2c9b3f 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerManager.cs @@ -11,22 +11,22 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler /// /// Work buffer for upsampler. /// - private Memory _upSamplerWorkBuffer; + private readonly Memory _upSamplerWorkBuffer; /// /// Global lock of the object. /// - private object Lock = new object(); + private readonly object _lock = new(); /// /// The upsamplers instances. /// - private UpsamplerState[] _upsamplers; + private readonly UpsamplerState[] _upsamplers; /// /// The count of upsamplers. /// - private uint _count; + private readonly uint _count; /// /// Create a new . @@ -49,7 +49,7 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler { int workBufferOffset = 0; - lock (Lock) + lock (_lock) { for (int i = 0; i < _count; i++) { @@ -73,7 +73,7 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler /// The index of the to free. public void Free(int index) { - lock (Lock) + lock (_lock) { Debug.Assert(_upsamplers[index] != null); @@ -81,4 +81,4 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs index e508f35b4..39a58c91a 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Upsampler/UpsamplerState.cs @@ -20,12 +20,12 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler /// /// The index of the . (used to free it) /// - private int _index; + private readonly int _index; /// /// The . /// - private UpsamplerManager _manager; + private readonly UpsamplerManager _manager; /// /// The source sample count. @@ -65,4 +65,4 @@ namespace Ryujinx.Audio.Renderer.Server.Upsampler _manager.Free(_index); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs index 939d92944..e3d5f797d 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceChannelResource.cs @@ -37,4 +37,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice Mix.AsSpan().CopyTo(PreviousMix.AsSpan()); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs index 1c57b71be..7ce7143ed 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceContext.cs @@ -126,7 +126,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice _sortedVoices.Span[i] = i; } - int[] sortedVoicesTemp = _sortedVoices.Slice(0, (int)GetCount()).ToArray(); + int[] sortedVoicesTemp = _sortedVoices[..(int)GetCount()].ToArray(); Array.Sort(sortedVoicesTemp, (a, b) => { @@ -146,4 +146,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice sortedVoicesTemp.AsSpan().CopyTo(_sortedVoices.Span); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs index 0bf53c544..225f7d31b 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/VoiceState.cs @@ -1,5 +1,6 @@ using Ryujinx.Audio.Common; using Ryujinx.Audio.Renderer.Common; +using Ryujinx.Audio.Renderer.Dsp.State; using Ryujinx.Audio.Renderer.Parameter; using Ryujinx.Audio.Renderer.Server.MemoryPool; using Ryujinx.Common.Memory; @@ -9,6 +10,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using static Ryujinx.Audio.Renderer.Common.BehaviourParameter; using static Ryujinx.Audio.Renderer.Parameter.VoiceInParameter; +using PlayState = Ryujinx.Audio.Renderer.Server.Types.PlayState; namespace Ryujinx.Audio.Renderer.Server.Voice { @@ -65,12 +67,12 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// /// The current voice . /// - public Types.PlayState PlayState; + public PlayState PlayState; /// /// The previous voice . /// - public Types.PlayState PreviousPlayState; + public PlayState PreviousPlayState; /// /// The priority of the voice. @@ -192,7 +194,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice DataSourceStateUnmapped = false; BufferInfoUnmapped = false; FlushWaveBufferCount = 0; - PlayState = Types.PlayState.Stopped; + PlayState = PlayState.Stopped; Priority = Constants.VoiceLowestPriority; Id = 0; NodeId = 0; @@ -202,7 +204,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice Pitch = 0.0f; Volume = 0.0f; PreviousVolume = 0.0f; - BiquadFilters.AsSpan().Fill(new BiquadFilterParameter()); + BiquadFilters.AsSpan().Clear(); WaveBuffersCount = 0; WaveBuffersIndex = 0; MixId = Constants.UnusedMixId; @@ -233,7 +235,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// Check if the voice needs to be skipped. /// /// Returns true if the voice needs to be skipped. - public bool ShouldSkip() + public readonly bool ShouldSkip() { return !InUse || WaveBuffersCount == 0 || DataSourceStateUnmapped || BufferInfoUnmapped || VoiceDropFlag; } @@ -242,7 +244,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// Return true if the mix has any destinations. /// /// True if the mix has any destinations. - public bool HasAnyDestination() + public readonly bool HasAnyDestination() { return MixId != Constants.UnusedMixId || SplitterId != Constants.UnusedSplitterId; } @@ -252,7 +254,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// /// The user parameter. /// Return true, if the server voice information needs to be updated. - private bool ShouldUpdateParameters(ref VoiceInParameter parameter) + private readonly bool ShouldUpdateParameters(ref VoiceInParameter parameter) { if (DataSourceStateAddressInfo.CpuAddress == parameter.DataSourceStateAddress) { @@ -338,31 +340,31 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// Update the internal play state from user play state. /// /// The target user play state. - public void UpdatePlayState(PlayState userPlayState) + public void UpdatePlayState(Common.PlayState userPlayState) { - Types.PlayState oldServerPlayState = PlayState; + PlayState oldServerPlayState = PlayState; PreviousPlayState = oldServerPlayState; - Types.PlayState newServerPlayState; + PlayState newServerPlayState; switch (userPlayState) { case Common.PlayState.Start: - newServerPlayState = Types.PlayState.Started; + newServerPlayState = PlayState.Started; break; case Common.PlayState.Stop: - if (oldServerPlayState == Types.PlayState.Stopped) + if (oldServerPlayState == PlayState.Stopped) { return; } - newServerPlayState = Types.PlayState.Stopping; + newServerPlayState = PlayState.Stopping; break; case Common.PlayState.Pause: - newServerPlayState = Types.PlayState.Paused; + newServerPlayState = PlayState.Paused; break; default: @@ -434,7 +436,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice for (int i = 0; i < parameter.ChannelCount; i++) { - voiceUpdateStates[i].Span[0].IsWaveBufferValid.Fill(false); + voiceUpdateStates[i].Span[0].IsWaveBufferValid.Clear(); } } @@ -530,7 +532,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice Memory dspSharedState = context.GetUpdateStateForDsp(channelResourceId); - MemoryMarshal.Cast(dspSharedState.Span).Fill(0); + MemoryMarshal.Cast(dspSharedState.Span).Clear(); voiceChannelResource.UpdateState(); } @@ -579,7 +581,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice switch (PlayState) { - case Types.PlayState.Started: + case PlayState.Started: for (int i = 0; i < WaveBuffers.Length; i++) { ref WaveBuffer wavebuffer = ref WaveBuffers[i]; @@ -611,7 +613,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice return false; - case Types.PlayState.Stopping: + case PlayState.Stopping: for (int i = 0; i < WaveBuffers.Length; i++) { ref WaveBuffer wavebuffer = ref WaveBuffers[i]; @@ -638,18 +640,18 @@ namespace Ryujinx.Audio.Renderer.Server.Voice voiceUpdateState.Offset = 0; voiceUpdateState.PlayedSampleCount = 0; - voiceUpdateState.Pitch.AsSpan().Fill(0); + voiceUpdateState.Pitch.AsSpan().Clear(); voiceUpdateState.Fraction = 0; - voiceUpdateState.LoopContext = new Dsp.State.AdpcmLoopContext(); + voiceUpdateState.LoopContext = new AdpcmLoopContext(); } - PlayState = Types.PlayState.Stopped; - WasPlaying = PreviousPlayState == Types.PlayState.Started; + PlayState = PlayState.Stopped; + WasPlaying = PreviousPlayState == PlayState.Started; return WasPlaying; - case Types.PlayState.Stopped: - case Types.PlayState.Paused: + case PlayState.Stopped: + case PlayState.Paused: foreach (ref WaveBuffer wavebuffer in WaveBuffers.AsSpan()) { wavebuffer.BufferAddressInfo.GetReference(true); @@ -664,7 +666,7 @@ namespace Ryujinx.Audio.Renderer.Server.Voice } } - WasPlaying = PreviousPlayState == Types.PlayState.Started; + WasPlaying = PreviousPlayState == PlayState.Started; return WasPlaying; default: @@ -696,4 +698,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice return UpdateParametersForCommandGeneration(voiceUpdateStates); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs b/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs index 4bf7dd280..a9946ba44 100644 --- a/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs +++ b/src/Ryujinx.Audio/Renderer/Server/Voice/WaveBuffer.cs @@ -71,10 +71,11 @@ namespace Ryujinx.Audio.Renderer.Server.Voice /// A new for use by the . public Common.WaveBuffer ToCommon(int version) { - Common.WaveBuffer waveBuffer = new Common.WaveBuffer(); - - waveBuffer.Buffer = BufferAddressInfo.GetReference(true); - waveBuffer.BufferSize = (uint)BufferAddressInfo.Size; + Common.WaveBuffer waveBuffer = new() + { + Buffer = BufferAddressInfo.GetReference(true), + BufferSize = (uint)BufferAddressInfo.Size, + }; if (ContextAddressInfo.CpuAddress != 0) { @@ -101,4 +102,4 @@ namespace Ryujinx.Audio.Renderer.Server.Voice return waveBuffer; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs b/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs index 973f0672a..8ebf20340 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/AudioProcessorMemoryManager.cs @@ -54,4 +54,4 @@ namespace Ryujinx.Audio.Renderer.Utils { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs b/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs index 8b1054771..8fd0baeae 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/BitArray.cs @@ -11,7 +11,7 @@ namespace Ryujinx.Audio.Renderer.Utils /// /// The backing storage of the . /// - private Memory _storage; + private readonly Memory _storage; /// /// Create a new from . @@ -97,7 +97,7 @@ namespace Ryujinx.Audio.Renderer.Utils [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { - _storage.Span.Fill(0); + _storage.Span.Clear(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs index d49313ea1..bc2313ccf 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/FileHardwareDevice.cs @@ -2,7 +2,6 @@ using Ryujinx.Audio.Integration; using System; using System.IO; using System.Runtime.InteropServices; -using System.Text; namespace Ryujinx.Audio.Renderer.Utils { @@ -12,8 +11,8 @@ namespace Ryujinx.Audio.Renderer.Utils public class FileHardwareDevice : IHardwareDevice { private FileStream _stream; - private uint _channelCount; - private uint _sampleRate; + private readonly uint _channelCount; + private readonly uint _sampleRate; private const int HeaderSize = 44; @@ -82,6 +81,7 @@ namespace Ryujinx.Audio.Renderer.Utils public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -96,4 +96,4 @@ namespace Ryujinx.Audio.Renderer.Utils } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs b/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs index 35c71ae36..26907af91 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Mailbox.cs @@ -9,8 +9,8 @@ namespace Ryujinx.Audio.Renderer.Utils /// The target unmanaged type used public class Mailbox : IDisposable where T : unmanaged { - private BlockingCollection _messageQueue; - private BlockingCollection _responseQueue; + private readonly BlockingCollection _messageQueue; + private readonly BlockingCollection _responseQueue; public Mailbox() { @@ -40,6 +40,7 @@ namespace Ryujinx.Audio.Renderer.Utils public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -52,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Utils } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs index 5b513aff3..7a6edab19 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix2x2.cs @@ -68,4 +68,4 @@ namespace Ryujinx.Audio.Renderer.Utils.Math return m; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs index 415a81fdf..ff0123026 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/Matrix6x6.cs @@ -94,4 +94,4 @@ namespace Ryujinx.Audio.Renderer.Utils.Math M66 = m66; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs index 209a81c46..7b4b7ad1d 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/MatrixHelper.cs @@ -28,7 +28,7 @@ namespace Ryujinx.Audio.Renderer.Dsp X = value2.M11 * value1.X + value2.M12 * value1.Y + value2.M13 * value1.Z + value2.M14 * value1.W, Y = value2.M21 * value1.X + value2.M22 * value1.Y + value2.M23 * value1.Z + value2.M24 * value1.W, Z = value2.M31 * value1.X + value2.M32 * value1.Y + value2.M33 * value1.Z + value2.M34 * value1.W, - W = value2.M41 * value1.X + value2.M42 * value1.Y + value2.M43 * value1.Z + value2.M44 * value1.W + W = value2.M41 * value1.X + value2.M42 * value1.Y + value2.M43 * value1.Z + value2.M44 * value1.W, }; } @@ -42,4 +42,4 @@ namespace Ryujinx.Audio.Renderer.Dsp }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs b/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs index 81bcb6982..303c5e9d0 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/Math/Vector6.cs @@ -53,4 +53,4 @@ namespace Ryujinx.Audio.Renderer.Utils.Math return left * new Vector6(right); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs b/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs index 103fb6a04..4771ae4dd 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/SpanIOHelper.cs @@ -22,12 +22,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - MemoryMarshal.Write(backingMemory.Span.Slice(0, size), ref data); + MemoryMarshal.Write(backingMemory.Span[..size], ref data); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; } /// @@ -42,12 +42,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - MemoryMarshal.Write(backingMemory.Slice(0, size), ref data); + MemoryMarshal.Write(backingMemory[..size], ref data); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; } /// @@ -62,12 +62,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - Span result = MemoryMarshal.Cast(backingMemory.Span.Slice(0, size)); + Span result = MemoryMarshal.Cast(backingMemory.Span[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -84,12 +84,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - Span result = MemoryMarshal.Cast(backingMemory.Slice(0, size)); + Span result = MemoryMarshal.Cast(backingMemory[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -106,12 +106,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - T result = MemoryMarshal.Read(backingMemory.Span.Slice(0, size)); + T result = MemoryMarshal.Read(backingMemory.Span[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -128,12 +128,12 @@ namespace Ryujinx.Audio.Renderer.Utils if (size > backingMemory.Length) { - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(backingMemory), backingMemory.Length, null); } - T result = MemoryMarshal.Read(backingMemory.Slice(0, size)); + T result = MemoryMarshal.Read(backingMemory[..size]); - backingMemory = backingMemory.Slice(size); + backingMemory = backingMemory[size..]; return result; } @@ -168,4 +168,4 @@ namespace Ryujinx.Audio.Renderer.Utils return ref GetMemory(memory, id, count).Span[0]; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs b/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs index 2c48da6aa..b6bafbe0f 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/SpanMemoryManager.cs @@ -19,7 +19,7 @@ namespace Ryujinx.Audio.Renderer.Utils } } - public override Span GetSpan() => new Span(_pointer, _length); + public override Span GetSpan() => new(_pointer, _length); public override MemoryHandle Pin(int elementIndex = 0) { @@ -40,4 +40,4 @@ namespace Ryujinx.Audio.Renderer.Utils return new SpanMemoryManager(MemoryMarshal.Cast(memory.Span)).Memory; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs b/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs index 183960789..32d50e12f 100644 --- a/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs +++ b/src/Ryujinx.Audio/Renderer/Utils/SplitterHardwareDevice.cs @@ -5,8 +5,8 @@ namespace Ryujinx.Audio.Renderer.Utils { public class SplitterHardwareDevice : IHardwareDevice { - private IHardwareDevice _baseDevice; - private IHardwareDevice _secondaryDevice; + private readonly IHardwareDevice _baseDevice; + private readonly IHardwareDevice _secondaryDevice; public SplitterHardwareDevice(IHardwareDevice baseDevice, IHardwareDevice secondaryDevice) { @@ -43,6 +43,7 @@ namespace Ryujinx.Audio.Renderer.Utils public void Dispose() { + GC.SuppressFinalize(this); Dispose(true); } @@ -55,4 +56,4 @@ namespace Ryujinx.Audio.Renderer.Utils } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Audio/ResultCode.cs b/src/Ryujinx.Audio/ResultCode.cs index 1d05ac65e..eab27c16d 100644 --- a/src/Ryujinx.Audio/ResultCode.cs +++ b/src/Ryujinx.Audio/ResultCode.cs @@ -19,4 +19,4 @@ namespace Ryujinx.Audio UnsupportedOperation = (513 << ErrorCodeShift) | ModuleId, InvalidExecutionContextOperation = (514 << ErrorCodeShift) | ModuleId, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/App.axaml.cs b/src/Ryujinx.Ava/App.axaml.cs index e36cbfdd6..4ecc424a6 100644 --- a/src/Ryujinx.Ava/App.axaml.cs +++ b/src/Ryujinx.Ava/App.axaml.cs @@ -5,7 +5,6 @@ using Avalonia.Styling; using Avalonia.Threading; using FluentAvalonia.Styling; using Ryujinx.Ava.Common.Locale; -using Ryujinx.Ava.UI.Controls; using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.Windows; using Ryujinx.Common; @@ -67,7 +66,7 @@ namespace Ryujinx.Ava if (result == UserResult.Yes) { - var path = Process.GetCurrentProcess().MainModule.FileName; + var path = Environment.ProcessPath; var proc = Process.Start(path, CommandLineState.Arguments); desktop.Shutdown(); Environment.Exit(0); @@ -151,4 +150,4 @@ namespace Ryujinx.Ava } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/AppHost.cs b/src/Ryujinx.Ava/AppHost.cs index 2502fa41b..7c1ce542c 100644 --- a/src/Ryujinx.Ava/AppHost.cs +++ b/src/Ryujinx.Ava/AppHost.cs @@ -1,4 +1,5 @@ using ARMeilleure.Translation; +using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Input; @@ -26,12 +27,14 @@ using Ryujinx.Graphics.GAL.Multithreading; using Ryujinx.Graphics.Gpu; using Ryujinx.Graphics.OpenGL; using Ryujinx.Graphics.Vulkan; +using Ryujinx.HLE; using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Services.Account.Acc; using Ryujinx.HLE.HOS.SystemState; using Ryujinx.Input; using Ryujinx.Input.HLE; +using Ryujinx.Ui.App.Common; using Ryujinx.Ui.Common; using Ryujinx.Ui.Common.Configuration; using Ryujinx.Ui.Common.Helper; @@ -48,10 +51,12 @@ using System.IO; using System.Threading; using System.Threading.Tasks; using static Ryujinx.Ava.UI.Helpers.Win32NativeInterop; +using AntiAliasing = Ryujinx.Common.Configuration.AntiAliasing; using Image = SixLabors.ImageSharp.Image; using InputManager = Ryujinx.Input.HLE.InputManager; using Key = Ryujinx.Input.Key; using MouseButton = Ryujinx.Input.MouseButton; +using ScalingFilter = Ryujinx.Common.Configuration.ScalingFilter; using Size = Avalonia.Size; using Switch = Ryujinx.HLE.Switch; @@ -59,31 +64,31 @@ namespace Ryujinx.Ava { internal class AppHost { - private const int CursorHideIdleTime = 5; // Hide Cursor seconds. + private const int CursorHideIdleTime = 5; // Hide Cursor seconds. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping. - private const int TargetFps = 60; - private const float VolumeDelta = 0.05f; + private const int TargetFps = 60; + private const float VolumeDelta = 0.05f; - private static readonly Cursor InvisibleCursor = new(StandardCursorType.None); - private readonly IntPtr InvisibleCursorWin; - private readonly IntPtr DefaultCursorWin; + private static readonly Cursor _invisibleCursor = new(StandardCursorType.None); + private readonly IntPtr _invisibleCursorWin; + private readonly IntPtr _defaultCursorWin; - private readonly long _ticksPerFrame; + private readonly long _ticksPerFrame; private readonly Stopwatch _chrono; - private long _ticks; + private long _ticks; - private readonly AccountManager _accountManager; + private readonly AccountManager _accountManager; private readonly UserChannelPersistence _userChannelPersistence; - private readonly InputManager _inputManager; + private readonly InputManager _inputManager; private readonly MainWindowViewModel _viewModel; - private readonly IKeyboard _keyboardInterface; - private readonly TopLevel _topLevel; - public RendererHost _rendererHost; + private readonly IKeyboard _keyboardInterface; + private readonly TopLevel _topLevel; + public RendererHost RendererHost; private readonly GraphicsDebugLevel _glLogLevel; - private float _newVolume; - private KeyboardHotkeyState _prevHotkeyState; + private float _newVolume; + private KeyboardHotkeyState _prevHotkeyState; private long _lastCursorMoveTime; private bool _isCursorInRenderer = true; @@ -92,14 +97,14 @@ namespace Ryujinx.Ava private bool _isActive; private bool _renderingStarted; - private ManualResetEvent _gpuDoneEvent; + private readonly ManualResetEvent _gpuDoneEvent; - private IRenderer _renderer; - private readonly Thread _renderingThread; + private IRenderer _renderer; + private readonly Thread _renderingThread; private readonly CancellationTokenSource _gpuCancellationTokenSource; private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution; - private bool _dialogShown; + private bool _dialogShown; private readonly bool _isFirmwareTitle; private readonly object _lockObject = new(); @@ -107,55 +112,55 @@ namespace Ryujinx.Ava public event EventHandler AppExit; public event EventHandler StatusUpdatedEvent; - public VirtualFileSystem VirtualFileSystem { get; } - public ContentManager ContentManager { get; } - public NpadManager NpadManager { get; } + public VirtualFileSystem VirtualFileSystem { get; } + public ContentManager ContentManager { get; } + public NpadManager NpadManager { get; } public TouchScreenManager TouchScreenManager { get; } - public Switch Device { get; set; } + public Switch Device { get; set; } - public int Width { get; private set; } - public int Height { get; private set; } - public string ApplicationPath { get; private set; } - public bool ScreenshotRequested { get; set; } + public int Width { get; private set; } + public int Height { get; private set; } + public string ApplicationPath { get; private set; } + public bool ScreenshotRequested { get; set; } public AppHost( - RendererHost renderer, - InputManager inputManager, - string applicationPath, - VirtualFileSystem virtualFileSystem, - ContentManager contentManager, - AccountManager accountManager, + RendererHost renderer, + InputManager inputManager, + string applicationPath, + VirtualFileSystem virtualFileSystem, + ContentManager contentManager, + AccountManager accountManager, UserChannelPersistence userChannelPersistence, - MainWindowViewModel viewmodel, - TopLevel topLevel) + MainWindowViewModel viewmodel, + TopLevel topLevel) { - _viewModel = viewmodel; - _inputManager = inputManager; - _accountManager = accountManager; + _viewModel = viewmodel; + _inputManager = inputManager; + _accountManager = accountManager; _userChannelPersistence = userChannelPersistence; - _renderingThread = new Thread(RenderLoop, 1 * 1024 * 1024) { Name = "GUI.RenderThread" }; - _lastCursorMoveTime = Stopwatch.GetTimestamp(); - _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel; - _topLevel = topLevel; + _renderingThread = new Thread(RenderLoop) { Name = "GUI.RenderThread" }; + _lastCursorMoveTime = Stopwatch.GetTimestamp(); + _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel; + _topLevel = topLevel; _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_topLevel, renderer)); _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0"); - NpadManager = _inputManager.CreateNpadManager(); + NpadManager = _inputManager.CreateNpadManager(); TouchScreenManager = _inputManager.CreateTouchScreenManager(); - ApplicationPath = applicationPath; - VirtualFileSystem = virtualFileSystem; - ContentManager = contentManager; + ApplicationPath = applicationPath; + VirtualFileSystem = virtualFileSystem; + ContentManager = contentManager; - _rendererHost = renderer; + RendererHost = renderer; - _chrono = new Stopwatch(); + _chrono = new Stopwatch(); _ticksPerFrame = Stopwatch.Frequency / TargetFps; if (ApplicationPath.StartsWith("@SystemContent")) { - ApplicationPath = _viewModel.VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath); + ApplicationPath = VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath); _isFirmwareTitle = true; } @@ -168,21 +173,21 @@ namespace Ryujinx.Ava if (OperatingSystem.IsWindows()) { - InvisibleCursorWin = CreateEmptyCursor(); - DefaultCursorWin = CreateArrowCursor(); + _invisibleCursorWin = CreateEmptyCursor(); + _defaultCursorWin = CreateArrowCursor(); } ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState; - ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState; - ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState; - ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState; - ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState; - ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState; - ConfigurationState.Instance.Graphics.AntiAliasing.Event += UpdateAntiAliasing; - ConfigurationState.Instance.Graphics.ScalingFilter.Event += UpdateScalingFilter; - ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event += UpdateScalingFilterLevel; + ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState; + ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState; + ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState; + ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState; + ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState; + ConfigurationState.Instance.Graphics.AntiAliasing.Event += UpdateAntiAliasing; + ConfigurationState.Instance.Graphics.ScalingFilter.Event += UpdateScalingFilter; + ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event += UpdateScalingFilterLevel; - ConfigurationState.Instance.Multiplayer.LanInterfaceId.Event += UpdateLanInterfaceIdState; + ConfigurationState.Instance.Multiplayer.LanInterfaceId.Event += UpdateLanInterfaceIdState; _gpuCancellationTokenSource = new CancellationTokenSource(); _gpuDoneEvent = new ManualResetEvent(false); @@ -194,10 +199,10 @@ namespace Ryujinx.Ava { _lastCursorMoveTime = Stopwatch.GetTimestamp(); - if (_rendererHost.EmbeddedWindow.TransformedBounds != null) + if (RendererHost.EmbeddedWindow.TransformedBounds != null) { - var point = e.GetCurrentPoint(window).Position; - var bounds = _rendererHost.EmbeddedWindow.TransformedBounds.Value.Clip; + var point = e.GetCurrentPoint(window).Position; + var bounds = RendererHost.EmbeddedWindow.TransformedBounds.Value.Clip; _isCursorInRenderer = point.X >= bounds.X && point.X <= bounds.Width + bounds.X && @@ -218,7 +223,7 @@ namespace Ryujinx.Ava _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value); } - private void UpdateScalingFilter(object sender, ReactiveEventArgs e) + private void UpdateScalingFilter(object sender, ReactiveEventArgs e) { _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value); _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value); @@ -232,7 +237,7 @@ namespace Ryujinx.Ava if (OperatingSystem.IsWindows()) { - SetCursor(DefaultCursorWin); + SetCursor(_defaultCursorWin); } }); } @@ -241,11 +246,11 @@ namespace Ryujinx.Ava { Dispatcher.UIThread.Post(() => { - _viewModel.Cursor = InvisibleCursor; + _viewModel.Cursor = _invisibleCursor; if (OperatingSystem.IsWindows()) { - SetCursor(InvisibleCursorWin); + SetCursor(_invisibleCursorWin); } }); } @@ -269,12 +274,12 @@ namespace Ryujinx.Ava lock (_lockObject) { DateTime currentTime = DateTime.Now; - string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png"; + string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png"; string directory = AppDataManager.Mode switch { AppDataManager.LaunchMode.Portable or AppDataManager.LaunchMode.Custom => Path.Combine(AppDataManager.BaseDirPath, "screenshots"), - _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx") + _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx"), }; string path = Path.Combine(directory, filename); @@ -303,9 +308,9 @@ namespace Ryujinx.Ava image.Mutate(x => x.Flip(FlipMode.Vertical)); } - image.SaveAsPng(path, new PngEncoder() + image.SaveAsPng(path, new PngEncoder { - ColorType = PngColorType.Rgb + ColorType = PngColorType.Rgb, }); image.Dispose(); @@ -334,21 +339,21 @@ namespace Ryujinx.Ava _viewModel.IsGameRunning = true; - var activeProcess = Device.Processes.ActiveApplication; + var activeProcess = Device.Processes.ActiveApplication; - string titleNameSection = string.IsNullOrWhiteSpace(activeProcess.Name) ? string.Empty : $" {activeProcess.Name}"; + string titleNameSection = string.IsNullOrWhiteSpace(activeProcess.Name) ? string.Empty : $" {activeProcess.Name}"; string titleVersionSection = string.IsNullOrWhiteSpace(activeProcess.DisplayVersion) ? string.Empty : $" v{activeProcess.DisplayVersion}"; - string titleIdSection = $" ({activeProcess.ProgramIdText.ToUpper()})"; - string titleArchSection = activeProcess.Is64Bit ? " (64-bit)" : " (32-bit)"; + string titleIdSection = $" ({activeProcess.ProgramIdText.ToUpper()})"; + string titleArchSection = activeProcess.Is64Bit ? " (64-bit)" : " (32-bit)"; Dispatcher.UIThread.InvokeAsync(() => { _viewModel.Title = $"Ryujinx {Program.Version} -{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}"; }); - _viewModel.SetUIProgressHandlers(Device); + _viewModel.SetUiProgressHandlers(Device); - _rendererHost.SizeChanged += Window_SizeChanged; + RendererHost.SizeChanged += Window_SizeChanged; _isActive = true; @@ -377,7 +382,7 @@ namespace Ryujinx.Ava } } - private void UpdateAntiAliasing(object sender, ReactiveEventArgs e) + private void UpdateAntiAliasing(object sender, ReactiveEventArgs e) { _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)e.NewValue); } @@ -417,7 +422,7 @@ namespace Ryujinx.Ava } _isStopped = true; - _isActive = false; + _isActive = false; } public void DisposeContext() @@ -446,16 +451,16 @@ namespace Ryujinx.Ava { if (Device.Processes != null) { - _viewModel.UpdateGameMetadata(Device.Processes.ActiveApplication.ProgramIdText); + MainWindowViewModel.UpdateGameMetadata(Device.Processes.ActiveApplication.ProgramIdText); } ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState; - ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState; - ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState; - ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState; - ConfigurationState.Instance.Graphics.ScalingFilter.Event -= UpdateScalingFilter; - ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event -= UpdateScalingFilterLevel; - ConfigurationState.Instance.Graphics.AntiAliasing.Event -= UpdateAntiAliasing; + ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState; + ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState; + ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState; + ConfigurationState.Instance.Graphics.ScalingFilter.Event -= UpdateScalingFilter; + ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event -= UpdateScalingFilterLevel; + ConfigurationState.Instance.Graphics.AntiAliasing.Event -= UpdateAntiAliasing; _topLevel.PointerMoved -= TopLevel_PointerEnterOrMoved; _topLevel.PointerEnter -= TopLevel_PointerEnterOrMoved; @@ -475,11 +480,20 @@ namespace Ryujinx.Ava _windowsMultimediaTimerResolution = null; } - (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(); + if (RendererHost.EmbeddedWindow is EmbeddedWindowOpenGL openGlWindow) + { + // Try to bind the OpenGL context before calling the shutdown event. + openGlWindow.MakeCurrent(false, false); - Device.DisposeGpu(); + Device.DisposeGpu(); - (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(null); + // Unbind context and destroy everything. + openGlWindow.MakeCurrent(true, false); + } + else + { + Device.DisposeGpu(); + } } private void HideCursorState_Changed(object sender, ReactiveEventArgs state) @@ -497,7 +511,7 @@ namespace Ryujinx.Ava SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion(); - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError)) { @@ -515,7 +529,7 @@ namespace Ryujinx.Ava if (result != UserResult.Yes) { - await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow)); + await UserErrorDialog.ShowUserErrorDialog(userError); Device.Dispose(); return false; @@ -524,7 +538,7 @@ namespace Ryujinx.Ava if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _)) { - await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow)); + await UserErrorDialog.ShowUserErrorDialog(userError); Device.Dispose(); return false; @@ -547,7 +561,7 @@ namespace Ryujinx.Ava } else { - await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow)); + await UserErrorDialog.ShowUserErrorDialog(userError); Device.Dispose(); return false; @@ -682,7 +696,7 @@ namespace Ryujinx.Ava DiscordIntegrationModule.SwitchToPlayingState(Device.Processes.ActiveApplication.ProgramIdText, Device.Processes.ActiveApplication.Name); - _viewModel.ApplicationLibrary.LoadAndSaveMetaData(Device.Processes.ActiveApplication.ProgramIdText, appMetadata => + ApplicationLibrary.LoadAndSaveMetaData(Device.Processes.ActiveApplication.ProgramIdText, appMetadata => { appMetadata.LastPlayed = DateTime.UtcNow; }); @@ -716,7 +730,7 @@ namespace Ryujinx.Ava { renderer = new VulkanRenderer( Vk.GetApi(), - (_rendererHost.EmbeddedWindow as EmbeddedWindowVulkan).CreateSurface, + (RendererHost.EmbeddedWindow as EmbeddedWindowVulkan).CreateSurface, VulkanHelper.GetRequiredInstanceExtensions, ConfigurationState.Instance.Graphics.PreferredGpu.Value); } @@ -727,18 +741,18 @@ namespace Ryujinx.Ava BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading; - var isGALthreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); - if (isGALthreaded) + var isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading); + if (isGALThreaded) { renderer = new ThreadedRenderer(renderer); } - Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALthreaded}"); + Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALThreaded}"); // Initialize Configuration. - var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? HLE.MemoryConfiguration.MemoryConfiguration6GiB : HLE.MemoryConfiguration.MemoryConfiguration4GiB; + var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? MemoryConfiguration.MemoryConfiguration6GiB : MemoryConfiguration.MemoryConfiguration4GiB; - HLE.HLEConfiguration configuration = new(VirtualFileSystem, + HLEConfiguration configuration = new(VirtualFileSystem, _viewModel.LibHacHorizonManager, ContentManager, _accountManager, @@ -769,12 +783,12 @@ namespace Ryujinx.Ava private static IHardwareDeviceDriver InitializeAudio() { - var availableBackends = new List() + var availableBackends = new List { AudioBackend.SDL2, AudioBackend.SoundIo, AudioBackend.OpenAl, - AudioBackend.Dummy + AudioBackend.Dummy, }; AudioBackend preferredBackend = ConfigurationState.Instance.System.AudioBackend.Value; @@ -795,12 +809,10 @@ namespace Ryujinx.Ava { return new T(); } - else - { - Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}."); - return null; - } + Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}."); + + return null; } IHardwareDeviceDriver deviceDriver = null; @@ -808,14 +820,14 @@ namespace Ryujinx.Ava for (int i = 0; i < availableBackends.Count; i++) { AudioBackend currentBackend = availableBackends[i]; - AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy; + AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy; deviceDriver = currentBackend switch { - AudioBackend.SDL2 => InitializeAudioBackend(AudioBackend.SDL2, nextBackend), + AudioBackend.SDL2 => InitializeAudioBackend(AudioBackend.SDL2, nextBackend), AudioBackend.SoundIo => InitializeAudioBackend(AudioBackend.SoundIo, nextBackend), - AudioBackend.OpenAl => InitializeAudioBackend(AudioBackend.OpenAl, nextBackend), - _ => new DummyHardwareDeviceDriver() + AudioBackend.OpenAl => InitializeAudioBackend(AudioBackend.OpenAl, nextBackend), + _ => new DummyHardwareDeviceDriver(), }; if (deviceDriver != null) @@ -832,7 +844,7 @@ namespace Ryujinx.Ava private void Window_SizeChanged(object sender, Size e) { - Width = (int)e.Width; + Width = (int)e.Width; Height = (int)e.Height; SetRendererWindowSize(e); @@ -868,7 +880,7 @@ namespace Ryujinx.Ava _renderer.ScreenCaptured += Renderer_ScreenCaptured; - (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.InitializeBackgroundContext(_renderer); + (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.InitializeBackgroundContext(_renderer); Device.Gpu.Renderer.Initialize(_glLogLevel); @@ -876,8 +888,8 @@ namespace Ryujinx.Ava _renderer?.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value); _renderer?.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value); - Width = (int)_rendererHost.Bounds.Width; - Height = (int)_rendererHost.Bounds.Height; + Width = (int)RendererHost.Bounds.Width; + Height = (int)RendererHost.Bounds.Height; _renderer.Window.SetSize((int)(Width * _topLevel.PlatformImpl.RenderScaling), (int)(Height * _topLevel.PlatformImpl.RenderScaling)); @@ -912,7 +924,7 @@ namespace Ryujinx.Ava _viewModel.SwitchToRenderer(false); } - Device.PresentFrame(() => (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.SwapBuffers()); + Device.PresentFrame(() => (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.SwapBuffers()); } if (_ticks >= _ticksPerFrame) @@ -930,7 +942,7 @@ namespace Ryujinx.Ava _gpuDoneEvent.Set(); }); - (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(null); + (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(true); } public void UpdateStatus() @@ -1044,7 +1056,7 @@ namespace Ryujinx.Ava ScreenshotRequested = true; break; case KeyboardHotkeyState.ShowUi: - _viewModel.ShowMenuAndStatusBar = true; + _viewModel.ShowMenuAndStatusBar = !_viewModel.ShowMenuAndStatusBar; break; case KeyboardHotkeyState.Pause: if (_viewModel.IsPaused) @@ -1164,4 +1176,4 @@ namespace Ryujinx.Ava return state; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Assets/Locales/en_US.json b/src/Ryujinx.Ava/Assets/Locales/en_US.json index 79765db16..4065a1dfb 100644 --- a/src/Ryujinx.Ava/Assets/Locales/en_US.json +++ b/src/Ryujinx.Ava/Assets/Locales/en_US.json @@ -545,7 +545,7 @@ "SwkbdMinRangeCharacters": "Must be {0}-{1} characters long", "SoftwareKeyboard": "Software Keyboard", "SoftwareKeyboardModeNumbersOnly": "Must be numbers only", - "SoftwareKeyboardModeAlphabet": "Must be alphabets only", + "SoftwareKeyboardModeAlphabet": "Must be non CJK-characters only", "SoftwareKeyboardModeASCII": "Must be ASCII text only", "DialogControllerAppletMessagePlayerRange": "Application requests {0} player(s) with:\n\nTYPES: {1}\n\nPLAYERS: {2}\n\n{3}Please open Settings and reconfigure Input now or press Close.", "DialogControllerAppletMessage": "Application requests exactly {0} player(s) with:\n\nTYPES: {1}\n\nPLAYERS: {2}\n\n{3}Please open Settings and reconfigure Input now or press Close.", diff --git a/src/Ryujinx.Ava/Common/ApplicationHelper.cs b/src/Ryujinx.Ava/Common/ApplicationHelper.cs index 882c06949..d28d5aac1 100644 --- a/src/Ryujinx.Ava/Common/ApplicationHelper.cs +++ b/src/Ryujinx.Ava/Common/ApplicationHelper.cs @@ -18,7 +18,6 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.Windows; using Ryujinx.Common.Logging; using Ryujinx.HLE.FileSystem; -using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Services.Account.Acc; using Ryujinx.Ui.App.Common; using Ryujinx.Ui.Common.Helper; @@ -27,6 +26,7 @@ using System.Buffers; using System.IO; using System.Threading; using System.Threading.Tasks; +using ApplicationId = LibHac.Ncm.ApplicationId; using Path = System.IO.Path; namespace Ryujinx.Ava.Common @@ -57,7 +57,7 @@ namespace Ryujinx.Ava.Common Logger.Info?.Print(LogClass.Application, $"Creating save directory for Title: {titleName} [{titleId:x16}]"); - if (Utilities.IsZeros(controlHolder.ByteSpan)) + if (controlHolder.ByteSpan.IsZeros()) { // If the current application doesn't have a loaded control property, create a dummy one // and set the savedata sizes so a user savedata will be created. @@ -72,7 +72,7 @@ namespace Ryujinx.Ava.Common Uid user = new((ulong)_accountManager.LastOpenedUser.UserId.High, (ulong)_accountManager.LastOpenedUser.UserId.Low); - result = _horizonClient.Fs.EnsureApplicationSaveData(out _, new LibHac.Ncm.ApplicationId(titleId), in control, in user); + result = _horizonClient.Fs.EnsureApplicationSaveData(out _, new ApplicationId(titleId), in control, in user); if (result.IsFailure()) { Dispatcher.UIThread.InvokeAsync(async () => @@ -114,7 +114,7 @@ namespace Ryujinx.Ava.Common public static void OpenSaveDir(ulong saveDataId) { - string saveRootPath = Path.Combine(_virtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}"); + string saveRootPath = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}"); if (!Directory.Exists(saveRootPath)) { @@ -147,11 +147,11 @@ namespace Ryujinx.Ava.Common { OpenFolderDialog folderDialog = new() { - Title = LocaleManager.Instance[LocaleKeys.FolderDialogExtractTitle] + Title = LocaleManager.Instance[LocaleKeys.FolderDialogExtractTitle], }; - string destination = await folderDialog.ShowAsync(_owner); - var cancellationToken = new CancellationTokenSource(); + string destination = await folderDialog.ShowAsync(_owner); + var cancellationToken = new CancellationTokenSource(); UpdateWaitWindow waitingDialog = new( LocaleManager.Instance[LocaleKeys.DialogNcaExtractionTitle], @@ -166,7 +166,7 @@ namespace Ryujinx.Ava.Common using FileStream file = new(titleFilePath, FileMode.Open, FileAccess.Read); - Nca mainNca = null; + Nca mainNca = null; Nca patchNca = null; string extension = Path.GetExtension(titleFilePath).ToLower(); @@ -293,10 +293,11 @@ namespace Ryujinx.Ava.Common await ContentDialogHelper.CreateErrorDialog(ex.Message); }); } - }); - - extractorThread.Name = "GUI.NcaSectionExtractorThread"; - extractorThread.IsBackground = true; + }) + { + Name = "GUI.NcaSectionExtractorThread", + IsBackground = true, + }; extractorThread.Start(); } } @@ -413,4 +414,4 @@ namespace Ryujinx.Ava.Common return Result.Success; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Common/ApplicationSort.cs b/src/Ryujinx.Ava/Common/ApplicationSort.cs index 6ff06a1e2..4b80e3d29 100644 --- a/src/Ryujinx.Ava/Common/ApplicationSort.cs +++ b/src/Ryujinx.Ava/Common/ApplicationSort.cs @@ -10,6 +10,6 @@ namespace Ryujinx.Ava.Common FileType, FileSize, Path, - Favorite + Favorite, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Common/KeyboardHotkeyState.cs b/src/Ryujinx.Ava/Common/KeyboardHotkeyState.cs index e85bdf341..1d7f0b9ce 100644 --- a/src/Ryujinx.Ava/Common/KeyboardHotkeyState.cs +++ b/src/Ryujinx.Ava/Common/KeyboardHotkeyState.cs @@ -11,6 +11,6 @@ ResScaleUp, ResScaleDown, VolumeUp, - VolumeDown + VolumeDown, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Common/Locale/LocaleExtension.cs b/src/Ryujinx.Ava/Common/Locale/LocaleExtension.cs index b82c405de..cd1c1510d 100644 --- a/src/Ryujinx.Ava/Common/Locale/LocaleExtension.cs +++ b/src/Ryujinx.Ava/Common/Locale/LocaleExtension.cs @@ -20,11 +20,11 @@ namespace Ryujinx.Ava.Common.Locale ReflectionBindingExtension binding = new($"[{keyToUse}]") { - Mode = BindingMode.OneWay, - Source = LocaleManager.Instance + Mode = BindingMode.OneWay, + Source = LocaleManager.Instance, }; return binding.ProvideValue(serviceProvider); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Common/Locale/LocaleManager.cs b/src/Ryujinx.Ava/Common/Locale/LocaleManager.cs index 464ab780d..583619fe5 100644 --- a/src/Ryujinx.Ava/Common/Locale/LocaleManager.cs +++ b/src/Ryujinx.Ava/Common/Locale/LocaleManager.cs @@ -13,17 +13,17 @@ namespace Ryujinx.Ava.Common.Locale { private const string DefaultLanguageCode = "en_US"; - private Dictionary _localeStrings; - private Dictionary _localeDefaultStrings; + private readonly Dictionary _localeStrings; + private Dictionary _localeDefaultStrings; private readonly ConcurrentDictionary _dynamicValues; - public static LocaleManager Instance { get; } = new LocaleManager(); + public static LocaleManager Instance { get; } = new(); public LocaleManager() { - _localeStrings = new Dictionary(); + _localeStrings = new Dictionary(); _localeDefaultStrings = new Dictionary(); - _dynamicValues = new ConcurrentDictionary(); + _dynamicValues = new ConcurrentDictionary(); Load(); } @@ -126,11 +126,11 @@ namespace Ryujinx.Ava.Common.Locale } } - private Dictionary LoadJsonLanguage(string languageCode = DefaultLanguageCode) + private static Dictionary LoadJsonLanguage(string languageCode = DefaultLanguageCode) { - var localeStrings = new Dictionary(); - string languageJson = EmbeddedResources.ReadAllText($"Ryujinx.Ava/Assets/Locales/{languageCode}.json"); - var strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); + var localeStrings = new Dictionary(); + string languageJson = EmbeddedResources.ReadAllText($"Ryujinx.Ava/Assets/Locales/{languageCode}.json"); + var strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); foreach (var item in strings) { @@ -143,4 +143,4 @@ namespace Ryujinx.Ava.Common.Locale return localeStrings; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Input/AvaloniaKeyboard.cs b/src/Ryujinx.Ava/Input/AvaloniaKeyboard.cs index d40ebbd2b..d07c81340 100644 --- a/src/Ryujinx.Ava/Input/AvaloniaKeyboard.cs +++ b/src/Ryujinx.Ava/Input/AvaloniaKeyboard.cs @@ -12,25 +12,25 @@ namespace Ryujinx.Ava.Input internal class AvaloniaKeyboard : IKeyboard { private readonly List _buttonsUserMapping; - private readonly AvaloniaKeyboardDriver _driver; - private StandardKeyboardInputConfig _configuration; + private readonly AvaloniaKeyboardDriver _driver; + private StandardKeyboardInputConfig _configuration; private readonly object _userMappingLock = new(); - public string Id { get; } + public string Id { get; } public string Name { get; } - public bool IsConnected => true; - public GamepadFeaturesFlag Features => GamepadFeaturesFlag.None; + public bool IsConnected => true; + public GamepadFeaturesFlag Features => GamepadFeaturesFlag.None; private class ButtonMappingEntry { - public readonly Key From; + public readonly Key From; public readonly GamepadButtonInputId To; public ButtonMappingEntry(GamepadButtonInputId to, Key from) { - To = to; + To = to; From = from; } } @@ -40,8 +40,8 @@ namespace Ryujinx.Ava.Input _buttonsUserMapping = new List(); _driver = driver; - Id = id; - Name = name; + Id = id; + Name = name; } public KeyboardStateSnapshot GetKeyboardStateSnapshot() @@ -52,7 +52,7 @@ namespace Ryujinx.Ava.Input public GamepadStateSnapshot GetMappedStateSnapshot() { KeyboardStateSnapshot rawState = GetKeyboardStateSnapshot(); - GamepadStateSnapshot result = default; + GamepadStateSnapshot result = default; lock (_userMappingLock) { @@ -75,10 +75,10 @@ namespace Ryujinx.Ava.Input } } - (short leftStickX, short leftStickY) = GetStickValues(ref rawState, _configuration.LeftJoyconStick); + (short leftStickX, short leftStickY) = GetStickValues(ref rawState, _configuration.LeftJoyconStick); (short rightStickX, short rightStickY) = GetStickValues(ref rawState, _configuration.RightJoyconStick); - result.SetStick(StickInputId.Left, ConvertRawStickValue(leftStickX), ConvertRawStickValue(leftStickY)); + result.SetStick(StickInputId.Left, ConvertRawStickValue(leftStickX), ConvertRawStickValue(leftStickY)); result.SetStick(StickInputId.Right, ConvertRawStickValue(rightStickX), ConvertRawStickValue(rightStickY)); } @@ -120,6 +120,7 @@ namespace Ryujinx.Ava.Input _buttonsUserMapping.Clear(); +#pragma warning disable IDE0055 // Disable formatting // Left JoyCon _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.LeftStick, (Key)_configuration.LeftJoyconStick.StickButton)); _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.DpadUp, (Key)_configuration.LeftJoycon.DpadUp)); @@ -143,6 +144,7 @@ namespace Ryujinx.Ava.Input _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.RightTrigger, (Key)_configuration.RightJoycon.ButtonZr)); _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleRightTrigger1, (Key)_configuration.RightJoycon.ButtonSr)); _buttonsUserMapping.Add(new ButtonMappingEntry(GamepadButtonInputId.SingleLeftTrigger1, (Key)_configuration.RightJoycon.ButtonSl)); +#pragma warning restore IDE0055 } } @@ -198,4 +200,4 @@ namespace Ryujinx.Ava.Input public void Dispose() { } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Input/AvaloniaKeyboardDriver.cs b/src/Ryujinx.Ava/Input/AvaloniaKeyboardDriver.cs index edcdb52fd..f12d0214b 100644 --- a/src/Ryujinx.Ava/Input/AvaloniaKeyboardDriver.cs +++ b/src/Ryujinx.Ava/Input/AvaloniaKeyboardDriver.cs @@ -13,23 +13,23 @@ namespace Ryujinx.Ava.Input internal class AvaloniaKeyboardDriver : IGamepadDriver { private static readonly string[] _keyboardIdentifers = new string[1] { "0" }; - private readonly Control _control; + private readonly Control _control; private readonly HashSet _pressedKeys; public event EventHandler KeyPressed; public event EventHandler KeyRelease; - public event EventHandler TextInput; + public event EventHandler TextInput; - public string DriverName => "AvaloniaKeyboardDriver"; + public string DriverName => "AvaloniaKeyboardDriver"; public ReadOnlySpan GamepadsIds => _keyboardIdentifers; public AvaloniaKeyboardDriver(Control control) { - _control = control; + _control = control; _pressedKeys = new HashSet(); - _control.KeyDown += OnKeyPress; - _control.KeyUp += OnKeyRelease; + _control.KeyDown += OnKeyPress; + _control.KeyUp += OnKeyRelease; _control.TextInput += Control_TextInput; _control.AddHandler(InputElement.TextInputEvent, Control_LastChanceTextInput, RoutingStrategies.Bubble); } @@ -47,13 +47,13 @@ namespace Ryujinx.Ava.Input public event Action OnGamepadConnected { - add { } + add { } remove { } } public event Action OnGamepadDisconnected { - add { } + add { } remove { } } @@ -71,7 +71,7 @@ namespace Ryujinx.Ava.Input { if (disposing) { - _control.KeyUp -= OnKeyPress; + _control.KeyUp -= OnKeyPress; _control.KeyDown -= OnKeyRelease; } } @@ -112,4 +112,4 @@ namespace Ryujinx.Ava.Input Dispose(true); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Input/AvaloniaKeyboardMappingHelper.cs b/src/Ryujinx.Ava/Input/AvaloniaKeyboardMappingHelper.cs index 0cc04d0a9..d30a7566a 100644 --- a/src/Ryujinx.Ava/Input/AvaloniaKeyboardMappingHelper.cs +++ b/src/Ryujinx.Ava/Input/AvaloniaKeyboardMappingHelper.cs @@ -143,7 +143,7 @@ namespace Ryujinx.Ava.Input AvaKey.OemBackslash, // NOTE: invalid - AvaKey.None + AvaKey.None, }; private static readonly Dictionary _avaKeyMapping; @@ -182,4 +182,4 @@ namespace Ryujinx.Ava.Input return _avaKeyMapping.GetValueOrDefault(key, Key.Unknown); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Input/AvaloniaMouse.cs b/src/Ryujinx.Ava/Input/AvaloniaMouse.cs index 3a9c91c0d..1aa2d586a 100644 --- a/src/Ryujinx.Ava/Input/AvaloniaMouse.cs +++ b/src/Ryujinx.Ava/Input/AvaloniaMouse.cs @@ -10,12 +10,12 @@ namespace Ryujinx.Ava.Input { private AvaloniaMouseDriver _driver; - public string Id => "0"; + public string Id => "0"; public string Name => "AvaloniaMouse"; - public bool IsConnected => true; - public GamepadFeaturesFlag Features => throw new NotImplementedException(); - public bool[] Buttons => _driver.PressedButtons; + public bool IsConnected => true; + public GamepadFeaturesFlag Features => throw new NotImplementedException(); + public bool[] Buttons => _driver.PressedButtons; public AvaloniaMouse(AvaloniaMouseDriver driver) { @@ -84,4 +84,4 @@ namespace Ryujinx.Ava.Input _driver = null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Input/AvaloniaMouseDriver.cs b/src/Ryujinx.Ava/Input/AvaloniaMouseDriver.cs index b7e5a4d95..e71bbf64a 100644 --- a/src/Ryujinx.Ava/Input/AvaloniaMouseDriver.cs +++ b/src/Ryujinx.Ava/Input/AvaloniaMouseDriver.cs @@ -11,16 +11,16 @@ namespace Ryujinx.Ava.Input { internal class AvaloniaMouseDriver : IGamepadDriver { - private Control _widget; - private bool _isDisposed; - private Size _size; + private Control _widget; + private bool _isDisposed; + private Size _size; private readonly TopLevel _window; - public bool[] PressedButtons { get; } + public bool[] PressedButtons { get; } public Vector2 CurrentPosition { get; private set; } - public Vector2 Scroll { get; private set; } + public Vector2 Scroll { get; private set; } - public string DriverName => "AvaloniaMouseDriver"; + public string DriverName => "AvaloniaMouseDriver"; public ReadOnlySpan GamepadsIds => new[] { "0" }; public AvaloniaMouseDriver(TopLevel window, Control parent) @@ -28,14 +28,14 @@ namespace Ryujinx.Ava.Input _widget = parent; _window = window; - _widget.PointerMoved += Parent_PointerMovedEvent; - _widget.PointerPressed += Parent_PointerPressedEvent; - _widget.PointerReleased += Parent_PointerReleasedEvent; + _widget.PointerMoved += Parent_PointerMovedEvent; + _widget.PointerPressed += Parent_PointerPressedEvent; + _widget.PointerReleased += Parent_PointerReleasedEvent; _widget.PointerWheelChanged += Parent_PointerWheelChanged; - - _window.PointerMoved += Parent_PointerMovedEvent; - _window.PointerPressed += Parent_PointerPressedEvent; - _window.PointerReleased += Parent_PointerReleasedEvent; + + _window.PointerMoved += Parent_PointerMovedEvent; + _window.PointerPressed += Parent_PointerPressedEvent; + _window.PointerReleased += Parent_PointerReleasedEvent; _window.PointerWheelChanged += Parent_PointerWheelChanged; PressedButtons = new bool[(int)MouseButton.Count]; @@ -47,13 +47,13 @@ namespace Ryujinx.Ava.Input public event Action OnGamepadConnected { - add { } + add { } remove { } } public event Action OnGamepadDisconnected { - add { } + add { } remove { } } @@ -143,17 +143,17 @@ namespace Ryujinx.Ava.Input _isDisposed = true; - _widget.PointerMoved -= Parent_PointerMovedEvent; - _widget.PointerPressed -= Parent_PointerPressedEvent; - _widget.PointerReleased -= Parent_PointerReleasedEvent; + _widget.PointerMoved -= Parent_PointerMovedEvent; + _widget.PointerPressed -= Parent_PointerPressedEvent; + _widget.PointerReleased -= Parent_PointerReleasedEvent; _widget.PointerWheelChanged -= Parent_PointerWheelChanged; - _window.PointerMoved -= Parent_PointerMovedEvent; - _window.PointerPressed -= Parent_PointerPressedEvent; - _window.PointerReleased -= Parent_PointerReleasedEvent; + _window.PointerMoved -= Parent_PointerMovedEvent; + _window.PointerPressed -= Parent_PointerPressedEvent; + _window.PointerReleased -= Parent_PointerReleasedEvent; _window.PointerWheelChanged -= Parent_PointerWheelChanged; _widget = null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Modules/Updater/Updater.cs b/src/Ryujinx.Ava/Modules/Updater/Updater.cs index 839526c4e..8216333a7 100644 --- a/src/Ryujinx.Ava/Modules/Updater/Updater.cs +++ b/src/Ryujinx.Ava/Modules/Updater/Updater.cs @@ -31,22 +31,22 @@ namespace Ryujinx.Modules { internal static class Updater { - private const string GitHubApiURL = "https://api.github.com"; - private static readonly GithubReleasesJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private const string GitHubApiUrl = "https://api.github.com"; + private static readonly GithubReleasesJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); - private static readonly string HomeDir = AppDomain.CurrentDomain.BaseDirectory; - private static readonly string UpdateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update"); - private static readonly string UpdatePublishDir = Path.Combine(UpdateDir, "publish"); - private static readonly int ConnectionCount = 4; + private static readonly string _homeDir = AppDomain.CurrentDomain.BaseDirectory; + private static readonly string _updateDir = Path.Combine(Path.GetTempPath(), "Ryujinx", "update"); + private static readonly string _updatePublishDir = Path.Combine(_updateDir, "publish"); + private static readonly int _connectionCount = 4; private static string _buildVer; private static string _platformExt; private static string _buildUrl; - private static long _buildSize; - private static bool _updateSuccessful; - private static bool _running; + private static long _buildSize; + private static bool _updateSuccessful; + private static bool _running; - private static readonly string[] WindowsDependencyDirs = Array.Empty(); + private static readonly string[] _windowsDependencyDirs = Array.Empty(); public static async Task BeginParse(Window mainWindow, bool showVersionUpToDate) { @@ -99,9 +99,9 @@ namespace Ryujinx.Modules { using HttpClient jsonClient = ConstructHttpClient(); - string buildInfoURL = $"{GitHubApiURL}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest"; - string fetchedJson = await jsonClient.GetStringAsync(buildInfoURL); - var fetched = JsonHelper.Deserialize(fetchedJson, SerializerContext.GithubReleasesJsonResponse); + string buildInfoUrl = $"{GitHubApiUrl}/repos/{ReleaseInformation.ReleaseChannelOwner}/{ReleaseInformation.ReleaseChannelRepo}/releases/latest"; + string fetchedJson = await jsonClient.GetStringAsync(buildInfoUrl); + var fetched = JsonHelper.Deserialize(fetchedJson, _serializerContext.GithubReleasesJsonResponse); _buildVer = fetched.Name; foreach (var asset in fetched.Assets) @@ -195,23 +195,21 @@ namespace Ryujinx.Modules } // Fetch build size information to learn chunk sizes. - using (HttpClient buildSizeClient = ConstructHttpClient()) + using HttpClient buildSizeClient = ConstructHttpClient(); + try { - try - { - buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0"); + buildSizeClient.DefaultRequestHeaders.Add("Range", "bytes=0-0"); - HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead); + HttpResponseMessage message = await buildSizeClient.GetAsync(new Uri(_buildUrl), HttpCompletionOption.ResponseHeadersRead); - _buildSize = message.Content.Headers.ContentRange.Length.Value; - } - catch (Exception ex) - { - Logger.Warning?.Print(LogClass.Application, ex.Message); - Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater"); + _buildSize = message.Content.Headers.ContentRange.Length.Value; + } + catch (Exception ex) + { + Logger.Warning?.Print(LogClass.Application, ex.Message); + Logger.Warning?.Print(LogClass.Application, "Couldn't determine build size for update, using single-threaded updater"); - _buildSize = -1; - } + _buildSize = -1; } Dispatcher.UIThread.Post(async () => @@ -248,23 +246,22 @@ namespace Ryujinx.Modules _updateSuccessful = false; // Empty update dir, although it shouldn't ever have anything inside it - if (Directory.Exists(UpdateDir)) + if (Directory.Exists(_updateDir)) { - Directory.Delete(UpdateDir, true); + Directory.Delete(_updateDir, true); } - Directory.CreateDirectory(UpdateDir); + Directory.CreateDirectory(_updateDir); - string updateFile = Path.Combine(UpdateDir, "update.bin"); + string updateFile = Path.Combine(_updateDir, "update.bin"); TaskDialog taskDialog = new() { - Header = LocaleManager.Instance[LocaleKeys.RyujinxUpdater], - SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterDownloading], - IconSource = new SymbolIconSource { Symbol = Symbol.Download }, - Buttons = { }, + Header = LocaleManager.Instance[LocaleKeys.RyujinxUpdater], + SubHeader = LocaleManager.Instance[LocaleKeys.UpdaterDownloading], + IconSource = new SymbolIconSource { Symbol = Symbol.Download }, ShowProgressBar = true, - XamlRoot = parent + XamlRoot = parent, }; taskDialog.Opened += (s, e) => @@ -301,7 +298,7 @@ namespace Ryujinx.Modules if (OperatingSystem.IsMacOS()) { string baseBundlePath = Path.GetFullPath(Path.Combine(executableDirectory, "..", "..")); - string newBundlePath = Path.Combine(UpdateDir, "Ryujinx.app"); + string newBundlePath = Path.Combine(_updateDir, "Ryujinx.app"); string updaterScriptPath = Path.Combine(newBundlePath, "Contents", "Resources", "updater.sh"); string currentPid = Environment.ProcessId.ToString(); @@ -328,7 +325,7 @@ namespace Ryujinx.Modules ProcessStartInfo processStart = new(ryuName) { UseShellExecute = true, - WorkingDirectory = executableDirectory + WorkingDirectory = executableDirectory, }; foreach (string argument in CommandLineState.Arguments) @@ -347,22 +344,22 @@ namespace Ryujinx.Modules private static void DoUpdateWithMultipleThreads(TaskDialog taskDialog, string downloadUrl, string updateFile) { // Multi-Threaded Updater - long chunkSize = _buildSize / ConnectionCount; - long remainderChunk = _buildSize % ConnectionCount; + long chunkSize = _buildSize / _connectionCount; + long remainderChunk = _buildSize % _connectionCount; - int completedRequests = 0; - int totalProgressPercentage = 0; - int[] progressPercentage = new int[ConnectionCount]; + int completedRequests = 0; + int totalProgressPercentage = 0; + int[] progressPercentage = new int[_connectionCount]; - List list = new(ConnectionCount); - List webClients = new(ConnectionCount); + List list = new(_connectionCount); + List webClients = new(_connectionCount); - for (int i = 0; i < ConnectionCount; i++) + for (int i = 0; i < _connectionCount; i++) { list.Add(Array.Empty()); } - for (int i = 0; i < ConnectionCount; i++) + for (int i = 0; i < _connectionCount; i++) { #pragma warning disable SYSLIB0014 // TODO: WebClient is obsolete and need to be replaced with a more complex logic using HttpClient. @@ -371,7 +368,7 @@ namespace Ryujinx.Modules webClients.Add(client); - if (i == ConnectionCount - 1) + if (i == _connectionCount - 1) { client.Headers.Add("Range", $"bytes={chunkSize * i}-{(chunkSize * (i + 1) - 1) + remainderChunk}"); } @@ -388,7 +385,7 @@ namespace Ryujinx.Modules Interlocked.Exchange(ref progressPercentage[index], args.ProgressPercentage); Interlocked.Add(ref totalProgressPercentage, args.ProgressPercentage); - taskDialog.SetProgressBarState(totalProgressPercentage / ConnectionCount, TaskDialogProgressState.Normal); + taskDialog.SetProgressBarState(totalProgressPercentage / _connectionCount, TaskDialogProgressState.Normal); }; client.DownloadDataCompleted += (_, args) => @@ -407,10 +404,10 @@ namespace Ryujinx.Modules list[index] = args.Result; Interlocked.Increment(ref completedRequests); - if (Equals(completedRequests, ConnectionCount)) + if (Equals(completedRequests, _connectionCount)) { byte[] mergedFileBytes = new byte[_buildSize]; - for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < ConnectionCount; connectionIndex++) + for (int connectionIndex = 0, destinationOffset = 0; connectionIndex < _connectionCount; connectionIndex++) { Array.Copy(list[connectionIndex], 0, mergedFileBytes, destinationOffset, list[connectionIndex].Length); destinationOffset += list[connectionIndex].Length; @@ -421,10 +418,9 @@ namespace Ryujinx.Modules // On macOS, ensure that we remove the quarantine bit to prevent Gatekeeper from blocking execution. if (OperatingSystem.IsMacOS()) { - using (Process xattrProcess = Process.Start("xattr", new List { "-d", "com.apple.quarantine", updateFile })) - { - xattrProcess.WaitForExit(); - } + using Process xattrProcess = Process.Start("xattr", new List { "-d", "com.apple.quarantine", updateFile }); + + xattrProcess.WaitForExit(); } try @@ -437,8 +433,6 @@ namespace Ryujinx.Modules Logger.Warning?.Print(LogClass.Application, "Multi-Threaded update failed, falling back to single-threaded updater."); DoUpdateWithSingleThread(taskDialog, downloadUrl, updateFile); - - return; } } }; @@ -470,31 +464,29 @@ namespace Ryujinx.Modules // We do not want to timeout while downloading client.Timeout = TimeSpan.FromDays(1); - using (HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result) - using (Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result) + using HttpResponseMessage response = client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead).Result; + using Stream remoteFileStream = response.Content.ReadAsStreamAsync().Result; + using Stream updateFileStream = File.Open(updateFile, FileMode.Create); + + long totalBytes = response.Content.Headers.ContentLength.Value; + long byteWritten = 0; + + byte[] buffer = new byte[32 * 1024]; + + while (true) { - using Stream updateFileStream = File.Open(updateFile, FileMode.Create); + int readSize = remoteFileStream.Read(buffer); - long totalBytes = response.Content.Headers.ContentLength.Value; - long byteWritten = 0; - - byte[] buffer = new byte[32 * 1024]; - - while (true) + if (readSize == 0) { - int readSize = remoteFileStream.Read(buffer); - - if (readSize == 0) - { - break; - } - - byteWritten += readSize; - - taskDialog.SetProgressBarState(GetPercentage(byteWritten, totalBytes), TaskDialogProgressState.Normal); - - updateFileStream.Write(buffer, 0, readSize); + break; } + + byteWritten += readSize; + + taskDialog.SetProgressBarState(GetPercentage(byteWritten, totalBytes), TaskDialogProgressState.Normal); + + updateFileStream.Write(buffer, 0, readSize); } InstallUpdate(taskDialog, updateFile); @@ -510,7 +502,7 @@ namespace Ryujinx.Modules { Thread worker = new(() => DoUpdateWithSingleThreadWorker(taskDialog, downloadUrl, updateFile)) { - Name = "Updater.SingleThreadWorker" + Name = "Updater.SingleThreadWorker", }; worker.Start(); @@ -520,9 +512,9 @@ namespace Ryujinx.Modules [SupportedOSPlatform("macos")] private static void ExtractTarGzipFile(TaskDialog taskDialog, string archivePath, string outputDirectoryPath) { - using Stream inStream = File.OpenRead(archivePath); + using Stream inStream = File.OpenRead(archivePath); using GZipInputStream gzipStream = new(inStream); - using TarInputStream tarStream = new(gzipStream, Encoding.ASCII); + using TarInputStream tarStream = new(gzipStream, Encoding.ASCII); TarEntry tarEntry; @@ -537,10 +529,8 @@ namespace Ryujinx.Modules Directory.CreateDirectory(Path.GetDirectoryName(outPath)); - using (FileStream outStream = File.OpenWrite(outPath)) - { - tarStream.CopyEntryContents(outStream); - } + using FileStream outStream = File.OpenWrite(outPath); + tarStream.CopyEntryContents(outStream); File.SetUnixFileMode(outPath, (UnixFileMode)tarEntry.TarHeader.Mode); File.SetLastWriteTime(outPath, DateTime.SpecifyKind(tarEntry.ModTime, DateTimeKind.Utc)); @@ -559,24 +549,26 @@ namespace Ryujinx.Modules private static void ExtractZipFile(TaskDialog taskDialog, string archivePath, string outputDirectoryPath) { - using Stream inStream = File.OpenRead(archivePath); - using ZipFile zipFile = new(inStream); + using Stream inStream = File.OpenRead(archivePath); + using ZipFile zipFile = new(inStream); double count = 0; foreach (ZipEntry zipEntry in zipFile) { count++; - if (zipEntry.IsDirectory) continue; + if (zipEntry.IsDirectory) + { + continue; + } string outPath = Path.Combine(outputDirectoryPath, zipEntry.Name); Directory.CreateDirectory(Path.GetDirectoryName(outPath)); - using (Stream zipStream = zipFile.GetInputStream(zipEntry)) - using (FileStream outStream = File.OpenWrite(outPath)) - { - zipStream.CopyTo(outStream); - } + using Stream zipStream = zipFile.GetInputStream(zipEntry); + using FileStream outStream = File.OpenWrite(outPath); + + zipStream.CopyTo(outStream); File.SetLastWriteTime(outPath, DateTime.SpecifyKind(zipEntry.DateTime, DateTimeKind.Utc)); @@ -597,11 +589,11 @@ namespace Ryujinx.Modules { if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()) { - ExtractTarGzipFile(taskDialog, updateFile, UpdateDir); + ExtractTarGzipFile(taskDialog, updateFile, _updateDir); } else if (OperatingSystem.IsWindows()) { - ExtractZipFile(taskDialog, updateFile, UpdateDir); + ExtractZipFile(taskDialog, updateFile, _updateDir); } else { @@ -648,10 +640,10 @@ namespace Ryujinx.Modules taskDialog.SetProgressBarState(0, TaskDialogProgressState.Normal); }); - MoveAllFilesOver(UpdatePublishDir, HomeDir, taskDialog); + MoveAllFilesOver(_updatePublishDir, _homeDir, taskDialog); }); - Directory.Delete(UpdateDir, true); + Directory.Delete(_updateDir, true); } _updateSuccessful = true; @@ -738,15 +730,15 @@ namespace Ryujinx.Modules // NOTE: This method should always reflect the latest build layout. private static IEnumerable EnumerateFilesToDelete() { - var files = Directory.EnumerateFiles(HomeDir); // All files directly in base dir. + var files = Directory.EnumerateFiles(_homeDir); // All files directly in base dir. // Determine and exclude user files only when the updater is running, not when cleaning old files - if (_running) + if (_running && !OperatingSystem.IsMacOS()) { // Compare the loose files in base directory against the loose files from the incoming update, and store foreign ones in a user list. - var oldFiles = Directory.EnumerateFiles(HomeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); - var newFiles = Directory.EnumerateFiles(UpdatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); - var userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(HomeDir, filename)); + var oldFiles = Directory.EnumerateFiles(_homeDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + var newFiles = Directory.EnumerateFiles(_updatePublishDir, "*", SearchOption.TopDirectoryOnly).Select(Path.GetFileName); + var userFiles = oldFiles.Except(newFiles).Select(filename => Path.Combine(_homeDir, filename)); // Remove user files from the paths in files. files = files.Except(userFiles); @@ -754,9 +746,9 @@ namespace Ryujinx.Modules if (OperatingSystem.IsWindows()) { - foreach (string dir in WindowsDependencyDirs) + foreach (string dir in _windowsDependencyDirs) { - string dirPath = Path.Combine(HomeDir, dir); + string dirPath = Path.Combine(_homeDir, dir); if (Directory.Exists(dirPath)) { files = files.Concat(Directory.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)); @@ -798,10 +790,10 @@ namespace Ryujinx.Modules public static void CleanupUpdate() { - foreach (string file in Directory.GetFiles(HomeDir, "*.ryuold", SearchOption.AllDirectories)) + foreach (string file in Directory.GetFiles(_homeDir, "*.ryuold", SearchOption.AllDirectories)) { File.Delete(file); } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/Program.cs b/src/Ryujinx.Ava/Program.cs index 0629e6062..5241f91f8 100644 --- a/src/Ryujinx.Ava/Program.cs +++ b/src/Ryujinx.Ava/Program.cs @@ -22,16 +22,16 @@ namespace Ryujinx.Ava { internal partial class Program { - public static double WindowScaleFactor { get; set; } + public static double WindowScaleFactor { get; set; } public static double DesktopScaleFactor { get; set; } = 1.0; - public static string Version { get; private set; } - public static string ConfigurationPath { get; private set; } - public static bool PreviewerDetached { get; private set; } + public static string Version { get; private set; } + public static string ConfigurationPath { get; private set; } + public static bool PreviewerDetached { get; private set; } [LibraryImport("user32.dll", SetLastError = true)] public static partial int MessageBoxA(IntPtr hWnd, [MarshalAs(UnmanagedType.LPStr)] string text, [MarshalAs(UnmanagedType.LPStr)] string caption, uint type); - private const uint MB_ICONWARNING = 0x30; + private const uint MbIconwarning = 0x30; public static void Main(string[] args) { @@ -39,7 +39,7 @@ namespace Ryujinx.Ava if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134)) { - _ = MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MB_ICONWARNING); + _ = MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MbIconwarning); } PreviewerDetached = true; @@ -58,15 +58,15 @@ namespace Ryujinx.Ava .With(new X11PlatformOptions { EnableMultiTouch = true, - EnableIme = true, - UseEGL = false, - UseGpu = true + EnableIme = true, + UseEGL = false, + UseGpu = true, }) .With(new Win32PlatformOptions { - EnableMultitouch = true, - UseWgl = false, - AllowEglInitialization = false, + EnableMultitouch = true, + UseWgl = false, + AllowEglInitialization = false, CompositionBackdropCornerRadius = 8.0f, }) .UseSkia(); @@ -84,7 +84,7 @@ namespace Ryujinx.Ava // Hook unhandled exception and process exit events. AppDomain.CurrentDomain.UnhandledException += (sender, e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating); - AppDomain.CurrentDomain.ProcessExit += (sender, e) => Exit(); + AppDomain.CurrentDomain.ProcessExit += (sender, e) => Exit(); // Setup base data directory. AppDataManager.Initialize(CommandLineState.BaseDirPathArg); @@ -130,7 +130,7 @@ namespace Ryujinx.Ava public static void ReloadConfig() { - string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json"); + string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json"); string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json"); // Now load the configuration as the other subsystems are now registered @@ -192,7 +192,7 @@ namespace Ryujinx.Ava "never" => HideCursorMode.Never, "onidle" => HideCursorMode.OnIdle, "always" => HideCursorMode.Always, - _ => ConfigurationState.Instance.HideCursor.Value + _ => ConfigurationState.Instance.HideCursor.Value, }; } } @@ -238,4 +238,4 @@ namespace Ryujinx.Ava Logger.Shutdown(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Applet/AvaHostUiHandler.cs b/src/Ryujinx.Ava/UI/Applet/AvaHostUiHandler.cs index c87308cfb..a2a944297 100644 --- a/src/Ryujinx.Ava/UI/Applet/AvaHostUiHandler.cs +++ b/src/Ryujinx.Ava/UI/Applet/AvaHostUiHandler.cs @@ -53,8 +53,6 @@ namespace Ryujinx.Ava.UI.Applet bool opened = false; - _parent.Activate(); - UserResult response = await ContentDialogHelper.ShowDeferredContentDialog(_parent, title, message, @@ -64,7 +62,7 @@ namespace Ryujinx.Ava.UI.Applet LocaleManager.Instance[LocaleKeys.SettingsButtonClose], (int)Symbol.Important, deferEvent, - async (window) => + async window => { if (opened) { @@ -112,7 +110,7 @@ namespace Ryujinx.Ava.UI.Applet { try { - var response = await SwkbdAppletDialog.ShowInputDialog(_parent, LocaleManager.Instance[LocaleKeys.SoftwareKeyboard], args); + var response = await SwkbdAppletDialog.ShowInputDialog(LocaleManager.Instance[LocaleKeys.SoftwareKeyboard], args); if (response.Result == UserResult.Ok) { @@ -142,10 +140,7 @@ namespace Ryujinx.Ava.UI.Applet public void ExecuteProgram(Switch device, ProgramSpecifyKind kind, ulong value) { device.Configuration.UserChannelPersistence.ExecuteProgram(kind, value); - if (_parent.ViewModel.AppHost != null) - { - _parent.ViewModel.AppHost.Stop(); - } + _parent.ViewModel.AppHost?.Stop(); } public bool DisplayErrorAppletDialog(string title, string message, string[] buttons) @@ -162,7 +157,7 @@ namespace Ryujinx.Ava.UI.Applet { Title = title, WindowStartupLocation = WindowStartupLocation.CenterScreen, - Width = 400 + Width = 400, }; object response = await msgDialog.Run(); @@ -194,4 +189,4 @@ namespace Ryujinx.Ava.UI.Applet return new AvaloniaDynamicTextInputHandler(_parent); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Applet/AvaloniaDynamicTextInputHandler.cs b/src/Ryujinx.Ava/UI/Applet/AvaloniaDynamicTextInputHandler.cs index 2dd65e362..2fa4d54f8 100644 --- a/src/Ryujinx.Ava/UI/Applet/AvaloniaDynamicTextInputHandler.cs +++ b/src/Ryujinx.Ava/UI/Applet/AvaloniaDynamicTextInputHandler.cs @@ -3,13 +3,11 @@ using Avalonia.Controls; using Avalonia.Input; using Avalonia.Threading; using Ryujinx.Ava.Input; -using Ryujinx.Ava.UI.Controls; using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.Windows; using Ryujinx.HLE.Ui; using System; using System.Threading; - using HidKey = Ryujinx.Common.Configuration.Hid.Key; namespace Ryujinx.Ava.UI.Applet @@ -17,7 +15,7 @@ namespace Ryujinx.Ava.UI.Applet class AvaloniaDynamicTextInputHandler : IDynamicTextInputHandler { private MainWindow _parent; - private OffscreenTextBox _hiddenTextBox; + private readonly OffscreenTextBox _hiddenTextBox; private bool _canProcessInput; private IDisposable _textChangedSubscription; private IDisposable _selectionStartChangedSubscription; @@ -76,7 +74,7 @@ namespace Ryujinx.Ava.UI.Applet return; } - e.RoutedEvent = _hiddenTextBox.GetKeyUpRoutedEvent(); + e.RoutedEvent = OffscreenTextBox.GetKeyUpRoutedEvent(); Dispatcher.UIThread.InvokeAsync(() => { @@ -96,7 +94,7 @@ namespace Ryujinx.Ava.UI.Applet return; } - e.RoutedEvent = _hiddenTextBox.GetKeyUpRoutedEvent(); + e.RoutedEvent = OffscreenTextBox.GetKeyUpRoutedEvent(); Dispatcher.UIThread.InvokeAsync(() => { diff --git a/src/Ryujinx.Ava/UI/Applet/AvaloniaHostUiTheme.cs b/src/Ryujinx.Ava/UI/Applet/AvaloniaHostUiTheme.cs index 77c7a2d2c..3cf273347 100644 --- a/src/Ryujinx.Ava/UI/Applet/AvaloniaHostUiTheme.cs +++ b/src/Ryujinx.Ava/UI/Applet/AvaloniaHostUiTheme.cs @@ -9,7 +9,7 @@ namespace Ryujinx.Ava.UI.Applet { public AvaloniaHostUiTheme(MainWindow parent) { - FontFamily = OperatingSystem.IsWindows() && OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000, 0) ? "Segoe UI Variable" : parent.FontFamily.Name; + FontFamily = OperatingSystem.IsWindows() && OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000) ? "Segoe UI Variable" : parent.FontFamily.Name; DefaultBackgroundColor = BrushToThemeColor(parent.Background); DefaultForegroundColor = BrushToThemeColor(parent.Foreground); DefaultBorderColor = BrushToThemeColor(parent.BorderBrush); @@ -25,7 +25,7 @@ namespace Ryujinx.Ava.UI.Applet public ThemeColor SelectionBackgroundColor { get; } public ThemeColor SelectionForegroundColor { get; } - private ThemeColor BrushToThemeColor(IBrush brush) + private static ThemeColor BrushToThemeColor(IBrush brush) { if (brush is SolidColorBrush solidColor) { @@ -34,10 +34,8 @@ namespace Ryujinx.Ava.UI.Applet (float)solidColor.Color.G / 255, (float)solidColor.Color.B / 255); } - else - { - return new ThemeColor(); - } + + return new ThemeColor(); } } } diff --git a/src/Ryujinx.Ava/UI/Applet/ErrorAppletWindow.axaml.cs b/src/Ryujinx.Ava/UI/Applet/ErrorAppletWindow.axaml.cs index 4134797ba..b77cc4020 100644 --- a/src/Ryujinx.Ava/UI/Applet/ErrorAppletWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Applet/ErrorAppletWindow.axaml.cs @@ -1,10 +1,12 @@ -using Avalonia; using Avalonia.Controls; using Avalonia.Interactivity; using Avalonia.Threading; using Ryujinx.Ava.Common.Locale; using Ryujinx.Ava.UI.Windows; using System.Threading.Tasks; +#if DEBUG +using Avalonia; +#endif namespace Ryujinx.Ava.UI.Applet { @@ -77,4 +79,4 @@ namespace Ryujinx.Ava.UI.Applet return _buttonResponse; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Applet/SwkbdAppletDialog.axaml.cs b/src/Ryujinx.Ava/UI/Applet/SwkbdAppletDialog.axaml.cs index 04bc46193..210fc9a2b 100644 --- a/src/Ryujinx.Ava/UI/Applet/SwkbdAppletDialog.axaml.cs +++ b/src/Ryujinx.Ava/UI/Applet/SwkbdAppletDialog.axaml.cs @@ -1,13 +1,10 @@ -using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; -using FluentAvalonia.Core; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.Common.Locale; using Ryujinx.Ava.UI.Helpers; -using Ryujinx.Ava.UI.Windows; using Ryujinx.HLE.HOS.Applets; using Ryujinx.HLE.HOS.Applets.SoftwareKeyboard; using System; @@ -22,7 +19,7 @@ namespace Ryujinx.Ava.UI.Controls private Predicate _checkInput = _ => true; private int _inputMax; private int _inputMin; - private string _placeholder; + private readonly string _placeholder; private ContentDialog _host; @@ -57,13 +54,13 @@ namespace Ryujinx.Ava.UI.Controls public string MainText { get; set; } = ""; public string SecondaryText { get; set; } = ""; - public static async Task<(UserResult Result, string Input)> ShowInputDialog(StyleableWindow window, string title, SoftwareKeyboardUiArgs args) + public static async Task<(UserResult Result, string Input)> ShowInputDialog(string title, SoftwareKeyboardUiArgs args) { - ContentDialog contentDialog = new ContentDialog(); + ContentDialog contentDialog = new(); UserResult result = UserResult.Cancel; - SwkbdAppletDialog content = new SwkbdAppletDialog(args.HeaderText, args.SubtitleText, args.GuideText, args.InitialText); + SwkbdAppletDialog content = new(args.HeaderText, args.SubtitleText, args.GuideText, args.InitialText); string input = string.Empty; @@ -78,15 +75,16 @@ namespace Ryujinx.Ava.UI.Controls contentDialog.CloseButtonText = LocaleManager.Instance[LocaleKeys.InputDialogCancel]; contentDialog.Content = content; - TypedEventHandler handler = (sender, eventArgs) => + void Handler(ContentDialog sender, ContentDialogClosedEventArgs eventArgs) { if (eventArgs.Result == ContentDialogResult.Primary) { result = UserResult.Ok; input = content.Input.Text; } - }; - contentDialog.Closed += handler; + } + + contentDialog.Closed += Handler; await ContentDialogHelper.ShowAsync(contentDialog); @@ -146,7 +144,7 @@ namespace Ryujinx.Ava.UI.Controls case KeyboardMode.Alphabet: localeText = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.SoftwareKeyboardModeAlphabet); validationInfoText = string.IsNullOrEmpty(validationInfoText) ? localeText : string.Join("\n", validationInfoText, localeText); - _checkInput = text => text.All(char.IsAsciiLetter); + _checkInput = text => text.All(value => !CJKCharacterValidation.IsCJK(value)); break; case KeyboardMode.ASCII: localeText = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.SoftwareKeyboardModeASCII); @@ -182,4 +180,4 @@ namespace Ryujinx.Ava.UI.Controls } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Controls/ApplicationContextMenu.axaml.cs b/src/Ryujinx.Ava/UI/Controls/ApplicationContextMenu.axaml.cs index 73c53e7f6..77b4f5207 100644 --- a/src/Ryujinx.Ava/UI/Controls/ApplicationContextMenu.axaml.cs +++ b/src/Ryujinx.Ava/UI/Controls/ApplicationContextMenu.axaml.cs @@ -10,15 +10,14 @@ using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Ava.UI.Windows; using Ryujinx.Common.Configuration; -using Ryujinx.Ui.App.Common; using Ryujinx.HLE.HOS; +using Ryujinx.Ui.App.Common; using Ryujinx.Ui.Common.Helper; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Path = System.IO.Path; -using UserId = LibHac.Fs.UserId; namespace Ryujinx.Ava.UI.Controls { @@ -42,7 +41,7 @@ namespace Ryujinx.Ava.UI.Controls { viewModel.SelectedApplication.Favorite = !viewModel.SelectedApplication.Favorite; - viewModel.ApplicationLibrary.LoadAndSaveMetaData(viewModel.SelectedApplication.TitleId, appMetadata => + ApplicationLibrary.LoadAndSaveMetaData(viewModel.SelectedApplication.TitleId, appMetadata => { appMetadata.Favorite = viewModel.SelectedApplication.Favorite; }); @@ -53,7 +52,7 @@ namespace Ryujinx.Ava.UI.Controls public void OpenUserSaveDirectory_Click(object sender, RoutedEventArgs args) { - if ((sender as MenuItem)?.DataContext is MainWindowViewModel viewModel) + if (sender is MenuItem { DataContext: MainWindowViewModel viewModel }) { OpenSaveDirectory(viewModel, SaveDataType.Account, userId: new UserId((ulong)viewModel.AccountManager.LastOpenedUser.UserId.High, (ulong)viewModel.AccountManager.LastOpenedUser.UserId.Low)); } @@ -334,4 +333,4 @@ namespace Ryujinx.Ava.UI.Controls } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Controls/ApplicationGridView.axaml.cs b/src/Ryujinx.Ava/UI/Controls/ApplicationGridView.axaml.cs index c30c75b36..efdc9ab02 100644 --- a/src/Ryujinx.Ava/UI/Controls/ApplicationGridView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Controls/ApplicationGridView.axaml.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ava.UI.Controls public event EventHandler ApplicationOpened { - add { AddHandler(ApplicationOpenedEvent, value); } + add { AddHandler(ApplicationOpenedEvent, value); } remove { RemoveHandler(ApplicationOpenedEvent, value); } } diff --git a/src/Ryujinx.Ava/UI/Controls/ApplicationListView.axaml.cs b/src/Ryujinx.Ava/UI/Controls/ApplicationListView.axaml.cs index 1a07c4251..1646fc1b1 100644 --- a/src/Ryujinx.Ava/UI/Controls/ApplicationListView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Controls/ApplicationListView.axaml.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ava.UI.Controls public event EventHandler ApplicationOpened { - add { AddHandler(ApplicationOpenedEvent, value); } + add { AddHandler(ApplicationOpenedEvent, value); } remove { RemoveHandler(ApplicationOpenedEvent, value); } } diff --git a/src/Ryujinx.Ava/UI/Controls/NavigationDialogHost.axaml.cs b/src/Ryujinx.Ava/UI/Controls/NavigationDialogHost.axaml.cs index 1b857fae4..a32c052bf 100644 --- a/src/Ryujinx.Ava/UI/Controls/NavigationDialogHost.axaml.cs +++ b/src/Ryujinx.Ava/UI/Controls/NavigationDialogHost.axaml.cs @@ -2,7 +2,6 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Styling; using Avalonia.Threading; -using FluentAvalonia.Core; using FluentAvalonia.UI.Controls; using LibHac; using LibHac.Common; @@ -10,7 +9,6 @@ using LibHac.Fs; using LibHac.Fs.Shim; using Ryujinx.Ava.Common.Locale; using Ryujinx.Ava.UI.Helpers; -using Ryujinx.Ava.UI.Models; using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Ava.UI.Views.User; using Ryujinx.HLE.FileSystem; @@ -19,6 +17,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using UserId = Ryujinx.HLE.HOS.Services.Account.Acc.UserId; using UserProfile = Ryujinx.Ava.UI.Models.UserProfile; namespace Ryujinx.Ava.UI.Controls @@ -56,7 +55,7 @@ namespace Ryujinx.Ava.UI.Controls InitializeComponent(); } - public void GoBack(object parameter = null) + public void GoBack() { if (ContentFrame.BackStack.Count > 0) { @@ -75,14 +74,14 @@ namespace Ryujinx.Ava.UI.Controls VirtualFileSystem ownerVirtualFileSystem, HorizonClient ownerHorizonClient) { var content = new NavigationDialogHost(ownerAccountManager, ownerContentManager, ownerVirtualFileSystem, ownerHorizonClient); - ContentDialog contentDialog = new ContentDialog + ContentDialog contentDialog = new() { Title = LocaleManager.Instance[LocaleKeys.UserProfileWindowTitle], PrimaryButtonText = "", SecondaryButtonText = "", CloseButtonText = "", Content = content, - Padding = new Thickness(0) + Padding = new Thickness(0), }; contentDialog.Closed += (sender, args) => @@ -125,7 +124,7 @@ namespace Ryujinx.Ava.UI.Controls Span saveDataInfo = stackalloc SaveDataInfo[10]; - HashSet lostAccounts = new(); + HashSet lostAccounts = new(); while (true) { @@ -139,15 +138,15 @@ namespace Ryujinx.Ava.UI.Controls for (int i = 0; i < readCount; i++) { var save = saveDataInfo[i]; - var id = new HLE.HOS.Services.Account.Acc.UserId((long)save.UserId.Id.Low, (long)save.UserId.Id.High); - if (ViewModel.Profiles.Cast().FirstOrDefault( x=> x.UserId == id) == null) + var id = new UserId((long)save.UserId.Id.Low, (long)save.UserId.Id.High); + if (ViewModel.Profiles.Cast().FirstOrDefault(x => x.UserId == id) == null) { lostAccounts.Add(id); } } } - foreach(var account in lostAccounts) + foreach (var account in lostAccounts) { ViewModel.LostProfiles.Add(new UserProfile(new HLE.HOS.Services.Account.Acc.UserProfile(account, "", null), this)); } @@ -166,7 +165,7 @@ namespace Ryujinx.Ava.UI.Controls if (profile == null) { - async void Action() + static async void Action() { await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogUserProfileDeletionWarningMessage]); } @@ -215,4 +214,4 @@ namespace Ryujinx.Ava.UI.Controls Navigate(typeof(UserSaveManagerView), (this, AccountManager, HorizonClient, VirtualFileSystem)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Controls/UpdateWaitWindow.axaml.cs b/src/Ryujinx.Ava/UI/Controls/UpdateWaitWindow.axaml.cs index 80a437e33..7ad1ee332 100644 --- a/src/Ryujinx.Ava/UI/Controls/UpdateWaitWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Controls/UpdateWaitWindow.axaml.cs @@ -28,4 +28,4 @@ namespace Ryujinx.Ava.UI.Controls InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/ApplicationOpenedEventArgs.cs b/src/Ryujinx.Ava/UI/Helpers/ApplicationOpenedEventArgs.cs index ebf5c16ec..cd63a99b0 100644 --- a/src/Ryujinx.Ava/UI/Helpers/ApplicationOpenedEventArgs.cs +++ b/src/Ryujinx.Ava/UI/Helpers/ApplicationOpenedEventArgs.cs @@ -13,4 +13,4 @@ namespace Ryujinx.Ava.UI.Helpers RoutedEvent = routedEvent; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/BitmapArrayValueConverter.cs b/src/Ryujinx.Ava/UI/Helpers/BitmapArrayValueConverter.cs index 133f8dbc9..42bd8d5a8 100644 --- a/src/Ryujinx.Ava/UI/Helpers/BitmapArrayValueConverter.cs +++ b/src/Ryujinx.Ava/UI/Helpers/BitmapArrayValueConverter.cs @@ -33,4 +33,4 @@ namespace Ryujinx.Ava.UI.Helpers throw new NotSupportedException(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/ButtonKeyAssigner.cs b/src/Ryujinx.Ava/UI/Helpers/ButtonKeyAssigner.cs index 6730b5711..7e8ba7342 100644 --- a/src/Ryujinx.Ava/UI/Helpers/ButtonKeyAssigner.cs +++ b/src/Ryujinx.Ava/UI/Helpers/ButtonKeyAssigner.cs @@ -23,7 +23,7 @@ namespace Ryujinx.Ava.UI.Helpers IsAssigned = isAssigned; } } - + public ToggleButton ToggledButton { get; set; } private bool _isWaitingForInput; diff --git a/src/Ryujinx.Ava/UI/Helpers/ContentDialogHelper.cs b/src/Ryujinx.Ava/UI/Helpers/ContentDialogHelper.cs index 045d508c6..086de953d 100644 --- a/src/Ryujinx.Ava/UI/Helpers/ContentDialogHelper.cs +++ b/src/Ryujinx.Ava/UI/Helpers/ContentDialogHelper.cs @@ -1,6 +1,7 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Layout; using Avalonia.Media; using Avalonia.Threading; using FluentAvalonia.Core; @@ -32,18 +33,17 @@ namespace Ryujinx.Ava.UI.Helpers ContentDialog contentDialog = new() { - Title = title, - PrimaryButtonText = primaryButton, + Title = title, + PrimaryButtonText = primaryButton, SecondaryButtonText = secondaryButton, - CloseButtonText = closeButton, - Content = content + CloseButtonText = closeButton, + Content = content, + PrimaryButtonCommand = MiniCommand.Create(() => + { + result = primaryButtonResult; + }), }; - contentDialog.PrimaryButtonCommand = MiniCommand.Create(() => - { - result = primaryButtonResult; - }); - contentDialog.SecondaryButtonCommand = MiniCommand.Create(() => { result = UserResult.No; @@ -96,7 +96,6 @@ namespace Ryujinx.Ava.UI.Helpers Func doWhileDeferred = null) { bool startedDeferring = false; - UserResult result = UserResult.None; return await ShowTextDialog( title, @@ -123,8 +122,6 @@ namespace Ryujinx.Ava.UI.Helpers var deferral = args.GetDeferral(); - result = primaryButton == LocaleManager.Instance[LocaleKeys.InputDialogYes] ? UserResult.Yes : UserResult.Ok; - sender.PrimaryButtonClick -= DeferClose; _ = Task.Run(() => @@ -150,18 +147,18 @@ namespace Ryujinx.Ava.UI.Helpers { Grid content = new() { - RowDefinitions = new RowDefinitions() { new RowDefinition(), new RowDefinition() }, - ColumnDefinitions = new ColumnDefinitions() { new ColumnDefinition(GridLength.Auto), new ColumnDefinition() }, + RowDefinitions = new RowDefinitions { new(), new() }, + ColumnDefinitions = new ColumnDefinitions { new(GridLength.Auto), new() }, - MinHeight = 80 + MinHeight = 80, }; SymbolIcon icon = new() { - Symbol = (Symbol)symbol, - Margin = new Thickness(10), - FontSize = 40, - VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center + Symbol = (Symbol)symbol, + Margin = new Thickness(10), + FontSize = 40, + VerticalAlignment = VerticalAlignment.Center, }; Grid.SetColumn(icon, 0); @@ -170,18 +167,18 @@ namespace Ryujinx.Ava.UI.Helpers TextBlock primaryLabel = new() { - Text = primaryText, - Margin = new Thickness(5), + Text = primaryText, + Margin = new Thickness(5), TextWrapping = TextWrapping.Wrap, - MaxWidth = 450 + MaxWidth = 450, }; TextBlock secondaryLabel = new() { - Text = secondaryText, - Margin = new Thickness(5), + Text = secondaryText, + Margin = new Thickness(5), TextWrapping = TextWrapping.Wrap, - MaxWidth = 450 + MaxWidth = 450, }; Grid.SetColumn(primaryLabel, 1); @@ -318,14 +315,16 @@ namespace Ryujinx.Ava.UI.Helpers Window parent = GetMainWindow(); - if (parent != null && parent.IsActive && (parent as MainWindow).ViewModel.IsGameRunning) + if (parent is MainWindow window) { + parent.Activate(); + contentDialogOverlayWindow = new() { - Height = parent.Bounds.Height, - Width = parent.Bounds.Width, - Position = parent.PointToScreen(new Point()), - ShowInTaskbar = false + Height = parent.Bounds.Height, + Width = parent.Bounds.Width, + Position = parent.PointToScreen(new Point()), + ShowInTaskbar = false, }; parent.PositionChanged += OverlayOnPositionChanged; @@ -372,7 +371,9 @@ namespace Ryujinx.Ava.UI.Helpers } else { - result = await contentDialog.ShowAsync(); + result = ContentDialogResult.None; + + Logger.Warning?.Print(LogClass.Ui, "Content dialog overlay failed to populate. Default value has been returned."); } return result; @@ -389,11 +390,11 @@ namespace Ryujinx.Ava.UI.Helpers private static Window GetMainWindow() { - if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime al) + if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime al) { foreach (Window item in al.Windows) { - if (item.IsActive && item is MainWindow window) + if (item is MainWindow window) { return window; } @@ -403,4 +404,4 @@ namespace Ryujinx.Ava.UI.Helpers return null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/Glyph.cs b/src/Ryujinx.Ava/UI/Helpers/Glyph.cs index 4aae854f7..e30de69bb 100644 --- a/src/Ryujinx.Ava/UI/Helpers/Glyph.cs +++ b/src/Ryujinx.Ava/UI/Helpers/Glyph.cs @@ -4,6 +4,6 @@ { List, Grid, - Chip + Chip, } } diff --git a/src/Ryujinx.Ava/UI/Helpers/GlyphValueConverter.cs b/src/Ryujinx.Ava/UI/Helpers/GlyphValueConverter.cs index 3d6c9c018..4e4b971eb 100644 --- a/src/Ryujinx.Ava/UI/Helpers/GlyphValueConverter.cs +++ b/src/Ryujinx.Ava/UI/Helpers/GlyphValueConverter.cs @@ -1,5 +1,6 @@ using Avalonia.Data; using Avalonia.Markup.Xaml; +using Avalonia.Markup.Xaml.MarkupExtensions; using FluentAvalonia.UI.Controls; using System; using System.Collections.Generic; @@ -8,13 +9,13 @@ namespace Ryujinx.Ava.UI.Helpers { public class GlyphValueConverter : MarkupExtension { - private string _key; + private readonly string _key; - private static Dictionary _glyphs = new Dictionary + private static readonly Dictionary _glyphs = new() { - { Glyph.List, char.ConvertFromUtf32((int)Symbol.List).ToString() }, - { Glyph.Grid, char.ConvertFromUtf32((int)Symbol.ViewAll).ToString() }, - { Glyph.Chip, char.ConvertFromUtf32(59748).ToString() } + { Glyph.List, char.ConvertFromUtf32((int)Symbol.List) }, + { Glyph.Grid, char.ConvertFromUtf32((int)Symbol.ViewAll) }, + { Glyph.Chip, char.ConvertFromUtf32(59748) }, }; public GlyphValueConverter(string key) @@ -37,13 +38,13 @@ namespace Ryujinx.Ava.UI.Helpers public override object ProvideValue(IServiceProvider serviceProvider) { - Avalonia.Markup.Xaml.MarkupExtensions.ReflectionBindingExtension binding = new($"[{_key}]") + ReflectionBindingExtension binding = new($"[{_key}]") { Mode = BindingMode.OneWay, - Source = this + Source = this, }; return binding.ProvideValue(serviceProvider); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/HotKeyControl.cs b/src/Ryujinx.Ava/UI/Helpers/HotKeyControl.cs index f1fad1576..4ae903b49 100644 --- a/src/Ryujinx.Ava/UI/Helpers/HotKeyControl.cs +++ b/src/Ryujinx.Ava/UI/Helpers/HotKeyControl.cs @@ -49,4 +49,4 @@ namespace Ryujinx.Ava.UI.Helpers } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/KeyValueConverter.cs b/src/Ryujinx.Ava/UI/Helpers/KeyValueConverter.cs index 8d5c2815a..028ed6bf4 100644 --- a/src/Ryujinx.Ava/UI/Helpers/KeyValueConverter.cs +++ b/src/Ryujinx.Ava/UI/Helpers/KeyValueConverter.cs @@ -43,4 +43,4 @@ namespace Ryujinx.Ava.UI.Helpers return key; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/LoggerAdapter.cs b/src/Ryujinx.Ava/UI/Helpers/LoggerAdapter.cs index 7a29cc198..dc8e3f945 100644 --- a/src/Ryujinx.Ava/UI/Helpers/LoggerAdapter.cs +++ b/src/Ryujinx.Ava/UI/Helpers/LoggerAdapter.cs @@ -1,15 +1,17 @@ +using Avalonia.Logging; using Avalonia.Utilities; +using Ryujinx.Common.Logging; using System; using System.Text; namespace Ryujinx.Ava.UI.Helpers { - using AvaLogger = Avalonia.Logging.Logger; - using AvaLogLevel = Avalonia.Logging.LogEventLevel; - using RyuLogClass = Ryujinx.Common.Logging.LogClass; - using RyuLogger = Ryujinx.Common.Logging.Logger; + using AvaLogger = Avalonia.Logging.Logger; + using AvaLogLevel = LogEventLevel; + using RyuLogClass = LogClass; + using RyuLogger = Ryujinx.Common.Logging.Logger; - internal class LoggerAdapter : Avalonia.Logging.ILogSink + internal class LoggerAdapter : ILogSink { public static void Register() { @@ -20,13 +22,13 @@ namespace Ryujinx.Ava.UI.Helpers { return level switch { - AvaLogLevel.Verbose => RyuLogger.Debug, - AvaLogLevel.Debug => RyuLogger.Debug, + AvaLogLevel.Verbose => RyuLogger.Debug, + AvaLogLevel.Debug => RyuLogger.Debug, AvaLogLevel.Information => RyuLogger.Debug, - AvaLogLevel.Warning => RyuLogger.Debug, - AvaLogLevel.Error => RyuLogger.Error, - AvaLogLevel.Fatal => RyuLogger.Error, - _ => throw new ArgumentOutOfRangeException(nameof(level), level, null) + AvaLogLevel.Warning => RyuLogger.Debug, + AvaLogLevel.Error => RyuLogger.Error, + AvaLogLevel.Fatal => RyuLogger.Error, + _ => throw new ArgumentOutOfRangeException(nameof(level), level, null), }; } @@ -45,7 +47,7 @@ namespace Ryujinx.Ava.UI.Helpers GetLog(level)?.PrintMsg(RyuLogClass.Ui, Format(level, area, messageTemplate, source, new object[] { propertyValue0 })); } - public void Log(AvaLogLevel level, string area, object source, string messageTemplate, T0 propertyValue0, T1 propertyValue1) + public void Log(AvaLogLevel level, string area, object source, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { GetLog(level)?.PrintMsg(RyuLogClass.Ui, Format(level, area, messageTemplate, source, new object[] { propertyValue0, propertyValue1 })); } @@ -112,4 +114,4 @@ namespace Ryujinx.Ava.UI.Helpers return result.ToString(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/MiniCommand.cs b/src/Ryujinx.Ava/UI/Helpers/MiniCommand.cs index 305182c92..864f53b8a 100644 --- a/src/Ryujinx.Ava/UI/Helpers/MiniCommand.cs +++ b/src/Ryujinx.Ava/UI/Helpers/MiniCommand.cs @@ -8,7 +8,7 @@ namespace Ryujinx.Ava.UI.Helpers { private readonly Action _callback; private bool _busy; - private Func _asyncCallback; + private readonly Func _asyncCallback; public MiniCommand(Action callback) { @@ -68,4 +68,4 @@ namespace Ryujinx.Ava.UI.Helpers public abstract void Execute(object parameter); public abstract event EventHandler CanExecuteChanged; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/NotificationHelper.cs b/src/Ryujinx.Ava/UI/Helpers/NotificationHelper.cs index f207c5fb0..a11fb5267 100644 --- a/src/Ryujinx.Ava/UI/Helpers/NotificationHelper.cs +++ b/src/Ryujinx.Ava/UI/Helpers/NotificationHelper.cs @@ -12,12 +12,12 @@ namespace Ryujinx.Ava.UI.Helpers { public static class NotificationHelper { - private const int MaxNotifications = 4; + private const int MaxNotifications = 4; private const int NotificationDelayInMs = 5000; private static WindowNotificationManager _notificationManager; - private static readonly BlockingCollection _notifications = new(); + private static readonly BlockingCollection _notifications = new(); public static void SetNotificationManager(Window host) { @@ -25,7 +25,7 @@ namespace Ryujinx.Ava.UI.Helpers { Position = NotificationPosition.BottomRight, MaxItems = MaxNotifications, - Margin = new Thickness(0, 0, 15, 40) + Margin = new Thickness(0, 0, 15, 40), }; var maybeAsyncWorkQueue = new Lazy>( @@ -67,4 +67,4 @@ namespace Ryujinx.Ava.UI.Helpers Show(LocaleManager.Instance[LocaleKeys.DialogErrorTitle], $"{LocaleManager.Instance[LocaleKeys.DialogErrorMessage]}\n\n{message}", NotificationType.Error); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/NullableDateTimeConverter.cs b/src/Ryujinx.Ava/UI/Helpers/NullableDateTimeConverter.cs index 1d862de01..e91937612 100644 --- a/src/Ryujinx.Ava/UI/Helpers/NullableDateTimeConverter.cs +++ b/src/Ryujinx.Ava/UI/Helpers/NullableDateTimeConverter.cs @@ -35,4 +35,4 @@ namespace Ryujinx.Ava.UI.Helpers return _instance; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/OffscreenTextBox.cs b/src/Ryujinx.Ava/UI/Helpers/OffscreenTextBox.cs index 785e785cd..670d3b361 100644 --- a/src/Ryujinx.Ava/UI/Helpers/OffscreenTextBox.cs +++ b/src/Ryujinx.Ava/UI/Helpers/OffscreenTextBox.cs @@ -6,12 +6,12 @@ namespace Ryujinx.Ava.UI.Helpers { public class OffscreenTextBox : TextBox { - public RoutedEvent GetKeyDownRoutedEvent() + public static RoutedEvent GetKeyDownRoutedEvent() { return KeyDownEvent; } - public RoutedEvent GetKeyUpRoutedEvent() + public static RoutedEvent GetKeyUpRoutedEvent() { return KeyUpEvent; } @@ -28,13 +28,13 @@ namespace Ryujinx.Ava.UI.Helpers public void SendText(string text) { - OnTextInput(new TextInputEventArgs() + OnTextInput(new TextInputEventArgs { Text = text, Device = KeyboardDevice.Instance, Source = this, - RoutedEvent = TextInputEvent + RoutedEvent = TextInputEvent, }); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/UserErrorDialog.cs b/src/Ryujinx.Ava/UI/Helpers/UserErrorDialog.cs index 4ed629ff1..afd2958c6 100644 --- a/src/Ryujinx.Ava/UI/Helpers/UserErrorDialog.cs +++ b/src/Ryujinx.Ava/UI/Helpers/UserErrorDialog.cs @@ -1,5 +1,4 @@ using Ryujinx.Ava.Common.Locale; -using Ryujinx.Ava.UI.Windows; using Ryujinx.Ui.Common; using Ryujinx.Ui.Common.Helper; using System.Threading.Tasks; @@ -24,7 +23,7 @@ namespace Ryujinx.Ava.UI.Helpers UserError.FirmwareParsingFailed => LocaleManager.Instance[LocaleKeys.UserErrorFirmwareParsingFailed], UserError.ApplicationNotFound => LocaleManager.Instance[LocaleKeys.UserErrorApplicationNotFound], UserError.Unknown => LocaleManager.Instance[LocaleKeys.UserErrorUnknown], - _ => LocaleManager.Instance[LocaleKeys.UserErrorUndefined] + _ => LocaleManager.Instance[LocaleKeys.UserErrorUndefined], }; } @@ -37,7 +36,7 @@ namespace Ryujinx.Ava.UI.Helpers UserError.FirmwareParsingFailed => LocaleManager.Instance[LocaleKeys.UserErrorFirmwareParsingFailedDescription], UserError.ApplicationNotFound => LocaleManager.Instance[LocaleKeys.UserErrorApplicationNotFoundDescription], UserError.Unknown => LocaleManager.Instance[LocaleKeys.UserErrorUnknownDescription], - _ => LocaleManager.Instance[LocaleKeys.UserErrorUndefinedDescription] + _ => LocaleManager.Instance[LocaleKeys.UserErrorUndefinedDescription], }; } @@ -48,7 +47,7 @@ namespace Ryujinx.Ava.UI.Helpers UserError.NoKeys or UserError.NoFirmware or UserError.FirmwareParsingFailed => true, - _ => false + _ => false, }; } @@ -63,11 +62,11 @@ namespace Ryujinx.Ava.UI.Helpers { UserError.NoKeys => SetupGuideUrl + "#initial-setup---placement-of-prodkeys", UserError.NoFirmware => SetupGuideUrl + "#initial-setup-continued---installation-of-firmware", - _ => SetupGuideUrl + _ => SetupGuideUrl, }; } - public static async Task ShowUserErrorDialog(UserError error, StyleableWindow owner) + public static async Task ShowUserErrorDialog(UserError error) { string errorCode = GetErrorCode(error); @@ -88,4 +87,4 @@ namespace Ryujinx.Ava.UI.Helpers } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/UserResult.cs b/src/Ryujinx.Ava/UI/Helpers/UserResult.cs index 57802804f..2fcd35ae4 100644 --- a/src/Ryujinx.Ava/UI/Helpers/UserResult.cs +++ b/src/Ryujinx.Ava/UI/Helpers/UserResult.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Ava.UI.Helpers Cancel, None, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Helpers/Win32NativeInterop.cs b/src/Ryujinx.Ava/UI/Helpers/Win32NativeInterop.cs index 03d3a49f3..ca55d0399 100644 --- a/src/Ryujinx.Ava/UI/Helpers/Win32NativeInterop.cs +++ b/src/Ryujinx.Ava/UI/Helpers/Win32NativeInterop.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Runtime.Versioning; @@ -10,46 +11,47 @@ namespace Ryujinx.Ava.UI.Helpers [Flags] public enum ClassStyles : uint { - CS_CLASSDC = 0x40, - CS_OWNDC = 0x20, + CsClassdc = 0x40, + CsOwndc = 0x20, } [Flags] public enum WindowStyles : uint { - WS_CHILD = 0x40000000 + WsChild = 0x40000000, } public enum Cursors : uint { - IDC_ARROW = 32512 + IdcArrow = 32512, } + [SuppressMessage("Design", "CA1069: Enums values should not be duplicated")] public enum WindowsMessages : uint { - MOUSEMOVE = 0x0200, - LBUTTONDOWN = 0x0201, - LBUTTONUP = 0x0202, - LBUTTONDBLCLK = 0x0203, - RBUTTONDOWN = 0x0204, - RBUTTONUP = 0x0205, - RBUTTONDBLCLK = 0x0206, - MBUTTONDOWN = 0x0207, - MBUTTONUP = 0x0208, - MBUTTONDBLCLK = 0x0209, - MOUSEWHEEL = 0x020A, - XBUTTONDOWN = 0x020B, - XBUTTONUP = 0x020C, - XBUTTONDBLCLK = 0x020D, - MOUSEHWHEEL = 0x020E, - MOUSELAST = 0x020E + Mousemove = 0x0200, + Lbuttondown = 0x0201, + Lbuttonup = 0x0202, + Lbuttondblclk = 0x0203, + Rbuttondown = 0x0204, + Rbuttonup = 0x0205, + Rbuttondblclk = 0x0206, + Mbuttondown = 0x0207, + Mbuttonup = 0x0208, + Mbuttondblclk = 0x0209, + Mousewheel = 0x020A, + Xbuttondown = 0x020B, + Xbuttonup = 0x020C, + Xbuttondblclk = 0x020D, + Mousehwheel = 0x020E, + Mouselast = 0x020E, } [UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate IntPtr WindowProc(IntPtr hWnd, WindowsMessages msg, IntPtr wParam, IntPtr lParam); [StructLayout(LayoutKind.Sequential)] - public struct WNDCLASSEX + public struct WndClassEx { public int cbSize; public ClassStyles style; @@ -64,9 +66,9 @@ namespace Ryujinx.Ava.UI.Helpers public IntPtr lpszClassName; public IntPtr hIconSm; - public WNDCLASSEX() + public WndClassEx() { - cbSize = Marshal.SizeOf(); + cbSize = Marshal.SizeOf(); } } @@ -77,17 +79,17 @@ namespace Ryujinx.Ava.UI.Helpers public static IntPtr CreateArrowCursor() { - return LoadCursor(IntPtr.Zero, (IntPtr)Cursors.IDC_ARROW); + return LoadCursor(IntPtr.Zero, (IntPtr)Cursors.IdcArrow); } [LibraryImport("user32.dll")] public static partial IntPtr SetCursor(IntPtr handle); [LibraryImport("user32.dll")] - public static partial IntPtr CreateCursor(IntPtr hInst, int xHotSpot, int yHotSpot, int nWidth, int nHeight, byte[] pvANDPlane, byte[] pvXORPlane); + public static partial IntPtr CreateCursor(IntPtr hInst, int xHotSpot, int yHotSpot, int nWidth, int nHeight, byte[] pvAndPlane, byte[] pvXorPlane); [LibraryImport("user32.dll", SetLastError = true, EntryPoint = "RegisterClassExW")] - public static partial ushort RegisterClassEx(ref WNDCLASSEX param); + public static partial ushort RegisterClassEx(ref WndClassEx param); [LibraryImport("user32.dll", SetLastError = true, EntryPoint = "UnregisterClassW")] public static partial short UnregisterClass([MarshalAs(UnmanagedType.LPWStr)] string lpClassName, IntPtr instance); diff --git a/src/Ryujinx.Ava/UI/Models/CheatModel.cs b/src/Ryujinx.Ava/UI/Models/CheatModel.cs index a7507add9..4434c09f4 100644 --- a/src/Ryujinx.Ava/UI/Models/CheatModel.cs +++ b/src/Ryujinx.Ava/UI/Models/CheatModel.cs @@ -11,8 +11,8 @@ namespace Ryujinx.Ava.UI.Models public CheatModel(string name, string buildId, bool isEnabled) { - Name = name; - BuildId = buildId; + Name = name; + BuildId = buildId; IsEnabled = isEnabled; } @@ -35,6 +35,6 @@ namespace Ryujinx.Ava.UI.Models public string Name { get; } - public string CleanName => Name.Substring(1, Name.Length - 8); + public string CleanName => Name[1..^7]; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/CheatsList.cs b/src/Ryujinx.Ava/UI/Models/CheatsList.cs index e674f4eb7..1cb0480c7 100644 --- a/src/Ryujinx.Ava/UI/Models/CheatsList.cs +++ b/src/Ryujinx.Ava/UI/Models/CheatsList.cs @@ -10,13 +10,13 @@ namespace Ryujinx.Ava.UI.Models public CheatsList(string buildId, string path) { BuildId = buildId; - Path = path; + Path = path; CollectionChanged += CheatsList_CollectionChanged; } public string BuildId { get; } - public string Path { get; } + public string Path { get; } public bool IsEnabled { @@ -48,4 +48,4 @@ namespace Ryujinx.Ava.UI.Models OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsEnabled))); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/DeviceType.cs b/src/Ryujinx.Ava/UI/Models/DeviceType.cs index fa2e620cc..bb4fc3b30 100644 --- a/src/Ryujinx.Ava/UI/Models/DeviceType.cs +++ b/src/Ryujinx.Ava/UI/Models/DeviceType.cs @@ -4,6 +4,6 @@ namespace Ryujinx.Ava.UI.Models { None, Keyboard, - Controller + Controller, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/DownloadableContentModel.cs b/src/Ryujinx.Ava/UI/Models/DownloadableContentModel.cs index b2ad0d31d..fedb3527b 100644 --- a/src/Ryujinx.Ava/UI/Models/DownloadableContentModel.cs +++ b/src/Ryujinx.Ava/UI/Models/DownloadableContentModel.cs @@ -18,18 +18,18 @@ namespace Ryujinx.Ava.UI.Models } } - public string TitleId { get; } + public string TitleId { get; } public string ContainerPath { get; } - public string FullPath { get; } + public string FullPath { get; } public string FileName => Path.GetFileName(ContainerPath); public DownloadableContentModel(string titleId, string containerPath, string fullPath, bool enabled) { - TitleId = titleId; + TitleId = titleId; ContainerPath = containerPath; - FullPath = fullPath; - Enabled = enabled; + FullPath = fullPath; + Enabled = enabled; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/Generic/LastPlayedSortComparer.cs b/src/Ryujinx.Ava/UI/Models/Generic/LastPlayedSortComparer.cs index 3627ada9a..8a4346556 100644 --- a/src/Ryujinx.Ava/UI/Models/Generic/LastPlayedSortComparer.cs +++ b/src/Ryujinx.Ava/UI/Models/Generic/LastPlayedSortComparer.cs @@ -29,4 +29,4 @@ namespace Ryujinx.Ava.UI.Models.Generic return (IsAscending ? 1 : -1) * DateTime.Compare(bValue.Value, aValue.Value); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/InputConfiguration.cs b/src/Ryujinx.Ava/UI/Models/InputConfiguration.cs index 2acd716ba..f1352c6d8 100644 --- a/src/Ryujinx.Ava/UI/Models/InputConfiguration.cs +++ b/src/Ryujinx.Ava/UI/Models/InputConfiguration.cs @@ -7,16 +7,16 @@ using System; namespace Ryujinx.Ava.UI.Models { - internal class InputConfiguration : BaseModel + internal class InputConfiguration : BaseModel { private float _deadzoneRight; private float _triggerThreshold; private float _deadzoneLeft; private double _gyroDeadzone; private int _sensitivity; - private bool enableMotion; - private float weakRumble; - private float strongRumble; + private bool _enableMotion; + private float _weakRumble; + private float _strongRumble; private float _rangeLeft; private float _rangeRight; @@ -37,17 +37,17 @@ namespace Ryujinx.Ava.UI.Models /// public PlayerIndex PlayerIndex { get; set; } - public Stick LeftJoystick { get; set; } + public TStick LeftJoystick { get; set; } public bool LeftInvertStickX { get; set; } public bool LeftInvertStickY { get; set; } public bool RightRotate90 { get; set; } - public Key LeftControllerStickButton { get; set; } + public TKey LeftControllerStickButton { get; set; } - public Stick RightJoystick { get; set; } + public TStick RightJoystick { get; set; } public bool RightInvertStickX { get; set; } public bool RightInvertStickY { get; set; } public bool LeftRotate90 { get; set; } - public Key RightControllerStickButton { get; set; } + public TKey RightControllerStickButton { get; set; } public float DeadzoneLeft { @@ -106,38 +106,37 @@ namespace Ryujinx.Ava.UI.Models public MotionInputBackendType MotionBackend { get; set; } - public Key ButtonMinus { get; set; } - public Key ButtonL { get; set; } - public Key ButtonZl { get; set; } - public Key LeftButtonSl { get; set; } - public Key LeftButtonSr { get; set; } - public Key DpadUp { get; set; } - public Key DpadDown { get; set; } - public Key DpadLeft { get; set; } - public Key DpadRight { get; set; } + public TKey ButtonMinus { get; set; } + public TKey ButtonL { get; set; } + public TKey ButtonZl { get; set; } + public TKey LeftButtonSl { get; set; } + public TKey LeftButtonSr { get; set; } + public TKey DpadUp { get; set; } + public TKey DpadDown { get; set; } + public TKey DpadLeft { get; set; } + public TKey DpadRight { get; set; } - public Key ButtonPlus { get; set; } - public Key ButtonR { get; set; } - public Key ButtonZr { get; set; } - public Key RightButtonSl { get; set; } - public Key RightButtonSr { get; set; } - public Key ButtonX { get; set; } - public Key ButtonB { get; set; } - public Key ButtonY { get; set; } - public Key ButtonA { get; set; } + public TKey ButtonPlus { get; set; } + public TKey ButtonR { get; set; } + public TKey ButtonZr { get; set; } + public TKey RightButtonSl { get; set; } + public TKey RightButtonSr { get; set; } + public TKey ButtonX { get; set; } + public TKey ButtonB { get; set; } + public TKey ButtonY { get; set; } + public TKey ButtonA { get; set; } + public TKey LeftStickUp { get; set; } + public TKey LeftStickDown { get; set; } + public TKey LeftStickLeft { get; set; } + public TKey LeftStickRight { get; set; } + public TKey LeftKeyboardStickButton { get; set; } - public Key LeftStickUp { get; set; } - public Key LeftStickDown { get; set; } - public Key LeftStickLeft { get; set; } - public Key LeftStickRight { get; set; } - public Key LeftKeyboardStickButton { get; set; } - - public Key RightStickUp { get; set; } - public Key RightStickDown { get; set; } - public Key RightStickLeft { get; set; } - public Key RightStickRight { get; set; } - public Key RightKeyboardStickButton { get; set; } + public TKey RightStickUp { get; set; } + public TKey RightStickDown { get; set; } + public TKey RightStickLeft { get; set; } + public TKey RightStickRight { get; set; } + public TKey RightKeyboardStickButton { get; set; } public int Sensitivity { @@ -163,9 +162,9 @@ namespace Ryujinx.Ava.UI.Models public bool EnableMotion { - get => enableMotion; set + get => _enableMotion; set { - enableMotion = value; + _enableMotion = value; OnPropertyChanged(); } @@ -181,18 +180,18 @@ namespace Ryujinx.Ava.UI.Models public bool EnableRumble { get; set; } public float WeakRumble { - get => weakRumble; set + get => _weakRumble; set { - weakRumble = value; + _weakRumble = value; OnPropertyChanged(); } } public float StrongRumble { - get => strongRumble; set + get => _strongRumble; set { - strongRumble = value; + _strongRumble = value; OnPropertyChanged(); } @@ -209,71 +208,71 @@ namespace Ryujinx.Ava.UI.Models if (config is StandardKeyboardInputConfig keyboardConfig) { - LeftStickUp = (Key)(object)keyboardConfig.LeftJoyconStick.StickUp; - LeftStickDown = (Key)(object)keyboardConfig.LeftJoyconStick.StickDown; - LeftStickLeft = (Key)(object)keyboardConfig.LeftJoyconStick.StickLeft; - LeftStickRight = (Key)(object)keyboardConfig.LeftJoyconStick.StickRight; - LeftKeyboardStickButton = (Key)(object)keyboardConfig.LeftJoyconStick.StickButton; + LeftStickUp = (TKey)(object)keyboardConfig.LeftJoyconStick.StickUp; + LeftStickDown = (TKey)(object)keyboardConfig.LeftJoyconStick.StickDown; + LeftStickLeft = (TKey)(object)keyboardConfig.LeftJoyconStick.StickLeft; + LeftStickRight = (TKey)(object)keyboardConfig.LeftJoyconStick.StickRight; + LeftKeyboardStickButton = (TKey)(object)keyboardConfig.LeftJoyconStick.StickButton; - RightStickUp = (Key)(object)keyboardConfig.RightJoyconStick.StickUp; - RightStickDown = (Key)(object)keyboardConfig.RightJoyconStick.StickDown; - RightStickLeft = (Key)(object)keyboardConfig.RightJoyconStick.StickLeft; - RightStickRight = (Key)(object)keyboardConfig.RightJoyconStick.StickRight; - RightKeyboardStickButton = (Key)(object)keyboardConfig.RightJoyconStick.StickButton; + RightStickUp = (TKey)(object)keyboardConfig.RightJoyconStick.StickUp; + RightStickDown = (TKey)(object)keyboardConfig.RightJoyconStick.StickDown; + RightStickLeft = (TKey)(object)keyboardConfig.RightJoyconStick.StickLeft; + RightStickRight = (TKey)(object)keyboardConfig.RightJoyconStick.StickRight; + RightKeyboardStickButton = (TKey)(object)keyboardConfig.RightJoyconStick.StickButton; - ButtonA = (Key)(object)keyboardConfig.RightJoycon.ButtonA; - ButtonB = (Key)(object)keyboardConfig.RightJoycon.ButtonB; - ButtonX = (Key)(object)keyboardConfig.RightJoycon.ButtonX; - ButtonY = (Key)(object)keyboardConfig.RightJoycon.ButtonY; - ButtonR = (Key)(object)keyboardConfig.RightJoycon.ButtonR; - RightButtonSl = (Key)(object)keyboardConfig.RightJoycon.ButtonSl; - RightButtonSr = (Key)(object)keyboardConfig.RightJoycon.ButtonSr; - ButtonZr = (Key)(object)keyboardConfig.RightJoycon.ButtonZr; - ButtonPlus = (Key)(object)keyboardConfig.RightJoycon.ButtonPlus; + ButtonA = (TKey)(object)keyboardConfig.RightJoycon.ButtonA; + ButtonB = (TKey)(object)keyboardConfig.RightJoycon.ButtonB; + ButtonX = (TKey)(object)keyboardConfig.RightJoycon.ButtonX; + ButtonY = (TKey)(object)keyboardConfig.RightJoycon.ButtonY; + ButtonR = (TKey)(object)keyboardConfig.RightJoycon.ButtonR; + RightButtonSl = (TKey)(object)keyboardConfig.RightJoycon.ButtonSl; + RightButtonSr = (TKey)(object)keyboardConfig.RightJoycon.ButtonSr; + ButtonZr = (TKey)(object)keyboardConfig.RightJoycon.ButtonZr; + ButtonPlus = (TKey)(object)keyboardConfig.RightJoycon.ButtonPlus; - DpadUp = (Key)(object)keyboardConfig.LeftJoycon.DpadUp; - DpadDown = (Key)(object)keyboardConfig.LeftJoycon.DpadDown; - DpadLeft = (Key)(object)keyboardConfig.LeftJoycon.DpadLeft; - DpadRight = (Key)(object)keyboardConfig.LeftJoycon.DpadRight; - ButtonMinus = (Key)(object)keyboardConfig.LeftJoycon.ButtonMinus; - LeftButtonSl = (Key)(object)keyboardConfig.LeftJoycon.ButtonSl; - LeftButtonSr = (Key)(object)keyboardConfig.LeftJoycon.ButtonSr; - ButtonZl = (Key)(object)keyboardConfig.LeftJoycon.ButtonZl; - ButtonL = (Key)(object)keyboardConfig.LeftJoycon.ButtonL; + DpadUp = (TKey)(object)keyboardConfig.LeftJoycon.DpadUp; + DpadDown = (TKey)(object)keyboardConfig.LeftJoycon.DpadDown; + DpadLeft = (TKey)(object)keyboardConfig.LeftJoycon.DpadLeft; + DpadRight = (TKey)(object)keyboardConfig.LeftJoycon.DpadRight; + ButtonMinus = (TKey)(object)keyboardConfig.LeftJoycon.ButtonMinus; + LeftButtonSl = (TKey)(object)keyboardConfig.LeftJoycon.ButtonSl; + LeftButtonSr = (TKey)(object)keyboardConfig.LeftJoycon.ButtonSr; + ButtonZl = (TKey)(object)keyboardConfig.LeftJoycon.ButtonZl; + ButtonL = (TKey)(object)keyboardConfig.LeftJoycon.ButtonL; } else if (config is StandardControllerInputConfig controllerConfig) { - LeftJoystick = (Stick)(object)controllerConfig.LeftJoyconStick.Joystick; + LeftJoystick = (TStick)(object)controllerConfig.LeftJoyconStick.Joystick; LeftInvertStickX = controllerConfig.LeftJoyconStick.InvertStickX; LeftInvertStickY = controllerConfig.LeftJoyconStick.InvertStickY; LeftRotate90 = controllerConfig.LeftJoyconStick.Rotate90CW; - LeftControllerStickButton = (Key)(object)controllerConfig.LeftJoyconStick.StickButton; + LeftControllerStickButton = (TKey)(object)controllerConfig.LeftJoyconStick.StickButton; - RightJoystick = (Stick)(object)controllerConfig.RightJoyconStick.Joystick; + RightJoystick = (TStick)(object)controllerConfig.RightJoyconStick.Joystick; RightInvertStickX = controllerConfig.RightJoyconStick.InvertStickX; RightInvertStickY = controllerConfig.RightJoyconStick.InvertStickY; RightRotate90 = controllerConfig.RightJoyconStick.Rotate90CW; - RightControllerStickButton = (Key)(object)controllerConfig.RightJoyconStick.StickButton; + RightControllerStickButton = (TKey)(object)controllerConfig.RightJoyconStick.StickButton; - ButtonA = (Key)(object)controllerConfig.RightJoycon.ButtonA; - ButtonB = (Key)(object)controllerConfig.RightJoycon.ButtonB; - ButtonX = (Key)(object)controllerConfig.RightJoycon.ButtonX; - ButtonY = (Key)(object)controllerConfig.RightJoycon.ButtonY; - ButtonR = (Key)(object)controllerConfig.RightJoycon.ButtonR; - RightButtonSl = (Key)(object)controllerConfig.RightJoycon.ButtonSl; - RightButtonSr = (Key)(object)controllerConfig.RightJoycon.ButtonSr; - ButtonZr = (Key)(object)controllerConfig.RightJoycon.ButtonZr; - ButtonPlus = (Key)(object)controllerConfig.RightJoycon.ButtonPlus; + ButtonA = (TKey)(object)controllerConfig.RightJoycon.ButtonA; + ButtonB = (TKey)(object)controllerConfig.RightJoycon.ButtonB; + ButtonX = (TKey)(object)controllerConfig.RightJoycon.ButtonX; + ButtonY = (TKey)(object)controllerConfig.RightJoycon.ButtonY; + ButtonR = (TKey)(object)controllerConfig.RightJoycon.ButtonR; + RightButtonSl = (TKey)(object)controllerConfig.RightJoycon.ButtonSl; + RightButtonSr = (TKey)(object)controllerConfig.RightJoycon.ButtonSr; + ButtonZr = (TKey)(object)controllerConfig.RightJoycon.ButtonZr; + ButtonPlus = (TKey)(object)controllerConfig.RightJoycon.ButtonPlus; - DpadUp = (Key)(object)controllerConfig.LeftJoycon.DpadUp; - DpadDown = (Key)(object)controllerConfig.LeftJoycon.DpadDown; - DpadLeft = (Key)(object)controllerConfig.LeftJoycon.DpadLeft; - DpadRight = (Key)(object)controllerConfig.LeftJoycon.DpadRight; - ButtonMinus = (Key)(object)controllerConfig.LeftJoycon.ButtonMinus; - LeftButtonSl = (Key)(object)controllerConfig.LeftJoycon.ButtonSl; - LeftButtonSr = (Key)(object)controllerConfig.LeftJoycon.ButtonSr; - ButtonZl = (Key)(object)controllerConfig.LeftJoycon.ButtonZl; - ButtonL = (Key)(object)controllerConfig.LeftJoycon.ButtonL; + DpadUp = (TKey)(object)controllerConfig.LeftJoycon.DpadUp; + DpadDown = (TKey)(object)controllerConfig.LeftJoycon.DpadDown; + DpadLeft = (TKey)(object)controllerConfig.LeftJoycon.DpadLeft; + DpadRight = (TKey)(object)controllerConfig.LeftJoycon.DpadRight; + ButtonMinus = (TKey)(object)controllerConfig.LeftJoycon.ButtonMinus; + LeftButtonSl = (TKey)(object)controllerConfig.LeftJoycon.ButtonSl; + LeftButtonSr = (TKey)(object)controllerConfig.LeftJoycon.ButtonSr; + ButtonZl = (TKey)(object)controllerConfig.LeftJoycon.ButtonZl; + ButtonL = (TKey)(object)controllerConfig.LeftJoycon.ButtonL; DeadzoneLeft = controllerConfig.DeadzoneLeft; DeadzoneRight = controllerConfig.DeadzoneRight; @@ -317,65 +316,66 @@ namespace Ryujinx.Ava.UI.Models { if (Backend == InputBackendType.WindowKeyboard) { - return new StandardKeyboardInputConfig() + return new StandardKeyboardInputConfig { Id = Id, Backend = Backend, PlayerIndex = PlayerIndex, ControllerType = ControllerType, - LeftJoycon = new LeftJoyconCommonConfig() + LeftJoycon = new LeftJoyconCommonConfig { - DpadUp = (Ryujinx.Common.Configuration.Hid.Key)(object)DpadUp, - DpadDown = (Ryujinx.Common.Configuration.Hid.Key)(object)DpadDown, - DpadLeft = (Ryujinx.Common.Configuration.Hid.Key)(object)DpadLeft, - DpadRight = (Ryujinx.Common.Configuration.Hid.Key)(object)DpadRight, - ButtonL = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonL, - ButtonZl = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonZl, - ButtonSl = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftButtonSl, - ButtonSr = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftButtonSr, - ButtonMinus = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonMinus + DpadUp = (Key)(object)DpadUp, + DpadDown = (Key)(object)DpadDown, + DpadLeft = (Key)(object)DpadLeft, + DpadRight = (Key)(object)DpadRight, + ButtonL = (Key)(object)ButtonL, + ButtonZl = (Key)(object)ButtonZl, + ButtonSl = (Key)(object)LeftButtonSl, + ButtonSr = (Key)(object)LeftButtonSr, + ButtonMinus = (Key)(object)ButtonMinus, }, - RightJoycon = new RightJoyconCommonConfig() + RightJoycon = new RightJoyconCommonConfig { - ButtonA = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonA, - ButtonB = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonB, - ButtonX = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonX, - ButtonY = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonY, - ButtonPlus = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonPlus, - ButtonSl = (Ryujinx.Common.Configuration.Hid.Key)(object)RightButtonSl, - ButtonSr = (Ryujinx.Common.Configuration.Hid.Key)(object)RightButtonSr, - ButtonR = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonR, - ButtonZr = (Ryujinx.Common.Configuration.Hid.Key)(object)ButtonZr + ButtonA = (Key)(object)ButtonA, + ButtonB = (Key)(object)ButtonB, + ButtonX = (Key)(object)ButtonX, + ButtonY = (Key)(object)ButtonY, + ButtonPlus = (Key)(object)ButtonPlus, + ButtonSl = (Key)(object)RightButtonSl, + ButtonSr = (Key)(object)RightButtonSr, + ButtonR = (Key)(object)ButtonR, + ButtonZr = (Key)(object)ButtonZr, }, - LeftJoyconStick = new JoyconConfigKeyboardStick() + LeftJoyconStick = new JoyconConfigKeyboardStick { - StickUp = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftStickUp, - StickDown = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftStickDown, - StickRight = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftStickRight, - StickLeft = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftStickLeft, - StickButton = (Ryujinx.Common.Configuration.Hid.Key)(object)LeftKeyboardStickButton + StickUp = (Key)(object)LeftStickUp, + StickDown = (Key)(object)LeftStickDown, + StickRight = (Key)(object)LeftStickRight, + StickLeft = (Key)(object)LeftStickLeft, + StickButton = (Key)(object)LeftKeyboardStickButton, }, - RightJoyconStick = new JoyconConfigKeyboardStick() + RightJoyconStick = new JoyconConfigKeyboardStick { - StickUp = (Ryujinx.Common.Configuration.Hid.Key)(object)RightStickUp, - StickDown = (Ryujinx.Common.Configuration.Hid.Key)(object)RightStickDown, - StickLeft = (Ryujinx.Common.Configuration.Hid.Key)(object)RightStickLeft, - StickRight = (Ryujinx.Common.Configuration.Hid.Key)(object)RightStickRight, - StickButton = (Ryujinx.Common.Configuration.Hid.Key)(object)RightKeyboardStickButton + StickUp = (Key)(object)RightStickUp, + StickDown = (Key)(object)RightStickDown, + StickLeft = (Key)(object)RightStickLeft, + StickRight = (Key)(object)RightStickRight, + StickButton = (Key)(object)RightKeyboardStickButton, }, - Version = InputConfig.CurrentVersion + Version = InputConfig.CurrentVersion, }; } - else if (Backend == InputBackendType.GamepadSDL2) + + if (Backend == InputBackendType.GamepadSDL2) { - var config = new StandardControllerInputConfig() + var config = new StandardControllerInputConfig { Id = Id, Backend = Backend, PlayerIndex = PlayerIndex, ControllerType = ControllerType, - LeftJoycon = new LeftJoyconCommonConfig() + LeftJoycon = new LeftJoyconCommonConfig { DpadUp = (GamepadInputId)(object)DpadUp, DpadDown = (GamepadInputId)(object)DpadDown, @@ -387,7 +387,7 @@ namespace Ryujinx.Ava.UI.Models ButtonSr = (GamepadInputId)(object)LeftButtonSr, ButtonMinus = (GamepadInputId)(object)ButtonMinus, }, - RightJoycon = new RightJoyconCommonConfig() + RightJoycon = new RightJoyconCommonConfig { ButtonA = (GamepadInputId)(object)ButtonA, ButtonB = (GamepadInputId)(object)ButtonB, @@ -399,7 +399,7 @@ namespace Ryujinx.Ava.UI.Models ButtonR = (GamepadInputId)(object)ButtonR, ButtonZr = (GamepadInputId)(object)ButtonZr, }, - LeftJoyconStick = new JoyconConfigControllerStick() + LeftJoyconStick = new JoyconConfigControllerStick { Joystick = (StickInputId)(object)LeftJoystick, InvertStickX = LeftInvertStickX, @@ -407,7 +407,7 @@ namespace Ryujinx.Ava.UI.Models Rotate90CW = LeftRotate90, StickButton = (GamepadInputId)(object)LeftControllerStickButton, }, - RightJoyconStick = new JoyconConfigControllerStick() + RightJoyconStick = new JoyconConfigControllerStick { Joystick = (StickInputId)(object)RightJoystick, InvertStickX = RightInvertStickX, @@ -415,11 +415,11 @@ namespace Ryujinx.Ava.UI.Models Rotate90CW = RightRotate90, StickButton = (GamepadInputId)(object)RightControllerStickButton, }, - Rumble = new RumbleConfigController() + Rumble = new RumbleConfigController { EnableRumble = EnableRumble, WeakRumble = WeakRumble, - StrongRumble = StrongRumble + StrongRumble = StrongRumble, }, Version = InputConfig.CurrentVersion, DeadzoneLeft = DeadzoneLeft, @@ -428,19 +428,19 @@ namespace Ryujinx.Ava.UI.Models RangeRight = RangeRight, TriggerThreshold = TriggerThreshold, Motion = EnableCemuHookMotion - ? new CemuHookMotionConfigController() - { - DsuServerHost = DsuServerHost, - DsuServerPort = DsuServerPort, - Slot = Slot, - AltSlot = AltSlot, - MirrorInput = MirrorInput, - MotionBackend = MotionInputBackendType.CemuHook - } - : new StandardMotionConfigController() - { - MotionBackend = MotionInputBackendType.GamepadDriver - } + ? new CemuHookMotionConfigController + { + DsuServerHost = DsuServerHost, + DsuServerPort = DsuServerPort, + Slot = Slot, + AltSlot = AltSlot, + MirrorInput = MirrorInput, + MotionBackend = MotionInputBackendType.CemuHook, + } + : new StandardMotionConfigController + { + MotionBackend = MotionInputBackendType.GamepadDriver, + }, }; config.Motion.Sensitivity = Sensitivity; @@ -453,4 +453,4 @@ namespace Ryujinx.Ava.UI.Models return null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/ProfileImageModel.cs b/src/Ryujinx.Ava/UI/Models/ProfileImageModel.cs index 8aa194005..99365dfc7 100644 --- a/src/Ryujinx.Ava/UI/Models/ProfileImageModel.cs +++ b/src/Ryujinx.Ava/UI/Models/ProfileImageModel.cs @@ -29,4 +29,4 @@ namespace Ryujinx.Ava.UI.Models } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/SaveModel.cs b/src/Ryujinx.Ava/UI/Models/SaveModel.cs index ab919c88d..f15befbb3 100644 --- a/src/Ryujinx.Ava/UI/Models/SaveModel.cs +++ b/src/Ryujinx.Ava/UI/Models/SaveModel.cs @@ -3,10 +3,12 @@ using LibHac.Ncm; using Ryujinx.Ava.UI.ViewModels; using Ryujinx.Ava.UI.Windows; using Ryujinx.HLE.FileSystem; +using Ryujinx.Ui.App.Common; using System; using System.IO; using System.Linq; using System.Threading.Tasks; +using Path = System.IO.Path; namespace Ryujinx.Ava.UI.Models { @@ -40,9 +42,9 @@ namespace Ryujinx.Ava.UI.Models private string GetSizeString() { - const int scale = 1024; + const int Scale = 1024; string[] orders = { "GiB", "MiB", "KiB" }; - long max = (long)Math.Pow(scale, orders.Length); + long max = (long)Math.Pow(Scale, orders.Length); foreach (string order in orders) { @@ -51,13 +53,13 @@ namespace Ryujinx.Ava.UI.Models return $"{decimal.Divide(Size, max):##.##} {order}"; } - max /= scale; + max /= Scale; } return "0 KiB"; } - public SaveModel(SaveDataInfo info, VirtualFileSystem virtualFileSystem) + public SaveModel(SaveDataInfo info) { SaveId = info.SaveDataId; TitleId = info.ProgramId; @@ -74,16 +76,17 @@ namespace Ryujinx.Ava.UI.Models } else { - var appMetadata = MainWindow.MainWindowViewModel.ApplicationLibrary.LoadAndSaveMetaData(TitleIdString); + var appMetadata = ApplicationLibrary.LoadAndSaveMetaData(TitleIdString); Title = appMetadata.Title ?? TitleIdString; } Task.Run(() => { - var saveRoot = System.IO.Path.Combine(virtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); + var saveRoot = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{info.SaveDataId:x16}"); - long total_size = GetDirectorySize(saveRoot); - long GetDirectorySize(string path) + long totalSize = GetDirectorySize(saveRoot); + + static long GetDirectorySize(string path) { long size = 0; if (Directory.Exists(path)) @@ -104,9 +107,9 @@ namespace Ryujinx.Ava.UI.Models return size; } - Size = total_size; + Size = totalSize; }); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/StatusUpdatedEventArgs.cs b/src/Ryujinx.Ava/UI/Models/StatusUpdatedEventArgs.cs index ea2b90385..cc29442d0 100644 --- a/src/Ryujinx.Ava/UI/Models/StatusUpdatedEventArgs.cs +++ b/src/Ryujinx.Ava/UI/Models/StatusUpdatedEventArgs.cs @@ -25,4 +25,4 @@ namespace Ryujinx.Ava.UI.Models GpuName = gpuName; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/TempProfile.cs b/src/Ryujinx.Ava/UI/Models/TempProfile.cs index 05e16632d..659092e6d 100644 --- a/src/Ryujinx.Ava/UI/Models/TempProfile.cs +++ b/src/Ryujinx.Ava/UI/Models/TempProfile.cs @@ -11,7 +11,7 @@ namespace Ryujinx.Ava.UI.Models private string _name = String.Empty; private UserId _userId; - public uint MaxProfileNameLength => 0x20; + public static uint MaxProfileNameLength => 0x20; public byte[] Image { @@ -58,4 +58,4 @@ namespace Ryujinx.Ava.UI.Models } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/TimeZone.cs b/src/Ryujinx.Ava/UI/Models/TimeZone.cs index cb6cc2fdc..950fbce43 100644 --- a/src/Ryujinx.Ava/UI/Models/TimeZone.cs +++ b/src/Ryujinx.Ava/UI/Models/TimeZone.cs @@ -13,4 +13,4 @@ namespace Ryujinx.Ava.UI.Models public string Location { get; set; } public string Abbreviation { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/TitleUpdateModel.cs b/src/Ryujinx.Ava/UI/Models/TitleUpdateModel.cs index 80476a433..3b44e8ee6 100644 --- a/src/Ryujinx.Ava/UI/Models/TitleUpdateModel.cs +++ b/src/Ryujinx.Ava/UI/Models/TitleUpdateModel.cs @@ -16,4 +16,4 @@ namespace Ryujinx.Ava.UI.Models Path = path; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Models/UserProfile.cs b/src/Ryujinx.Ava/UI/Models/UserProfile.cs index e7cd53007..e1698b4df 100644 --- a/src/Ryujinx.Ava/UI/Models/UserProfile.cs +++ b/src/Ryujinx.Ava/UI/Models/UserProfile.cs @@ -1,3 +1,4 @@ +using Avalonia; using Avalonia.Media; using Ryujinx.Ava.UI.Controls; using Ryujinx.Ava.UI.ViewModels; @@ -87,7 +88,7 @@ namespace Ryujinx.Ava.UI.Models private void UpdateBackground() { - Avalonia.Application.Current.Styles.TryGetResource("ControlFillColorSecondary", out object color); + Application.Current.Styles.TryGetResource("ControlFillColorSecondary", out object color); if (color is not null) { @@ -100,4 +101,4 @@ namespace Ryujinx.Ava.UI.Models _owner.Navigate(typeof(UserEditorView), (_owner, userProfile, true)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindow.cs b/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindow.cs index a5c8b0031..e324b484d 100644 --- a/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindow.cs +++ b/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindow.cs @@ -21,20 +21,20 @@ namespace Ryujinx.Ava.UI.Renderer public class EmbeddedWindow : NativeControlHost { private WindowProc _wndProcDelegate; - private string _className; + private string _className; protected GLXWindow X11Window { get; set; } protected IntPtr WindowHandle { get; set; } - protected IntPtr X11Display { get; set; } - protected IntPtr NsView { get; set; } - protected IntPtr MetalLayer { get; set; } + protected IntPtr X11Display { get; set; } + protected IntPtr NsView { get; set; } + protected IntPtr MetalLayer { get; set; } public delegate void UpdateBoundsCallbackDelegate(Rect rect); private UpdateBoundsCallbackDelegate _updateBoundsCallback; public event EventHandler WindowCreated; - public event EventHandler SizeChanged; + public event EventHandler SizeChanged; public EmbeddedWindow() { @@ -50,9 +50,9 @@ namespace Ryujinx.Ava.UI.Renderer protected virtual void OnWindowDestroying() { WindowHandle = IntPtr.Zero; - X11Display = IntPtr.Zero; - NsView = IntPtr.Zero; - MetalLayer = IntPtr.Zero; + X11Display = IntPtr.Zero; + NsView = IntPtr.Zero; + MetalLayer = IntPtr.Zero; } private void OnNativeEmbeddedWindowCreated(object sender, EventArgs e) @@ -77,11 +77,13 @@ namespace Ryujinx.Ava.UI.Renderer { return CreateLinux(control); } - else if (OperatingSystem.IsWindows()) + + if (OperatingSystem.IsWindows()) { return CreateWin32(control); } - else if (OperatingSystem.IsMacOS()) + + if (OperatingSystem.IsMacOS()) { return CreateMacOS(); } @@ -123,11 +125,11 @@ namespace Ryujinx.Ava.UI.Renderer } else { - X11Window = PlatformHelper.CreateOpenGLWindow(FramebufferFormat.Default, 0, 0, 100, 100) as GLXWindow; + X11Window = PlatformHelper.CreateOpenGLWindow(new FramebufferFormat(new ColorFormat(8, 8, 8, 0), 16, 0, ColorFormat.Zero, 0, 2, false), 0, 0, 100, 100) as GLXWindow; } WindowHandle = X11Window.WindowHandle.RawHandle; - X11Display = X11Window.DisplayHandle.RawHandle; + X11Display = X11Window.DisplayHandle.RawHandle; return new PlatformHandle(WindowHandle, "X11"); } @@ -141,23 +143,23 @@ namespace Ryujinx.Ava.UI.Renderer { if (VisualRoot != null) { - if (msg == WindowsMessages.LBUTTONDOWN || - msg == WindowsMessages.RBUTTONDOWN || - msg == WindowsMessages.LBUTTONUP || - msg == WindowsMessages.RBUTTONUP || - msg == WindowsMessages.MOUSEMOVE) + if (msg == WindowsMessages.Lbuttondown || + msg == WindowsMessages.Rbuttondown || + msg == WindowsMessages.Lbuttonup || + msg == WindowsMessages.Rbuttonup || + msg == WindowsMessages.Mousemove) { - Point rootVisualPosition = this.TranslatePoint(new Point((long)lParam & 0xFFFF, (long)lParam >> 16 & 0xFFFF), VisualRoot).Value; - Pointer pointer = new(0, PointerType.Mouse, true); + Point rootVisualPosition = this.TranslatePoint(new Point((long)lParam & 0xFFFF, (long)lParam >> 16 & 0xFFFF), VisualRoot).Value; + Pointer pointer = new(0, PointerType.Mouse, true); switch (msg) { - case WindowsMessages.LBUTTONDOWN: - case WindowsMessages.RBUTTONDOWN: + case WindowsMessages.Lbuttondown: + case WindowsMessages.Rbuttondown: { - bool isLeft = msg == WindowsMessages.LBUTTONDOWN; - RawInputModifiers pointerPointModifier = isLeft ? RawInputModifiers.LeftMouseButton : RawInputModifiers.RightMouseButton; - PointerPointProperties properties = new(pointerPointModifier, isLeft ? PointerUpdateKind.LeftButtonPressed : PointerUpdateKind.RightButtonPressed); + bool isLeft = msg == WindowsMessages.Lbuttondown; + RawInputModifiers pointerPointModifier = isLeft ? RawInputModifiers.LeftMouseButton : RawInputModifiers.RightMouseButton; + PointerPointProperties properties = new(pointerPointModifier, isLeft ? PointerUpdateKind.LeftButtonPressed : PointerUpdateKind.RightButtonPressed); var evnt = new PointerPressedEventArgs( this, @@ -172,12 +174,12 @@ namespace Ryujinx.Ava.UI.Renderer break; } - case WindowsMessages.LBUTTONUP: - case WindowsMessages.RBUTTONUP: + case WindowsMessages.Lbuttonup: + case WindowsMessages.Rbuttonup: { - bool isLeft = msg == WindowsMessages.LBUTTONUP; - RawInputModifiers pointerPointModifier = isLeft ? RawInputModifiers.LeftMouseButton : RawInputModifiers.RightMouseButton; - PointerPointProperties properties = new(pointerPointModifier, isLeft ? PointerUpdateKind.LeftButtonReleased : PointerUpdateKind.RightButtonReleased); + bool isLeft = msg == WindowsMessages.Lbuttonup; + RawInputModifiers pointerPointModifier = isLeft ? RawInputModifiers.LeftMouseButton : RawInputModifiers.RightMouseButton; + PointerPointProperties properties = new(pointerPointModifier, isLeft ? PointerUpdateKind.LeftButtonReleased : PointerUpdateKind.RightButtonReleased); var evnt = new PointerReleasedEventArgs( this, @@ -193,7 +195,7 @@ namespace Ryujinx.Ava.UI.Renderer break; } - case WindowsMessages.MOUSEMOVE: + case WindowsMessages.Mousemove: { var evnt = new PointerEventArgs( PointerMovedEvent, @@ -216,19 +218,19 @@ namespace Ryujinx.Ava.UI.Renderer return DefWindowProc(hWnd, msg, wParam, lParam); }; - WNDCLASSEX wndClassEx = new() + WndClassEx wndClassEx = new() { - cbSize = Marshal.SizeOf(), - hInstance = GetModuleHandle(null), - lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate), - style = ClassStyles.CS_OWNDC, + cbSize = Marshal.SizeOf(), + hInstance = GetModuleHandle(null), + lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate), + style = ClassStyles.CsOwndc, lpszClassName = Marshal.StringToHGlobalUni(_className), - hCursor = CreateArrowCursor() + hCursor = CreateArrowCursor(), }; RegisterClassEx(ref wndClassEx); - WindowHandle = CreateWindowEx(0, _className, "NativeWindow", WindowStyles.WS_CHILD, 0, 0, 640, 480, control.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); + WindowHandle = CreateWindowEx(0, _className, "NativeWindow", WindowStyles.WsChild, 0, 0, 640, 480, control.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); Marshal.FreeHGlobal(wndClassEx.lpszClassName); @@ -239,28 +241,28 @@ namespace Ryujinx.Ava.UI.Renderer IPlatformHandle CreateMacOS() { // Create a new CAMetalLayer. - IntPtr layerClass = ObjectiveC.objc_getClass("CAMetalLayer"); - IntPtr metalLayer = ObjectiveC.IntPtr_objc_msgSend(layerClass, "alloc"); - ObjectiveC.objc_msgSend(metalLayer, "init"); + ObjectiveC.Object layerObject = new("CAMetalLayer"); + ObjectiveC.Object metalLayer = layerObject.GetFromMessage("alloc"); + metalLayer.SendMessage("init"); // Create a child NSView to render into. - IntPtr nsViewClass = ObjectiveC.objc_getClass("NSView"); - IntPtr child = ObjectiveC.IntPtr_objc_msgSend(nsViewClass, "alloc"); - ObjectiveC.objc_msgSend(child, "init", new ObjectiveC.NSRect(0, 0, 0, 0)); + ObjectiveC.Object nsViewObject = new("NSView"); + ObjectiveC.Object child = nsViewObject.GetFromMessage("alloc"); + child.SendMessage("init", new ObjectiveC.NSRect(0, 0, 0, 0)); // Make its renderer our metal layer. - ObjectiveC.objc_msgSend(child, "setWantsLayer:", 1); - ObjectiveC.objc_msgSend(child, "setLayer:", metalLayer); - ObjectiveC.objc_msgSend(metalLayer, "setContentsScale:", Program.DesktopScaleFactor); + child.SendMessage("setWantsLayer:", 1); + child.SendMessage("setLayer:", metalLayer); + metalLayer.SendMessage("setContentsScale:", Program.DesktopScaleFactor); // Ensure the scale factor is up to date. _updateBoundsCallback = rect => { - ObjectiveC.objc_msgSend(metalLayer, "setContentsScale:", Program.DesktopScaleFactor); + metalLayer.SendMessage("setContentsScale:", Program.DesktopScaleFactor); }; - IntPtr nsView = child; - MetalLayer = metalLayer; + IntPtr nsView = child.ObjPtr; + MetalLayer = metalLayer.ObjPtr; NsView = nsView; return new PlatformHandle(nsView, "NSView"); @@ -280,9 +282,11 @@ namespace Ryujinx.Ava.UI.Renderer } [SupportedOSPlatform("macos")] +#pragma warning disable CA1822 // Mark member as static void DestroyMacOS() { // TODO } +#pragma warning restore CA1822 } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowOpenGL.cs b/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowOpenGL.cs index 305e891a1..769a1c91a 100644 --- a/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowOpenGL.cs +++ b/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowOpenGL.cs @@ -1,9 +1,11 @@ using OpenTK.Graphics.OpenGL; using Ryujinx.Common.Configuration; +using Ryujinx.Common.Logging; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.OpenGL; using Ryujinx.Ui.Common.Configuration; using SPB.Graphics; +using SPB.Graphics.Exceptions; using SPB.Graphics.OpenGL; using SPB.Platform; using SPB.Platform.WGL; @@ -18,8 +20,6 @@ namespace Ryujinx.Ava.UI.Renderer public OpenGLContextBase Context { get; set; } - public EmbeddedWindowOpenGL() { } - protected override void OnWindowDestroying() { Context.Dispose(); @@ -62,14 +62,21 @@ namespace Ryujinx.Ava.UI.Renderer Context.MakeCurrent(null); } - public void MakeCurrent() + public void MakeCurrent(bool unbind = false, bool shouldThrow = true) { - Context?.MakeCurrent(_window); - } + try + { + Context?.MakeCurrent(!unbind ? _window : null); + } + catch (ContextException e) + { + if (shouldThrow) + { + throw; + } - public void MakeCurrent(NativeWindowBase window) - { - Context?.MakeCurrent(window); + Logger.Warning?.Print(LogClass.Ui, $"Failed to {(!unbind ? "bind" : "unbind")} OpenGL context: {e}"); + } } public void SwapBuffers() @@ -84,4 +91,4 @@ namespace Ryujinx.Ava.UI.Renderer MakeCurrent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowVulkan.cs b/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowVulkan.cs index 0b3eb9e30..fafbec207 100644 --- a/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowVulkan.cs +++ b/src/Ryujinx.Ava/UI/Renderer/EmbeddedWindowVulkan.cs @@ -34,9 +34,9 @@ namespace Ryujinx.Ava.UI.Renderer return new SurfaceKHR((ulong?)VulkanHelper.CreateWindowSurface(instance.Handle, nativeWindowBase)); } - public SurfaceKHR CreateSurface(Instance instance, Vk api) + public SurfaceKHR CreateSurface(Instance instance, Vk _) { return CreateSurface(instance); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Renderer/OpenTKBindingsContext.cs b/src/Ryujinx.Ava/UI/Renderer/OpenTKBindingsContext.cs index a2ec02b25..85e8585fc 100644 --- a/src/Ryujinx.Ava/UI/Renderer/OpenTKBindingsContext.cs +++ b/src/Ryujinx.Ava/UI/Renderer/OpenTKBindingsContext.cs @@ -17,4 +17,4 @@ namespace Ryujinx.Ava.UI.Renderer return _getProcAddress(procName); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Renderer/RendererHost.axaml.cs b/src/Ryujinx.Ava/UI/Renderer/RendererHost.axaml.cs index ee10282db..b74265a31 100644 --- a/src/Ryujinx.Ava/UI/Renderer/RendererHost.axaml.cs +++ b/src/Ryujinx.Ava/UI/Renderer/RendererHost.axaml.cs @@ -11,7 +11,7 @@ namespace Ryujinx.Ava.UI.Renderer public readonly EmbeddedWindow EmbeddedWindow; public event EventHandler WindowCreated; - public event Action SizeChanged; + public event Action SizeChanged; public RendererHost() { @@ -32,7 +32,7 @@ namespace Ryujinx.Ava.UI.Renderer private void Initialize() { EmbeddedWindow.WindowCreated += CurrentWindow_WindowCreated; - EmbeddedWindow.SizeChanged += CurrentWindow_SizeChanged; + EmbeddedWindow.SizeChanged += CurrentWindow_SizeChanged; Content = EmbeddedWindow; } @@ -42,7 +42,7 @@ namespace Ryujinx.Ava.UI.Renderer if (EmbeddedWindow != null) { EmbeddedWindow.WindowCreated -= CurrentWindow_WindowCreated; - EmbeddedWindow.SizeChanged -= CurrentWindow_SizeChanged; + EmbeddedWindow.SizeChanged -= CurrentWindow_SizeChanged; } GC.SuppressFinalize(this); @@ -65,4 +65,4 @@ namespace Ryujinx.Ava.UI.Renderer WindowCreated?.Invoke(this, EventArgs.Empty); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Renderer/SPBOpenGLContext.cs b/src/Ryujinx.Ava/UI/Renderer/SPBOpenGLContext.cs index e090f14c7..a2c7aa279 100644 --- a/src/Ryujinx.Ava/UI/Renderer/SPBOpenGLContext.cs +++ b/src/Ryujinx.Ava/UI/Renderer/SPBOpenGLContext.cs @@ -10,12 +10,12 @@ namespace Ryujinx.Ava.UI.Renderer class SPBOpenGLContext : IOpenGLContext { private readonly OpenGLContextBase _context; - private readonly NativeWindowBase _window; + private readonly NativeWindowBase _window; private SPBOpenGLContext(OpenGLContextBase context, NativeWindowBase window) { _context = context; - _window = window; + _window = window; } public void Dispose() @@ -32,7 +32,7 @@ namespace Ryujinx.Ava.UI.Renderer public static SPBOpenGLContext CreateBackgroundContext(OpenGLContextBase sharedContext) { OpenGLContextBase context = PlatformHelper.CreateOpenGLContext(FramebufferFormat.Default, 3, 3, OpenGLContextFlags.Compat, true, sharedContext); - NativeWindowBase window = PlatformHelper.CreateOpenGLWindow(FramebufferFormat.Default, 0, 0, 100, 100); + NativeWindowBase window = PlatformHelper.CreateOpenGLWindow(FramebufferFormat.Default, 0, 0, 100, 100); context.Initialize(window); context.MakeCurrent(window); diff --git a/src/Ryujinx.Ava/UI/ViewModels/AboutWindowViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/AboutWindowViewModel.cs index 479411cba..fddcd71a7 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/AboutWindowViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/AboutWindowViewModel.cs @@ -1,5 +1,6 @@ using Avalonia; using Avalonia.Media.Imaging; +using Avalonia.Platform; using Avalonia.Threading; using Ryujinx.Ava.Common.Locale; using Ryujinx.Common.Utilities; @@ -87,7 +88,7 @@ namespace Ryujinx.Ava.UI.ViewModels { Version = Program.Version; - var assets = AvaloniaLocator.Current.GetService(); + var assets = AvaloniaLocator.Current.GetService(); if (ConfigurationState.Instance.Ui.BaseStyle.Value == "Light") { @@ -130,4 +131,4 @@ namespace Ryujinx.Ava.UI.ViewModels } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/AmiiboWindowViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/AmiiboWindowViewModel.cs index ead1a1442..3138dd146 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/AmiiboWindowViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/AmiiboWindowViewModel.cs @@ -18,7 +18,6 @@ using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; -using AmiiboJsonSerializerContext = Ryujinx.Ui.Common.Models.Amiibo.AmiiboJsonSerializerContext; namespace Ryujinx.Ava.UI.ViewModels { @@ -44,7 +43,7 @@ namespace Ryujinx.Ava.UI.ViewModels private bool _useRandomUuid; private string _usage; - private static readonly AmiiboJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly AmiiboJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); public AmiiboWindowViewModel(StyleableWindow owner, string lastScannedAmiiboId, string titleId) { @@ -52,7 +51,7 @@ namespace Ryujinx.Ava.UI.ViewModels _httpClient = new HttpClient { - Timeout = TimeSpan.FromSeconds(30) + Timeout = TimeSpan.FromSeconds(30), }; LastScannedAmiiboId = lastScannedAmiiboId; @@ -185,6 +184,7 @@ namespace Ryujinx.Ava.UI.ViewModels public void Dispose() { + GC.SuppressFinalize(this); _httpClient.Dispose(); } @@ -196,7 +196,7 @@ namespace Ryujinx.Ava.UI.ViewModels { amiiboJsonString = await File.ReadAllTextAsync(_amiiboJsonPath); - if (await NeedsUpdate(JsonHelper.Deserialize(amiiboJsonString, SerializerContext.AmiiboJson).LastUpdated)) + if (await NeedsUpdate(JsonHelper.Deserialize(amiiboJsonString, _serializerContext.AmiiboJson).LastUpdated)) { amiiboJsonString = await DownloadAmiiboJson(); } @@ -215,7 +215,7 @@ namespace Ryujinx.Ava.UI.ViewModels } } - _amiiboList = JsonHelper.Deserialize(amiiboJsonString, SerializerContext.AmiiboJson).Amiibo; + _amiiboList = JsonHelper.Deserialize(amiiboJsonString, _serializerContext.AmiiboJson).Amiibo; _amiiboList = _amiiboList.OrderBy(amiibo => amiibo.AmiiboSeries).ToList(); ParseAmiiboData(); @@ -264,7 +264,7 @@ namespace Ryujinx.Ava.UI.ViewModels private void SelectLastScannedAmiibo() { - AmiiboApi scanned = _amiiboList.FirstOrDefault(amiibo => amiibo.GetId() == LastScannedAmiiboId); + AmiiboApi scanned = _amiiboList.Find(amiibo => amiibo.GetId() == LastScannedAmiiboId); SeriesSelectedIndex = AmiiboSeries.IndexOf(scanned.AmiiboSeries); AmiiboSelectedIndex = AmiiboList.IndexOf(scanned); @@ -325,7 +325,7 @@ namespace Ryujinx.Ava.UI.ViewModels AmiiboApi selected = _amiibos[_amiiboSelectedIndex]; - string imageUrl = _amiiboList.FirstOrDefault(amiibo => amiibo.Equals(selected)).Image; + string imageUrl = _amiiboList.Find(amiibo => amiibo.Equals(selected)).Image; string usageString = ""; @@ -426,18 +426,17 @@ namespace Ryujinx.Ava.UI.ViewModels if (response.IsSuccessStatusCode) { byte[] amiiboPreviewBytes = await response.Content.ReadAsByteArrayAsync(); - using (MemoryStream memoryStream = new(amiiboPreviewBytes)) - { - Bitmap bitmap = new(memoryStream); + using MemoryStream memoryStream = new(amiiboPreviewBytes); - double ratio = Math.Min(AmiiboImageSize / bitmap.Size.Width, + Bitmap bitmap = new(memoryStream); + + double ratio = Math.Min(AmiiboImageSize / bitmap.Size.Width, AmiiboImageSize / bitmap.Size.Height); - int resizeHeight = (int)(bitmap.Size.Height * ratio); - int resizeWidth = (int)(bitmap.Size.Width * ratio); + int resizeHeight = (int)(bitmap.Size.Height * ratio); + int resizeWidth = (int)(bitmap.Size.Width * ratio); - AmiiboImage = bitmap.CreateScaledBitmap(new PixelSize(resizeWidth, resizeHeight)); - } + AmiiboImage = bitmap.CreateScaledBitmap(new PixelSize(resizeWidth, resizeHeight)); } else { @@ -447,15 +446,14 @@ namespace Ryujinx.Ava.UI.ViewModels private void ResetAmiiboPreview() { - using (MemoryStream memoryStream = new(_amiiboLogoBytes)) - { - Bitmap bitmap = new(memoryStream); + using MemoryStream memoryStream = new(_amiiboLogoBytes); - AmiiboImage = bitmap; - } + Bitmap bitmap = new(memoryStream); + + AmiiboImage = bitmap; } - private async void ShowInfoDialog() + private static async void ShowInfoDialog() { await ContentDialogHelper.CreateInfoDialog(LocaleManager.Instance[LocaleKeys.DialogAmiiboApiTitle], LocaleManager.Instance[LocaleKeys.DialogAmiiboApiConnectErrorMessage], @@ -464,4 +462,4 @@ namespace Ryujinx.Ava.UI.ViewModels LocaleManager.Instance[LocaleKeys.RyujinxInfo]); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/AvatarProfileViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/AvatarProfileViewModel.cs deleted file mode 100644 index b2b310149..000000000 --- a/src/Ryujinx.Ava/UI/ViewModels/AvatarProfileViewModel.cs +++ /dev/null @@ -1,363 +0,0 @@ -using Avalonia.Media; -using DynamicData; -using LibHac.Common; -using LibHac.Fs; -using LibHac.Fs.Fsa; -using LibHac.FsSystem; -using LibHac.Ncm; -using LibHac.Tools.Fs; -using LibHac.Tools.FsSystem; -using LibHac.Tools.FsSystem.NcaUtils; -using Ryujinx.Ava.UI.Models; -using Ryujinx.HLE.FileSystem; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Png; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing; -using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Color = Avalonia.Media.Color; - -namespace Ryujinx.Ava.UI.ViewModels -{ - internal class AvatarProfileViewModel : BaseModel, IDisposable - { - private const int MaxImageTasks = 4; - - private static readonly Dictionary _avatarStore = new(); - private static bool _isPreloading; - private static Action _loadCompleteAction; - - private ObservableCollection _images; - private Color _backgroundColor = Colors.White; - - private int _selectedIndex; - private int _imagesLoaded; - private bool _isActive; - private byte[] _selectedImage; - private bool _isIndeterminate = true; - - public bool IsActive - { - get => _isActive; - set => _isActive = value; - } - - public AvatarProfileViewModel() - { - _images = new ObservableCollection(); - } - - public AvatarProfileViewModel(Action loadCompleteAction) - { - _images = new ObservableCollection(); - - if (_isPreloading) - { - _loadCompleteAction = loadCompleteAction; - } - else - { - ReloadImages(); - } - } - - public Color BackgroundColor - { - get => _backgroundColor; - set - { - _backgroundColor = value; - - IsActive = false; - - ReloadImages(); - } - } - - public ObservableCollection Images - { - get => _images; - set - { - _images = value; - OnPropertyChanged(); - } - } - - public bool IsIndeterminate - { - get => _isIndeterminate; - set - { - _isIndeterminate = value; - - OnPropertyChanged(); - } - } - - public int ImageCount => _avatarStore.Count; - - public int ImagesLoaded - { - get => _imagesLoaded; - set - { - _imagesLoaded = value; - OnPropertyChanged(); - } - } - - public int SelectedIndex - { - get => _selectedIndex; - set - { - _selectedIndex = value; - - if (_selectedIndex == -1) - { - SelectedImage = null; - } - else - { - SelectedImage = _images[_selectedIndex].Data; - } - - OnPropertyChanged(); - } - } - - public byte[] SelectedImage - { - get => _selectedImage; - private set => _selectedImage = value; - } - - public void ReloadImages() - { - if (_isPreloading) - { - IsIndeterminate = false; - return; - } - Task.Run(() => - { - IsActive = true; - - Images.Clear(); - int selectedIndex = _selectedIndex; - int index = 0; - - ImagesLoaded = 0; - IsIndeterminate = false; - - var keys = _avatarStore.Keys.ToList(); - - var newImages = new List(); - var tasks = new List(); - - for (int i = 0; i < MaxImageTasks; i++) - { - var start = i; - tasks.Add(Task.Run(() => ImageTask(start))); - } - - Task.WaitAll(tasks.ToArray()); - - Images.AddRange(newImages); - - void ImageTask(int start) - { - for (int i = start; i < keys.Count; i += MaxImageTasks) - { - if (!IsActive) - { - return; - } - - var key = keys[i]; - var image = _avatarStore[keys[i]]; - - var data = ProcessImage(image); - newImages.Add(new ProfileImageModel(key, data)); - if (index++ == selectedIndex) - { - SelectedImage = data; - } - - Interlocked.Increment(ref _imagesLoaded); - OnPropertyChanged(nameof(ImagesLoaded)); - } - } - }); - } - - private byte[] ProcessImage(byte[] data) - { - using (MemoryStream streamJpg = new()) - { - Image avatarImage = Image.Load(data, new PngDecoder()); - - avatarImage.Mutate(x => x.BackgroundColor(new Rgba32(BackgroundColor.R, - BackgroundColor.G, - BackgroundColor.B, - BackgroundColor.A))); - avatarImage.SaveAsJpeg(streamJpg); - - return streamJpg.ToArray(); - } - } - - public static void PreloadAvatars(ContentManager contentManager, VirtualFileSystem virtualFileSystem) - { - try - { - if (_avatarStore.Count > 0) - { - return; - } - - _isPreloading = true; - - string contentPath = - contentManager.GetInstalledContentPath(0x010000000000080A, StorageId.BuiltInSystem, - NcaContentType.Data); - string avatarPath = virtualFileSystem.SwitchPathToSystemPath(contentPath); - - if (!string.IsNullOrWhiteSpace(avatarPath)) - { - using (IStorage ncaFileStream = new LocalStorage(avatarPath, FileAccess.Read, FileMode.Open)) - { - Nca nca = new(virtualFileSystem.KeySet, ncaFileStream); - IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - - foreach (DirectoryEntryEx item in romfs.EnumerateEntries()) - { - // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. - if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && - item.FullPath.Contains("szs")) - { - using var file = new UniqueRef(); - - romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read) - .ThrowIfFailure(); - - using (MemoryStream stream = new()) - using (MemoryStream streamPng = new()) - { - file.Get.AsStream().CopyTo(stream); - - stream.Position = 0; - - Image avatarImage = Image.LoadPixelData(DecompressYaz0(stream), 256, 256); - - avatarImage.SaveAsPng(streamPng); - - _avatarStore.Add(item.FullPath, streamPng.ToArray()); - } - } - } - } - } - } - finally - { - _isPreloading = false; - _loadCompleteAction?.Invoke(); - } - } - - private static byte[] DecompressYaz0(Stream stream) - { - using (BinaryReader reader = new(stream)) - { - reader.ReadInt32(); // Magic - - uint decodedLength = BinaryPrimitives.ReverseEndianness(reader.ReadUInt32()); - - reader.ReadInt64(); // Padding - - byte[] input = new byte[stream.Length - stream.Position]; - stream.Read(input, 0, input.Length); - - uint inputOffset = 0; - - byte[] output = new byte[decodedLength]; - uint outputOffset = 0; - - ushort mask = 0; - byte header = 0; - - while (outputOffset < decodedLength) - { - if ((mask >>= 1) == 0) - { - header = input[inputOffset++]; - mask = 0x80; - } - - if ((header & mask) != 0) - { - if (outputOffset == output.Length) - { - break; - } - - output[outputOffset++] = input[inputOffset++]; - } - else - { - byte byte1 = input[inputOffset++]; - byte byte2 = input[inputOffset++]; - - uint dist = (uint)((byte1 & 0xF) << 8) | byte2; - uint position = outputOffset - (dist + 1); - - uint length = (uint)byte1 >> 4; - if (length == 0) - { - length = (uint)input[inputOffset++] + 0x12; - } - else - { - length += 2; - } - - uint gap = outputOffset - position; - uint nonOverlappingLength = length; - - if (nonOverlappingLength > gap) - { - nonOverlappingLength = gap; - } - - Buffer.BlockCopy(output, (int)position, output, (int)outputOffset, (int)nonOverlappingLength); - outputOffset += nonOverlappingLength; - position += nonOverlappingLength; - length -= nonOverlappingLength; - - while (length-- > 0) - { - output[outputOffset++] = output[position++]; - } - } - } - - return output; - } - } - - public void Dispose() - { - _loadCompleteAction = null; - IsActive = false; - } - } -} \ No newline at end of file diff --git a/src/Ryujinx.Ava/UI/ViewModels/BaseModel.cs b/src/Ryujinx.Ava/UI/ViewModels/BaseModel.cs index 5a3717fd3..0ff72dbc4 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/BaseModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/BaseModel.cs @@ -12,4 +12,4 @@ namespace Ryujinx.Ava.UI.ViewModels PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/ControllerInputViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/ControllerInputViewModel.cs index fda58504e..c0c625321 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/ControllerInputViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/ControllerInputViewModel.cs @@ -1,3 +1,4 @@ +using Avalonia; using Avalonia.Collections; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; @@ -44,15 +45,14 @@ namespace Ryujinx.Ava.UI.ViewModels private PlayerIndex _playerId; private int _controller; - private int _controllerNumber = 0; + private int _controllerNumber; private string _controllerImage; private int _device; private object _configuration; private string _profileName; private bool _isLoaded; - private readonly UserControl _owner; - private static readonly InputConfigJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly InputConfigJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); public IGamepadDriver AvaloniaKeyboardDriver { get; } public IGamepad SelectedGamepad { get; private set; } @@ -176,11 +176,11 @@ namespace Ryujinx.Ava.UI.ViewModels { get { - SvgImage image = new SvgImage(); + SvgImage image = new(); if (!string.IsNullOrWhiteSpace(_controllerImage)) { - SvgSource source = new SvgSource(); + SvgSource source = new(); source.Load(EmbeddedResources.GetStream(_controllerImage)); @@ -234,22 +234,18 @@ namespace Ryujinx.Ava.UI.ViewModels public ControllerInputViewModel(UserControl owner) : this() { - _owner = owner; - if (Program.PreviewerDetached) { _mainWindow = - (MainWindow)((IClassicDesktopStyleApplicationLifetime)Avalonia.Application.Current + (MainWindow)((IClassicDesktopStyleApplicationLifetime)Application.Current .ApplicationLifetime).MainWindow; AvaloniaKeyboardDriver = new AvaloniaKeyboardDriver(owner); _mainWindow.InputManager.GamepadDriver.OnGamepadConnected += HandleOnGamepadConnected; _mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected += HandleOnGamepadDisconnected; - if (_mainWindow.ViewModel.AppHost != null) - { - _mainWindow.ViewModel.AppHost.NpadManager.BlockInputUpdates(); - } + + _mainWindow.ViewModel.AppHost?.NpadManager.BlockInputUpdates(); _isLoaded = false; @@ -351,7 +347,8 @@ namespace Ryujinx.Ava.UI.ViewModels { return; } - else if (type == DeviceType.Keyboard) + + if (type == DeviceType.Keyboard) { if (_mainWindow.InputManager.KeyboardDriver is AvaloniaKeyboardDriver) { @@ -448,7 +445,7 @@ namespace Ryujinx.Ava.UI.ViewModels const string Hyphen = "-"; const int Offset = 1; - return str.Substring(str.IndexOf(Hyphen) + Offset); + return str[(str.IndexOf(Hyphen) + Offset)..]; } public void LoadDevices() @@ -562,7 +559,7 @@ namespace Ryujinx.Ava.UI.ViewModels ButtonL = Key.E, ButtonZl = Key.Q, ButtonSl = Key.Unbound, - ButtonSr = Key.Unbound + ButtonSr = Key.Unbound, }, LeftJoyconStick = new JoyconConfigKeyboardStick @@ -571,7 +568,7 @@ namespace Ryujinx.Ava.UI.ViewModels StickDown = Key.S, StickLeft = Key.A, StickRight = Key.D, - StickButton = Key.F + StickButton = Key.F, }, RightJoycon = new RightJoyconCommonConfig { @@ -583,7 +580,7 @@ namespace Ryujinx.Ava.UI.ViewModels ButtonR = Key.U, ButtonZr = Key.O, ButtonSl = Key.Unbound, - ButtonSr = Key.Unbound + ButtonSr = Key.Unbound, }, RightJoyconStick = new JoyconConfigKeyboardStick { @@ -591,8 +588,8 @@ namespace Ryujinx.Ava.UI.ViewModels StickDown = Key.K, StickLeft = Key.J, StickRight = Key.L, - StickButton = Key.H - } + StickButton = Key.H, + }, }; } else if (activeDevice.Type == DeviceType.Controller) @@ -622,14 +619,14 @@ namespace Ryujinx.Ava.UI.ViewModels ButtonL = ConfigGamepadInputId.LeftShoulder, ButtonZl = ConfigGamepadInputId.LeftTrigger, ButtonSl = ConfigGamepadInputId.Unbound, - ButtonSr = ConfigGamepadInputId.Unbound + ButtonSr = ConfigGamepadInputId.Unbound, }, LeftJoyconStick = new JoyconConfigControllerStick { Joystick = ConfigStickInputId.Left, StickButton = ConfigGamepadInputId.LeftStick, InvertStickX = false, - InvertStickY = false + InvertStickY = false, }, RightJoycon = new RightJoyconCommonConfig { @@ -641,28 +638,28 @@ namespace Ryujinx.Ava.UI.ViewModels ButtonR = ConfigGamepadInputId.RightShoulder, ButtonZr = ConfigGamepadInputId.RightTrigger, ButtonSl = ConfigGamepadInputId.Unbound, - ButtonSr = ConfigGamepadInputId.Unbound + ButtonSr = ConfigGamepadInputId.Unbound, }, RightJoyconStick = new JoyconConfigControllerStick { Joystick = ConfigStickInputId.Right, StickButton = ConfigGamepadInputId.RightStick, InvertStickX = false, - InvertStickY = false + InvertStickY = false, }, Motion = new StandardMotionConfigController { MotionBackend = MotionInputBackendType.GamepadDriver, EnableMotion = true, Sensitivity = 100, - GyroDeadzone = 1 + GyroDeadzone = 1, }, Rumble = new RumbleConfigController { StrongRumble = 1f, WeakRumble = 1f, - EnableRumble = false - } + EnableRumble = false, + }, }; } else @@ -709,7 +706,7 @@ namespace Ryujinx.Ava.UI.ViewModels try { - config = JsonHelper.DeserializeFromFile(path, SerializerContext.InputConfig); + config = JsonHelper.DeserializeFromFile(path, _serializerContext.InputConfig); } catch (JsonException) { } catch (InvalidOperationException) @@ -754,37 +751,35 @@ namespace Ryujinx.Ava.UI.ViewModels return; } + + bool validFileName = ProfileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1; + + if (validFileName) + { + string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json"); + + InputConfig config = null; + + if (IsKeyboard) + { + config = (Configuration as InputConfiguration).GetConfig(); + } + else if (IsController) + { + config = (Configuration as InputConfiguration).GetConfig(); + } + + config.ControllerType = Controllers[_controller].Type; + + string jsonString = JsonHelper.Serialize(config, _serializerContext.InputConfig); + + await File.WriteAllTextAsync(path, jsonString); + + LoadProfiles(); + } else { - bool validFileName = ProfileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1; - - if (validFileName) - { - string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json"); - - InputConfig config = null; - - if (IsKeyboard) - { - config = (Configuration as InputConfiguration).GetConfig(); - } - else if (IsController) - { - config = (Configuration as InputConfiguration).GetConfig(); - } - - config.ControllerType = Controllers[_controller].Type; - - string jsonString = JsonHelper.Serialize(config, SerializerContext.InputConfig); - - await File.WriteAllTextAsync(path, jsonString); - - LoadProfiles(); - } - else - { - await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogProfileInvalidProfileNameErrorMessage]); - } + await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogProfileInvalidProfileNameErrorMessage]); } } @@ -887,6 +882,8 @@ namespace Ryujinx.Ava.UI.ViewModels public void Dispose() { + GC.SuppressFinalize(this); + _mainWindow.InputManager.GamepadDriver.OnGamepadConnected -= HandleOnGamepadConnected; _mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected -= HandleOnGamepadDisconnected; @@ -897,4 +894,4 @@ namespace Ryujinx.Ava.UI.ViewModels AvaloniaKeyboardDriver.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/DownloadableContentManagerViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/DownloadableContentManagerViewModel.cs index 1d7da9a40..f2f569472 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/DownloadableContentManagerViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/DownloadableContentManagerViewModel.cs @@ -22,6 +22,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using Application = Avalonia.Application; using Path = System.IO.Path; namespace Ryujinx.Ava.UI.ViewModels @@ -29,18 +30,17 @@ namespace Ryujinx.Ava.UI.ViewModels public class DownloadableContentManagerViewModel : BaseModel { private readonly List _downloadableContentContainerList; - private readonly string _downloadableContentJsonPath; + private readonly string _downloadableContentJsonPath; - private VirtualFileSystem _virtualFileSystem; + private readonly VirtualFileSystem _virtualFileSystem; private AvaloniaList _downloadableContents = new(); private AvaloniaList _views = new(); private AvaloniaList _selectedDownloadableContents = new(); private string _search; - private ulong _titleId; - private string _titleName; + private readonly ulong _titleId; - private static readonly DownloadableContentJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly DownloadableContentJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); public AvaloniaList DownloadableContents { @@ -90,18 +90,17 @@ namespace Ryujinx.Ava.UI.ViewModels get => string.Format(LocaleManager.Instance[LocaleKeys.DlcWindowHeading], DownloadableContents.Count); } - public DownloadableContentManagerViewModel(VirtualFileSystem virtualFileSystem, ulong titleId, string titleName) + public DownloadableContentManagerViewModel(VirtualFileSystem virtualFileSystem, ulong titleId) { _virtualFileSystem = virtualFileSystem; - _titleId = titleId; - _titleName = titleName; + _titleId = titleId; _downloadableContentJsonPath = Path.Combine(AppDataManager.GamesDirPath, titleId.ToString("x16"), "dlc.json"); try { - _downloadableContentContainerList = JsonHelper.DeserializeFromFile(_downloadableContentJsonPath, SerializerContext.ListDownloadableContentContainer); + _downloadableContentContainerList = JsonHelper.DeserializeFromFile(_downloadableContentJsonPath, _serializerContext.ListDownloadableContentContainer); } catch { @@ -132,7 +131,7 @@ namespace Ryujinx.Ava.UI.ViewModels Nca nca = TryOpenNca(ncaFile.Get.AsStorage(), downloadableContentContainer.ContainerPath); if (nca != null) - { + { var content = new DownloadableContentModel(nca.Header.TitleId.ToString("X16"), downloadableContentContainer.ContainerPath, downloadableContentNca.FullPath, @@ -196,19 +195,19 @@ namespace Ryujinx.Ava.UI.ViewModels public async void Add() { - OpenFileDialog dialog = new OpenFileDialog() + OpenFileDialog dialog = new() { - Title = LocaleManager.Instance[LocaleKeys.SelectDlcDialogTitle], - AllowMultiple = true + Title = LocaleManager.Instance[LocaleKeys.SelectDlcDialogTitle], + AllowMultiple = true, }; dialog.Filters.Add(new FileDialogFilter { - Name = "NSP", - Extensions = { "nsp" } + Name = "NSP", + Extensions = { "nsp" }, }); - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { string[] files = await dialog.ShowAsync(desktop.MainWindow); @@ -231,8 +230,8 @@ namespace Ryujinx.Ava.UI.ViewModels using FileStream containerFile = File.OpenRead(path); - PartitionFileSystem partitionFileSystem = new(containerFile.AsStorage()); - bool containsDownloadableContent = false; + PartitionFileSystem partitionFileSystem = new(containerFile.AsStorage()); + bool containsDownloadableContent = false; _virtualFileSystem.ImportTickets(partitionFileSystem); @@ -313,16 +312,16 @@ namespace Ryujinx.Ava.UI.ViewModels container = new DownloadableContentContainer { - ContainerPath = downloadableContent.ContainerPath, - DownloadableContentNcaList = new List() + ContainerPath = downloadableContent.ContainerPath, + DownloadableContentNcaList = new List(), }; } container.DownloadableContentNcaList.Add(new DownloadableContentNca { - Enabled = downloadableContent.Enabled, - TitleId = Convert.ToUInt64(downloadableContent.TitleId, 16), - FullPath = downloadableContent.FullPath + Enabled = downloadableContent.Enabled, + TitleId = Convert.ToUInt64(downloadableContent.TitleId, 16), + FullPath = downloadableContent.FullPath, }); } @@ -331,8 +330,8 @@ namespace Ryujinx.Ava.UI.ViewModels _downloadableContentContainerList.Add(container); } - JsonHelper.SerializeToFile(_downloadableContentJsonPath, _downloadableContentContainerList, SerializerContext.ListDownloadableContentContainer); + JsonHelper.SerializeToFile(_downloadableContentJsonPath, _downloadableContentContainerList, _serializerContext.ListDownloadableContentContainer); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/MainWindowViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/MainWindowViewModel.cs index 409ccad3c..e8d68f769 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/MainWindowViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/MainWindowViewModel.cs @@ -1,3 +1,4 @@ +using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Input; @@ -12,6 +13,7 @@ using Ryujinx.Ava.Input; using Ryujinx.Ava.UI.Controls; using Ryujinx.Ava.UI.Helpers; using Ryujinx.Ava.UI.Models; +using Ryujinx.Ava.UI.Models.Generic; using Ryujinx.Ava.UI.Renderer; using Ryujinx.Ava.UI.Windows; using Ryujinx.Common; @@ -23,6 +25,7 @@ using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS.Services.Account.Acc; using Ryujinx.HLE.Ui; +using Ryujinx.Modules; using Ryujinx.Ui.App.Common; using Ryujinx.Ui.Common; using Ryujinx.Ui.Common.Configuration; @@ -34,7 +37,10 @@ using System.Collections.ObjectModel; using System.IO; using System.Threading; using System.Threading.Tasks; -using Path = System.IO.Path; +using Image = SixLabors.ImageSharp.Image; +using InputManager = Ryujinx.Input.HLE.InputManager; +using Key = Ryujinx.Input.Key; +using MissingKeyException = LibHac.Common.Keys.MissingKeyException; using ShaderCacheLoadingState = Ryujinx.Graphics.Gpu.Shader.ShaderCacheState; namespace Ryujinx.Ava.UI.ViewModels @@ -89,7 +95,7 @@ namespace Ryujinx.Ava.UI.ViewModels private Cursor _cursor; private string _title; private string _currentEmulatedGamePath; - private AutoResetEvent _rendererWaitEvent; + private readonly AutoResetEvent _rendererWaitEvent; private WindowState _windowState; private double _windowWidth; private double _windowHeight; @@ -128,7 +134,7 @@ namespace Ryujinx.Ava.UI.ViewModels ApplicationLibrary applicationLibrary, VirtualFileSystem virtualFileSystem, AccountManager accountManager, - Ryujinx.Input.HLE.InputManager inputManager, + InputManager inputManager, UserChannelPersistence userChannelPersistence, LibHacHorizonManager libHacHorizonManager, IHostUiHandler uiHandler, @@ -152,7 +158,7 @@ namespace Ryujinx.Ava.UI.ViewModels TopLevel = topLevel; } -#region Properties + #region Properties public string SearchText { @@ -177,7 +183,7 @@ namespace Ryujinx.Ava.UI.ViewModels public bool CanUpdate { - get => _canUpdate && EnableNonGameRunningControls && Modules.Updater.CanUpdate(false); + get => _canUpdate && EnableNonGameRunningControls && Updater.CanUpdate(false); set { _canUpdate = value; @@ -343,11 +349,11 @@ namespace Ryujinx.Ava.UI.ViewModels } } - public bool OpenUserSaveDirectoryEnabled => !Utilities.IsZeros(SelectedApplication.ControlHolder.ByteSpan) && SelectedApplication.ControlHolder.Value.UserAccountSaveDataSize > 0; + public bool OpenUserSaveDirectoryEnabled => !SelectedApplication.ControlHolder.ByteSpan.IsZeros() && SelectedApplication.ControlHolder.Value.UserAccountSaveDataSize > 0; - public bool OpenDeviceSaveDirectoryEnabled => !Utilities.IsZeros(SelectedApplication.ControlHolder.ByteSpan) && SelectedApplication.ControlHolder.Value.DeviceSaveDataSize > 0; + public bool OpenDeviceSaveDirectoryEnabled => !SelectedApplication.ControlHolder.ByteSpan.IsZeros() && SelectedApplication.ControlHolder.Value.DeviceSaveDataSize > 0; - public bool OpenBcatSaveDirectoryEnabled => !Utilities.IsZeros(SelectedApplication.ControlHolder.ByteSpan) && SelectedApplication.ControlHolder.Value.BcatDeliveryCacheStorageSize > 0; + public bool OpenBcatSaveDirectoryEnabled => !SelectedApplication.ControlHolder.ByteSpan.IsZeros() && SelectedApplication.ControlHolder.Value.BcatDeliveryCacheStorageSize > 0; public string LoadHeading { @@ -622,7 +628,7 @@ namespace Ryujinx.Ava.UI.ViewModels OnPropertyChanged(); } } - + public double WindowWidth { get => _windowWidth; @@ -888,7 +894,7 @@ namespace Ryujinx.Ava.UI.ViewModels public ApplicationLibrary ApplicationLibrary { get; private set; } public VirtualFileSystem VirtualFileSystem { get; private set; } public AccountManager AccountManager { get; private set; } - public Ryujinx.Input.HLE.InputManager InputManager { get; private set; } + public InputManager InputManager { get; private set; } public UserChannelPersistence UserChannelPersistence { get; private set; } public Action ShowLoading { get; private set; } public Action SwitchToGameControl { get; private set; } @@ -911,15 +917,16 @@ namespace Ryujinx.Ava.UI.ViewModels public bool IsGridLarge => ConfigurationState.Instance.Ui.GridSize == 3; public bool IsGridHuge => ConfigurationState.Instance.Ui.GridSize == 4; -#endregion + #endregion -#region PrivateMethods + #region PrivateMethods private IComparer GetComparer() { return SortMode switch { - ApplicationSort.LastPlayed => new Models.Generic.LastPlayedSortComparer(IsAscending), +#pragma warning disable IDE0055 // Disable formatting + ApplicationSort.LastPlayed => new LastPlayedSortComparer(IsAscending), ApplicationSort.FileSize => IsAscending ? SortExpressionComparer.Ascending(app => app.FileSizeBytes) : SortExpressionComparer.Descending(app => app.FileSizeBytes), ApplicationSort.TotalTimePlayed => IsAscending ? SortExpressionComparer.Ascending(app => app.TimePlayedNum) @@ -935,6 +942,7 @@ namespace Ryujinx.Ava.UI.ViewModels ApplicationSort.Path => IsAscending ? SortExpressionComparer.Ascending(app => app.Path) : SortExpressionComparer.Descending(app => app.Path), _ => null, +#pragma warning restore IDE0055 }; } @@ -1023,7 +1031,7 @@ namespace Ryujinx.Ava.UI.ViewModels // Purge Applet Cache. - DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache")); + DirectoryInfo miiEditorCacheFolder = new(Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache")); if (miiEditorCacheFolder.Exists) { @@ -1044,18 +1052,21 @@ namespace Ryujinx.Ava.UI.ViewModels { RefreshFirmwareStatus(); } - }) { Name = "GUI.FirmwareInstallerThread" }; + }) + { + Name = "GUI.FirmwareInstallerThread", + }; thread.Start(); } } - catch (LibHac.Common.Keys.MissingKeyException ex) + catch (MissingKeyException ex) { - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { Logger.Error?.Print(LogClass.Application, ex.ToString()); - async void Action() => await UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys, (desktop.MainWindow as MainWindow)); + static async void Action() => await UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys); Dispatcher.UIThread.Post(Action); } @@ -1120,17 +1131,17 @@ namespace Ryujinx.Ava.UI.ViewModels private void PrepareLoadScreen() { using MemoryStream stream = new(SelectedIcon); - using var gameIconBmp = SixLabors.ImageSharp.Image.Load(stream); + using var gameIconBmp = Image.Load(stream); var dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp).ToPixel(); - const float colorMultiple = 0.5f; + const float ColorMultiple = 0.5f; Color progressFgColor = Color.FromRgb(dominantColor.R, dominantColor.G, dominantColor.B); Color progressBgColor = Color.FromRgb( - (byte)(dominantColor.R * colorMultiple), - (byte)(dominantColor.G * colorMultiple), - (byte)(dominantColor.B * colorMultiple)); + (byte)(dominantColor.R * ColorMultiple), + (byte)(dominantColor.G * ColorMultiple), + (byte)(dominantColor.B * ColorMultiple)); ProgressBarForegroundColor = new SolidColorBrush(progressFgColor); ProgressBarBackgroundColor = new SolidColorBrush(progressBgColor); @@ -1175,7 +1186,7 @@ namespace Ryujinx.Ava.UI.ViewModels { Dispatcher.UIThread.InvokeAsync(() => { - Avalonia.Application.Current.Styles.TryGetResource(args.VSyncEnabled + Application.Current.Styles.TryGetResource(args.VSyncEnabled ? "VsyncEnabled" : "VsyncDisabled", out object color); @@ -1204,11 +1215,11 @@ namespace Ryujinx.Ava.UI.ViewModels _rendererWaitEvent.Set(); } -#endregion + #endregion -#region PublicMethods + #region PublicMethods - public void SetUIProgressHandlers(Switch emulationContext) + public void SetUiProgressHandlers(Switch emulationContext) { if (emulationContext.Processes.ActiveApplication.DiskCacheLoadState != null) { @@ -1222,17 +1233,17 @@ namespace Ryujinx.Ava.UI.ViewModels public void LoadConfigurableHotKeys() { - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Ryujinx.Input.Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi, out var showUiKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi, out var showUiKey)) { ShowUiKey = new KeyGesture(showUiKey); } - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Ryujinx.Input.Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out var screenshotKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out var screenshotKey)) { ScreenshotKey = new KeyGesture(screenshotKey); } - if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Ryujinx.Input.Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out var pauseKey)) + if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out var pauseKey)) { PauseKey = new KeyGesture(pauseKey); } @@ -1260,12 +1271,12 @@ namespace Ryujinx.Ava.UI.ViewModels public async void InstallFirmwareFromFile() { - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { OpenFileDialog dialog = new() { AllowMultiple = false }; dialog.Filters.Add(new FileDialogFilter { Name = LocaleManager.Instance[LocaleKeys.FileDialogAllTypes], Extensions = { "xci", "zip" } }); - dialog.Filters.Add(new FileDialogFilter { Name = "XCI", Extensions = { "xci" } }); - dialog.Filters.Add(new FileDialogFilter { Name = "ZIP", Extensions = { "zip" } }); + dialog.Filters.Add(new FileDialogFilter { Name = "XCI", Extensions = { "xci" } }); + dialog.Filters.Add(new FileDialogFilter { Name = "ZIP", Extensions = { "zip" } }); string[] file = await dialog.ShowAsync(desktop.MainWindow); @@ -1278,7 +1289,7 @@ namespace Ryujinx.Ava.UI.ViewModels public async void InstallFirmwareFromFolder() { - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { OpenFolderDialog dialog = new(); @@ -1327,7 +1338,7 @@ namespace Ryujinx.Ava.UI.ViewModels } } - public void ChangeLanguage(object languageCode) + public static void ChangeLanguage(object languageCode) { LocaleManager.Instance.LoadLanguage((string)languageCode); @@ -1342,6 +1353,7 @@ namespace Ryujinx.Ava.UI.ViewModels { _ = fileType switch { +#pragma warning disable IDE0055 // Disable formatting "NSP" => ConfigurationState.Instance.Ui.ShownFileTypes.NSP.Value = !ConfigurationState.Instance.Ui.ShownFileTypes.NSP, "PFS0" => ConfigurationState.Instance.Ui.ShownFileTypes.PFS0.Value = !ConfigurationState.Instance.Ui.ShownFileTypes.PFS0, "XCI" => ConfigurationState.Instance.Ui.ShownFileTypes.XCI.Value = !ConfigurationState.Instance.Ui.ShownFileTypes.XCI, @@ -1349,6 +1361,7 @@ namespace Ryujinx.Ava.UI.ViewModels "NRO" => ConfigurationState.Instance.Ui.ShownFileTypes.NRO.Value = !ConfigurationState.Instance.Ui.ShownFileTypes.NRO, "NSO" => ConfigurationState.Instance.Ui.ShownFileTypes.NSO.Value = !ConfigurationState.Instance.Ui.ShownFileTypes.NSO, _ => throw new ArgumentOutOfRangeException(fileType), +#pragma warning restore IDE0055 }; ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath); @@ -1371,9 +1384,9 @@ namespace Ryujinx.Ava.UI.ViewModels { Applications.Clear(); - StatusBarVisible = true; + StatusBarVisible = true; StatusBarProgressMaximum = 0; - StatusBarProgressValue = 0; + StatusBarProgressValue = 0; LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarGamesLoaded, 0, 0); }); @@ -1383,11 +1396,11 @@ namespace Ryujinx.Ava.UI.ViewModels public async void OpenFile() { - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { OpenFileDialog dialog = new() { - Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle] + Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle], }; dialog.Filters.Add(new FileDialogFilter @@ -1400,16 +1413,18 @@ namespace Ryujinx.Ava.UI.ViewModels "xci", "nca", "nro", - "nso" - } + "nso", + }, }); +#pragma warning disable IDE0055 // Disable formatting dialog.Filters.Add(new FileDialogFilter { Name = "NSP", Extensions = { "nsp" } }); dialog.Filters.Add(new FileDialogFilter { Name = "PFS0", Extensions = { "pfs0" } }); dialog.Filters.Add(new FileDialogFilter { Name = "XCI", Extensions = { "xci" } }); dialog.Filters.Add(new FileDialogFilter { Name = "NCA", Extensions = { "nca" } }); dialog.Filters.Add(new FileDialogFilter { Name = "NRO", Extensions = { "nro" } }); dialog.Filters.Add(new FileDialogFilter { Name = "NSO", Extensions = { "nso" } }); +#pragma warning restore IDE0055 string[] files = await dialog.ShowAsync(desktop.MainWindow); @@ -1422,11 +1437,11 @@ namespace Ryujinx.Ava.UI.ViewModels public async void OpenFolder() { - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { OpenFolderDialog dialog = new() { - Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle] + Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle], }; string folder = await dialog.ShowAsync(desktop.MainWindow); @@ -1458,10 +1473,7 @@ namespace Ryujinx.Ava.UI.ViewModels Logger.RestartTime(); - if (SelectedIcon == null) - { - SelectedIcon = ApplicationLibrary.GetApplicationIcon(path); - } + SelectedIcon ??= ApplicationLibrary.GetApplicationIcon(path); PrepareLoadScreen(); @@ -1495,7 +1507,7 @@ namespace Ryujinx.Ava.UI.ViewModels if (string.IsNullOrWhiteSpace(titleName)) { LoadHeading = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.LoadingHeading, AppHost.Device.Processes.ActiveApplication.Name); - TitleName = AppHost.Device.Processes.ActiveApplication.Name; + TitleName = AppHost.Device.Processes.ActiveApplication.Name; } SwitchToRenderer(startFullscreen); @@ -1521,7 +1533,7 @@ namespace Ryujinx.Ava.UI.ViewModels }); } - public void UpdateGameMetadata(string titleId) + public static void UpdateGameMetadata(string titleId) { ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata => { @@ -1675,6 +1687,6 @@ namespace Ryujinx.Ava.UI.ViewModels } } -#endregion + #endregion } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/MotionInputViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/MotionInputViewModel.cs index d57ccc6bb..0b12a51f6 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/MotionInputViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/MotionInputViewModel.cs @@ -90,4 +90,4 @@ namespace Ryujinx.Ava.UI.ViewModels } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/RumbleInputViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/RumbleInputViewModel.cs index 2d53968f7..49de19937 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/RumbleInputViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/RumbleInputViewModel.cs @@ -24,4 +24,4 @@ namespace Ryujinx.Ava.UI.ViewModels } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/SettingsViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/SettingsViewModel.cs index d260b6fc7..a9eb9c618 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/SettingsViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/SettingsViewModel.cs @@ -22,10 +22,9 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using System.Runtime.InteropServices; using System.Net.NetworkInformation; +using System.Runtime.InteropServices; using TimeZone = Ryujinx.Ava.UI.Models.TimeZone; -using Silk.NET.Vulkan; namespace Ryujinx.Ava.UI.ViewModels { @@ -248,7 +247,7 @@ namespace Ryujinx.Ava.UI.ViewModels public AvaloniaList NetworkInterfaceList { - get => new AvaloniaList(_networkInterfaces.Keys); + get => new(_networkInterfaces.Keys); } public KeyboardHotkeys KeyboardHotkeys @@ -561,7 +560,7 @@ namespace Ryujinx.Ava.UI.ViewModels _directoryChanged = false; } - public void RevertIfNotSaved() + private static void RevertIfNotSaved() { Program.ReloadConfig(); } @@ -583,4 +582,4 @@ namespace Ryujinx.Ava.UI.ViewModels CloseWindow?.Invoke(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/TitleUpdateViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/TitleUpdateViewModel.cs index 1f4e3c624..740d888bb 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/TitleUpdateViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/TitleUpdateViewModel.cs @@ -1,3 +1,4 @@ +using Avalonia; using Avalonia.Collections; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; @@ -16,7 +17,6 @@ using Ryujinx.Common.Configuration; using Ryujinx.Common.Logging; using Ryujinx.Common.Utilities; using Ryujinx.HLE.FileSystem; -using Ryujinx.HLE.HOS; using Ryujinx.Ui.App.Common; using System; using System.Collections.Generic; @@ -29,17 +29,16 @@ namespace Ryujinx.Ava.UI.ViewModels { public class TitleUpdateViewModel : BaseModel { - public TitleUpdateMetadata _titleUpdateWindowData; - public readonly string _titleUpdateJsonPath; - private VirtualFileSystem _virtualFileSystem { get; } - private ulong _titleId { get; } - private string _titleName { get; } + public TitleUpdateMetadata TitleUpdateWindowData; + public readonly string TitleUpdateJsonPath; + private VirtualFileSystem VirtualFileSystem { get; } + private ulong TitleId { get; } private AvaloniaList _titleUpdates = new(); private AvaloniaList _views = new(); private object _selectedUpdate; - private static readonly TitleUpdateMetadataJsonSerializerContext SerializerContext = new(JsonHelper.GetDefaultSerializerOptions()); + private static readonly TitleUpdateMetadataJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions()); public AvaloniaList TitleUpdates { @@ -71,27 +70,26 @@ namespace Ryujinx.Ava.UI.ViewModels } } - public TitleUpdateViewModel(VirtualFileSystem virtualFileSystem, ulong titleId, string titleName) + public TitleUpdateViewModel(VirtualFileSystem virtualFileSystem, ulong titleId) { - _virtualFileSystem = virtualFileSystem; + VirtualFileSystem = virtualFileSystem; - _titleId = titleId; - _titleName = titleName; + TitleId = titleId; - _titleUpdateJsonPath = Path.Combine(AppDataManager.GamesDirPath, titleId.ToString("x16"), "updates.json"); + TitleUpdateJsonPath = Path.Combine(AppDataManager.GamesDirPath, titleId.ToString("x16"), "updates.json"); try { - _titleUpdateWindowData = JsonHelper.DeserializeFromFile(_titleUpdateJsonPath, SerializerContext.TitleUpdateMetadata); + TitleUpdateWindowData = JsonHelper.DeserializeFromFile(TitleUpdateJsonPath, _serializerContext.TitleUpdateMetadata); } catch { - Logger.Warning?.Print(LogClass.Application, $"Failed to deserialize title update data for {_titleId} at {_titleUpdateJsonPath}"); + Logger.Warning?.Print(LogClass.Application, $"Failed to deserialize title update data for {TitleId} at {TitleUpdateJsonPath}"); - _titleUpdateWindowData = new TitleUpdateMetadata + TitleUpdateWindowData = new TitleUpdateMetadata { Selected = "", - Paths = new List() + Paths = new List(), }; Save(); @@ -102,12 +100,12 @@ namespace Ryujinx.Ava.UI.ViewModels private void LoadUpdates() { - foreach (string path in _titleUpdateWindowData.Paths) + foreach (string path in TitleUpdateWindowData.Paths) { AddUpdate(path); } - TitleUpdateModel selected = TitleUpdates.FirstOrDefault(x => x.Path == _titleUpdateWindowData.Selected, null); + TitleUpdateModel selected = TitleUpdates.FirstOrDefault(x => x.Path == TitleUpdateWindowData.Selected, null); SelectedUpdate = selected; @@ -126,7 +124,8 @@ namespace Ryujinx.Ava.UI.ViewModels { return -1; } - else if (string.IsNullOrEmpty(second.Control.DisplayVersionString.ToString())) + + if (string.IsNullOrEmpty(second.Control.DisplayVersionString.ToString())) { return 1; } @@ -163,7 +162,7 @@ namespace Ryujinx.Ava.UI.ViewModels try { - (Nca patchNca, Nca controlNca) = ApplicationLibrary.GetGameUpdateDataFromPartition(_virtualFileSystem, new PartitionFileSystem(file.AsStorage()), _titleId.ToString("x16"), 0); + (Nca patchNca, Nca controlNca) = ApplicationLibrary.GetGameUpdateDataFromPartition(VirtualFileSystem, new PartitionFileSystem(file.AsStorage()), TitleId.ToString("x16"), 0); if (controlNca != null && patchNca != null) { @@ -205,17 +204,17 @@ namespace Ryujinx.Ava.UI.ViewModels { OpenFileDialog dialog = new() { - Title = LocaleManager.Instance[LocaleKeys.SelectUpdateDialogTitle], - AllowMultiple = true + Title = LocaleManager.Instance[LocaleKeys.SelectUpdateDialogTitle], + AllowMultiple = true, }; dialog.Filters.Add(new FileDialogFilter { - Name = "NSP", - Extensions = { "nsp" } + Name = "NSP", + Extensions = { "nsp" }, }); - if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { string[] files = await dialog.ShowAsync(desktop.MainWindow); @@ -233,20 +232,20 @@ namespace Ryujinx.Ava.UI.ViewModels public void Save() { - _titleUpdateWindowData.Paths.Clear(); - _titleUpdateWindowData.Selected = ""; + TitleUpdateWindowData.Paths.Clear(); + TitleUpdateWindowData.Selected = ""; foreach (TitleUpdateModel update in TitleUpdates) { - _titleUpdateWindowData.Paths.Add(update.Path); + TitleUpdateWindowData.Paths.Add(update.Path); if (update == SelectedUpdate) { - _titleUpdateWindowData.Selected = update.Path; + TitleUpdateWindowData.Selected = update.Path; } } - JsonHelper.SerializeToFile(_titleUpdateJsonPath, _titleUpdateWindowData, SerializerContext.TitleUpdateMetadata); + JsonHelper.SerializeToFile(TitleUpdateJsonPath, TitleUpdateWindowData, _serializerContext.TitleUpdateMetadata); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs index 558cad5a7..89b591229 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/UserFirmwareAvatarSelectorViewModel.cs @@ -28,7 +28,6 @@ namespace Ryujinx.Ava.UI.ViewModels private Color _backgroundColor = Colors.White; private int _selectedIndex; - private byte[] _selectedImage; public UserFirmwareAvatarSelectorViewModel() { @@ -78,11 +77,7 @@ namespace Ryujinx.Ava.UI.ViewModels } } - public byte[] SelectedImage - { - get => _selectedImage; - private set => _selectedImage = value; - } + public byte[] SelectedImage { get; private set; } private void LoadImagesFromStore() { @@ -110,38 +105,36 @@ namespace Ryujinx.Ava.UI.ViewModels } string contentPath = contentManager.GetInstalledContentPath(0x010000000000080A, StorageId.BuiltInSystem, NcaContentType.Data); - string avatarPath = virtualFileSystem.SwitchPathToSystemPath(contentPath); + string avatarPath = VirtualFileSystem.SwitchPathToSystemPath(contentPath); if (!string.IsNullOrWhiteSpace(avatarPath)) { - using (IStorage ncaFileStream = new LocalStorage(avatarPath, FileAccess.Read, FileMode.Open)) + using IStorage ncaFileStream = new LocalStorage(avatarPath, FileAccess.Read, FileMode.Open); + + Nca nca = new(virtualFileSystem.KeySet, ncaFileStream); + IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); + + foreach (DirectoryEntryEx item in romfs.EnumerateEntries()) { - Nca nca = new(virtualFileSystem.KeySet, ncaFileStream); - IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid); - - foreach (DirectoryEntryEx item in romfs.EnumerateEntries()) + // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. + if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && item.FullPath.Contains("szs")) { - // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy. - if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") && item.FullPath.Contains("szs")) - { - using var file = new UniqueRef(); + using var file = new UniqueRef(); - romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read).ThrowIfFailure(); + romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read).ThrowIfFailure(); - using (MemoryStream stream = new()) - using (MemoryStream streamPng = new()) - { - file.Get.AsStream().CopyTo(stream); + using MemoryStream stream = new(); + using MemoryStream streamPng = new(); - stream.Position = 0; + file.Get.AsStream().CopyTo(stream); - Image avatarImage = Image.LoadPixelData(DecompressYaz0(stream), 256, 256); + stream.Position = 0; - avatarImage.SaveAsPng(streamPng); + Image avatarImage = Image.LoadPixelData(DecompressYaz0(stream), 256, 256); - _avatarStore.Add(item.FullPath, streamPng.ToArray()); - } - } + avatarImage.SaveAsPng(streamPng); + + _avatarStore.Add(item.FullPath, streamPng.ToArray()); } } } @@ -149,82 +142,81 @@ namespace Ryujinx.Ava.UI.ViewModels private static byte[] DecompressYaz0(Stream stream) { - using (BinaryReader reader = new(stream)) + using BinaryReader reader = new(stream); + + reader.ReadInt32(); // Magic + + uint decodedLength = BinaryPrimitives.ReverseEndianness(reader.ReadUInt32()); + + reader.ReadInt64(); // Padding + + byte[] input = new byte[stream.Length - stream.Position]; + stream.Read(input, 0, input.Length); + + uint inputOffset = 0; + + byte[] output = new byte[decodedLength]; + uint outputOffset = 0; + + ushort mask = 0; + byte header = 0; + + while (outputOffset < decodedLength) { - reader.ReadInt32(); // Magic - - uint decodedLength = BinaryPrimitives.ReverseEndianness(reader.ReadUInt32()); - - reader.ReadInt64(); // Padding - - byte[] input = new byte[stream.Length - stream.Position]; - stream.Read(input, 0, input.Length); - - uint inputOffset = 0; - - byte[] output = new byte[decodedLength]; - uint outputOffset = 0; - - ushort mask = 0; - byte header = 0; - - while (outputOffset < decodedLength) + if ((mask >>= 1) == 0) { - if ((mask >>= 1) == 0) + header = input[inputOffset++]; + mask = 0x80; + } + + if ((header & mask) != 0) + { + if (outputOffset == output.Length) { - header = input[inputOffset++]; - mask = 0x80; + break; } - if ((header & mask) != 0) - { - if (outputOffset == output.Length) - { - break; - } + output[outputOffset++] = input[inputOffset++]; + } + else + { + byte byte1 = input[inputOffset++]; + byte byte2 = input[inputOffset++]; - output[outputOffset++] = input[inputOffset++]; + uint dist = (uint)((byte1 & 0xF) << 8) | byte2; + uint position = outputOffset - (dist + 1); + + uint length = (uint)byte1 >> 4; + if (length == 0) + { + length = (uint)input[inputOffset++] + 0x12; } else { - byte byte1 = input[inputOffset++]; - byte byte2 = input[inputOffset++]; + length += 2; + } - uint dist = (uint)((byte1 & 0xF) << 8) | byte2; - uint position = outputOffset - (dist + 1); + uint gap = outputOffset - position; + uint nonOverlappingLength = length; - uint length = (uint)byte1 >> 4; - if (length == 0) - { - length = (uint)input[inputOffset++] + 0x12; - } - else - { - length += 2; - } + if (nonOverlappingLength > gap) + { + nonOverlappingLength = gap; + } - uint gap = outputOffset - position; - uint nonOverlappingLength = length; + Buffer.BlockCopy(output, (int)position, output, (int)outputOffset, (int)nonOverlappingLength); + outputOffset += nonOverlappingLength; + position += nonOverlappingLength; + length -= nonOverlappingLength; - if (nonOverlappingLength > gap) - { - nonOverlappingLength = gap; - } - - Buffer.BlockCopy(output, (int)position, output, (int)outputOffset, (int)nonOverlappingLength); - outputOffset += nonOverlappingLength; - position += nonOverlappingLength; - length -= nonOverlappingLength; - - while (length-- > 0) - { - output[outputOffset++] = output[position++]; - } + while (length-- > 0) + { + output[outputOffset++] = output[position++]; } } - - return output; } + + return output; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/UserProfileImageSelectorViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/UserProfileImageSelectorViewModel.cs index 7261631c1..8e7d41a55 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/UserProfileImageSelectorViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/UserProfileImageSelectorViewModel.cs @@ -7,7 +7,7 @@ namespace Ryujinx.Ava.UI.ViewModels public bool FirmwareFound { get => _firmwareFound; - + set { _firmwareFound = value; @@ -15,4 +15,4 @@ namespace Ryujinx.Ava.UI.ViewModels } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/UserProfileViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/UserProfileViewModel.cs index 8f997efc1..70274847f 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/UserProfileViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/UserProfileViewModel.cs @@ -1,7 +1,7 @@ using Microsoft.IdentityModel.Tokens; +using Ryujinx.Ava.UI.Models; using System; using System.Collections.ObjectModel; -using UserProfile = Ryujinx.Ava.UI.Models.UserProfile; namespace Ryujinx.Ava.UI.ViewModels { @@ -20,6 +20,9 @@ namespace Ryujinx.Ava.UI.ViewModels public bool IsEmpty { get; set; } - public void Dispose() { } + public void Dispose() + { + GC.SuppressFinalize(this); + } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/ViewModels/UserSaveManagerViewModel.cs b/src/Ryujinx.Ava/UI/ViewModels/UserSaveManagerViewModel.cs index 097634a80..0a13f24a8 100644 --- a/src/Ryujinx.Ava/UI/ViewModels/UserSaveManagerViewModel.cs +++ b/src/Ryujinx.Ava/UI/ViewModels/UserSaveManagerViewModel.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Ava.UI.ViewModels private string _search; private ObservableCollection _saves = new(); private ObservableCollection _views = new(); - private AccountManager _accountManager; + private readonly AccountManager _accountManager; public string SaveManagerHeading => LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.SaveManagerHeading, _accountManager.LastOpenedUser.Name, _accountManager.LastOpenedUser.UserId); @@ -102,19 +102,16 @@ namespace Ryujinx.Ava.UI.ViewModels private IComparer GetComparer() { - switch (SortIndex) + return SortIndex switch { - case 0: - return OrderIndex == 0 - ? SortExpressionComparer.Ascending(save => save.Title) - : SortExpressionComparer.Descending(save => save.Title); - case 1: - return OrderIndex == 0 - ? SortExpressionComparer.Ascending(save => save.Size) - : SortExpressionComparer.Descending(save => save.Size); - default: - return null; - } + 0 => OrderIndex == 0 + ? SortExpressionComparer.Ascending(save => save.Title) + : SortExpressionComparer.Descending(save => save.Title), + 1 => OrderIndex == 0 + ? SortExpressionComparer.Ascending(save => save.Size) + : SortExpressionComparer.Descending(save => save.Size), + _ => null, + }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Input/ControllerInputView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Input/ControllerInputView.axaml.cs index 8fe7b9412..19009f5f2 100644 --- a/src/Ryujinx.Ava/UI/Views/Input/ControllerInputView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Input/ControllerInputView.axaml.cs @@ -29,7 +29,7 @@ namespace Ryujinx.Ava.UI.Views.Input foreach (ILogical visual in SettingButtons.GetLogicalDescendants()) { - if (visual is ToggleButton button && !(visual is CheckBox)) + if (visual is ToggleButton button && visual is not CheckBox) { button.Checked += Button_Checked; button.Unchecked += Button_Unchecked; @@ -177,4 +177,4 @@ namespace Ryujinx.Ava.UI.Views.Input ViewModel.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Input/MotionInputView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Input/MotionInputView.axaml.cs index 88bbcd932..1b340752b 100644 --- a/src/Ryujinx.Ava/UI/Views/Input/MotionInputView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Input/MotionInputView.axaml.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Ava.UI.Views.Input { public partial class MotionInputView : UserControl { - private MotionInputViewModel _viewModel; + private readonly MotionInputViewModel _viewModel; public MotionInputView() { @@ -30,7 +30,7 @@ namespace Ryujinx.Ava.UI.Views.Input MirrorInput = config.MirrorInput, Sensitivity = config.Sensitivity, GyroDeadzone = config.GyroDeadzone, - EnableCemuHookMotion = config.EnableCemuHookMotion + EnableCemuHookMotion = config.EnableCemuHookMotion, }; InitializeComponent(); @@ -47,7 +47,7 @@ namespace Ryujinx.Ava.UI.Views.Input PrimaryButtonText = LocaleManager.Instance[LocaleKeys.ControllerSettingsSave], SecondaryButtonText = "", CloseButtonText = LocaleManager.Instance[LocaleKeys.ControllerSettingsClose], - Content = content + Content = content, }; contentDialog.PrimaryButtonClick += (sender, args) => { @@ -65,4 +65,4 @@ namespace Ryujinx.Ava.UI.Views.Input await contentDialog.ShowAsync(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Input/RumbleInputView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Input/RumbleInputView.axaml.cs index dfe05b08b..9307f872c 100644 --- a/src/Ryujinx.Ava/UI/Views/Input/RumbleInputView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Input/RumbleInputView.axaml.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Ava.UI.Views.Input { public partial class RumbleInputView : UserControl { - private RumbleInputViewModel _viewModel; + private readonly RumbleInputViewModel _viewModel; public RumbleInputView() { @@ -24,11 +24,11 @@ namespace Ryujinx.Ava.UI.Views.Input _viewModel = new RumbleInputViewModel { StrongRumble = config.StrongRumble, - WeakRumble = config.WeakRumble + WeakRumble = config.WeakRumble, }; InitializeComponent(); - + DataContext = _viewModel; } @@ -55,4 +55,4 @@ namespace Ryujinx.Ava.UI.Views.Input await contentDialog.ShowAsync(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Main/MainMenuBarView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Main/MainMenuBarView.axaml.cs index f94b80d45..ae52f0719 100644 --- a/src/Ryujinx.Ava/UI/Views/Main/MainMenuBarView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Main/MainMenuBarView.axaml.cs @@ -38,26 +38,26 @@ namespace Ryujinx.Ava.UI.Views.Main { List checkBoxes = new(); - foreach (var item in Enum.GetValues(typeof (FileTypes))) + foreach (var item in Enum.GetValues(typeof(FileTypes))) { - string fileName = Enum.GetName(typeof (FileTypes), item); - checkBoxes.Add(new CheckBox() + string fileName = Enum.GetName(typeof(FileTypes), item); + checkBoxes.Add(new CheckBox { Content = $".{fileName}", IsChecked = ((FileTypes)item).GetConfigValue(ConfigurationState.Instance.Ui.ShownFileTypes), - Command = MiniCommand.Create(() => ViewModel.ToggleFileType(fileName)) + Command = MiniCommand.Create(() => ViewModel.ToggleFileType(fileName)), }); } return checkBoxes.ToArray(); } - private MenuItem[] GenerateLanguageMenuItems() + private static MenuItem[] GenerateLanguageMenuItems() { List menuItems = new(); string localePath = "Ryujinx.Ava/Assets/Locales"; - string localeExt = ".json"; + string localeExt = ".json"; string[] localesPath = EmbeddedResources.GetAllAvailableResources(localePath, localeExt); @@ -67,7 +67,7 @@ namespace Ryujinx.Ava.UI.Views.Main { string languageCode = Path.GetFileNameWithoutExtension(locale).Split('.').Last(); string languageJson = EmbeddedResources.ReadAllText($"{localePath}/{languageCode}{localeExt}"); - var strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); + var strings = JsonHelper.Deserialize(languageJson, CommonJsonContext.Default.StringDictionary); if (!strings.TryGetValue("Language", out string languageName)) { @@ -76,11 +76,11 @@ namespace Ryujinx.Ava.UI.Views.Main MenuItem menuItem = new() { - Header = languageName, + Header = languageName, Command = MiniCommand.Create(() => { - ViewModel.ChangeLanguage(languageCode); - }) + MainWindowViewModel.ChangeLanguage(languageCode); + }), }; menuItems.Add(menuItem); @@ -236,4 +236,4 @@ namespace Ryujinx.Ava.UI.Views.Main Window.Close(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Main/MainStatusBarView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Main/MainStatusBarView.axaml.cs index 473de0ee2..0640869c1 100644 --- a/src/Ryujinx.Ava/UI/Views/Main/MainStatusBarView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Main/MainStatusBarView.axaml.cs @@ -49,4 +49,4 @@ namespace Ryujinx.Ava.UI.Views.Main ConfigurationState.Instance.Graphics.AspectRatio.Value = (int)aspectRatio + 1 > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Main/MainViewControls.axaml.cs b/src/Ryujinx.Ava/UI/Views/Main/MainViewControls.axaml.cs index fd7578939..9163222f4 100644 --- a/src/Ryujinx.Ava/UI/Views/Main/MainViewControls.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Main/MainViewControls.axaml.cs @@ -12,7 +12,7 @@ namespace Ryujinx.Ava.UI.Views.Main public partial class MainViewControls : UserControl { public MainWindowViewModel ViewModel; - + public MainViewControls() { InitializeComponent(); @@ -37,7 +37,7 @@ namespace Ryujinx.Ava.UI.Views.Main ViewModel.Sort(Enum.Parse(button.Tag.ToString())); } } - + public void Order_Checked(object sender, RoutedEventArgs args) { if (sender is RadioButton button) @@ -45,10 +45,10 @@ namespace Ryujinx.Ava.UI.Views.Main ViewModel.Sort(button.Tag.ToString() != "Descending"); } } - + private void SearchBox_OnKeyUp(object sender, KeyEventArgs e) { ViewModel.SearchText = SearchBox.Text; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsAudioView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsAudioView.axaml.cs index 026c7fdf8..f9f93ba3c 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsAudioView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsAudioView.axaml.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Ava.UI.Views.Settings InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsCPUView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsCPUView.axaml.cs index 5c5b60793..47a640e08 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsCPUView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsCPUView.axaml.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Ava.UI.Views.Settings InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsGraphicsView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsGraphicsView.axaml.cs index 8fe08552e..56b966523 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsGraphicsView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsGraphicsView.axaml.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Ava.UI.Views.Settings InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsHotkeysView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsHotkeysView.axaml.cs index 702f73e87..4bbd0133a 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsHotkeysView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsHotkeysView.axaml.cs @@ -12,12 +12,12 @@ namespace Ryujinx.Ava.UI.Views.Settings public partial class SettingsHotkeysView : UserControl { private ButtonKeyAssigner _currentAssigner; - private IGamepadDriver AvaloniaKeyboardDriver; - + private readonly IGamepadDriver _avaloniaKeyboardDriver; + public SettingsHotkeysView() { InitializeComponent(); - AvaloniaKeyboardDriver = new AvaloniaKeyboardDriver(this); + _avaloniaKeyboardDriver = new AvaloniaKeyboardDriver(this); } private void MouseClick(object sender, PointerPressedEventArgs e) @@ -28,7 +28,7 @@ namespace Ryujinx.Ava.UI.Views.Settings PointerPressed -= MouseClick; } - + private void Button_Checked(object sender, RoutedEventArgs e) { if (sender is ToggleButton button) @@ -46,7 +46,7 @@ namespace Ryujinx.Ava.UI.Views.Settings PointerPressed += MouseClick; - var keyboard = (IKeyboard)AvaloniaKeyboardDriver.GetGamepad(AvaloniaKeyboardDriver.GamepadsIds[0]); + var keyboard = (IKeyboard)_avaloniaKeyboardDriver.GetGamepad(_avaloniaKeyboardDriver.GamepadsIds[0]); IButtonAssigner assigner = new KeyboardKeyAssigner(keyboard); _currentAssigner.GetInputAndAssign(assigner); @@ -78,4 +78,4 @@ namespace Ryujinx.Ava.UI.Views.Settings _currentAssigner = null; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsInputView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsInputView.axaml.cs index 0c2105ec4..8a0cb8ab9 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsInputView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsInputView.axaml.cs @@ -14,4 +14,4 @@ namespace Ryujinx.Ava.UI.Views.Settings ControllerSettings.Dispose(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsLoggingView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsLoggingView.axaml.cs index 2ec476ac6..f18f73390 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsLoggingView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsLoggingView.axaml.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Ava.UI.Views.Settings InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsNetworkView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsNetworkView.axaml.cs index d7407b9d5..bf728f410 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsNetworkView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsNetworkView.axaml.cs @@ -9,4 +9,4 @@ namespace Ryujinx.Ava.UI.Views.Settings InitializeComponent(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsSystemView.axaml.cs b/src/Ryujinx.Ava/UI/Views/Settings/SettingsSystemView.axaml.cs index d2ea59deb..4acf2f44c 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsSystemView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsSystemView.axaml.cs @@ -15,7 +15,7 @@ namespace Ryujinx.Ava.UI.Views.Settings public SettingsSystemView() { InitializeComponent(); - + FuncMultiValueConverter converter = new(parts => string.Format("{0} {1} {2}", parts.ToArray()).Trim()); MultiBinding tzMultiBinding = new() { Converter = converter }; @@ -49,4 +49,4 @@ namespace Ryujinx.Ava.UI.Views.Settings } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/Settings/SettingsUIView.axaml b/src/Ryujinx.Ava/UI/Views/Settings/SettingsUIView.axaml index acc5e2b70..c92d56728 100644 --- a/src/Ryujinx.Ava/UI/Views/Settings/SettingsUIView.axaml +++ b/src/Ryujinx.Ava/UI/Views/Settings/SettingsUIView.axaml @@ -1,5 +1,5 @@  0x20; + public static uint MaxProfileNameLength => 0x20; public bool IsDeletable => _profile.UserId != AccountManager.DefaultUserId; public UserEditorView() @@ -39,17 +39,17 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var args = ((NavigationDialogHost parent, UserProfile profile, bool isNewUser))arg.Parameter; - _isNewUser = args.isNewUser; - _profile = args.profile; + var (parent, profile, isNewUser) = ((NavigationDialogHost parent, UserProfile profile, bool isNewUser))arg.Parameter; + _isNewUser = isNewUser; + _profile = profile; TempProfile = new TempProfile(_profile); - _parent = args.parent; + _parent = parent; break; } ((ContentDialog)_parent.Parent).Title = $"{LocaleManager.Instance[LocaleKeys.UserProfileWindowTitle]} - " + - $"{ (_isNewUser ? LocaleManager.Instance[LocaleKeys.UserEditorTitleCreate] : LocaleManager.Instance[LocaleKeys.UserEditorTitle])}"; + $"{(_isNewUser ? LocaleManager.Instance[LocaleKeys.UserEditorTitleCreate] : LocaleManager.Instance[LocaleKeys.UserEditorTitle])}"; DataContext = TempProfile; @@ -162,4 +162,4 @@ namespace Ryujinx.Ava.UI.Views.User } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs b/src/Ryujinx.Ava/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs index 7c9191ab2..b6376866d 100644 --- a/src/Ryujinx.Ava/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/User/UserFirmwareAvatarSelectorView.axaml.cs @@ -11,6 +11,7 @@ using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using System.IO; +using Image = SixLabors.ImageSharp.Image; namespace Ryujinx.Ava.UI.Views.User { @@ -70,7 +71,7 @@ namespace Ryujinx.Ava.UI.Views.User if (ViewModel.SelectedImage != null) { MemoryStream streamJpg = new(); - SixLabors.ImageSharp.Image avatarImage = SixLabors.ImageSharp.Image.Load(ViewModel.SelectedImage, new PngDecoder()); + Image avatarImage = Image.Load(ViewModel.SelectedImage, new PngDecoder()); avatarImage.Mutate(x => x.BackgroundColor(new Rgba32( ViewModel.BackgroundColor.R, @@ -85,4 +86,4 @@ namespace Ryujinx.Ava.UI.Views.User } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/User/UserProfileImageSelectorView.axaml.cs b/src/Ryujinx.Ava/UI/Views/User/UserProfileImageSelectorView.axaml.cs index 18f76f805..26b77dcdc 100644 --- a/src/Ryujinx.Ava/UI/Views/User/UserProfileImageSelectorView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/User/UserProfileImageSelectorView.axaml.cs @@ -67,7 +67,7 @@ namespace Ryujinx.Ava.UI.Views.User dialog.Filters.Add(new FileDialogFilter { Name = LocaleManager.Instance[LocaleKeys.AllSupportedFormats], - Extensions = { "jpg", "jpeg", "png", "bmp" } + Extensions = { "jpg", "jpeg", "png", "bmp" }, }); dialog.Filters.Add(new FileDialogFilter { Name = "JPEG", Extensions = { "jpg", "jpeg" } }); dialog.Filters.Add(new FileDialogFilter { Name = "PNG", Extensions = { "png" } }); @@ -108,17 +108,15 @@ namespace Ryujinx.Ava.UI.Views.User private static byte[] ProcessProfileImage(byte[] buffer) { - using (Image image = Image.Load(buffer)) - { - image.Mutate(x => x.Resize(256, 256)); + using Image image = Image.Load(buffer); - using (MemoryStream streamJpg = new()) - { - image.SaveAsJpeg(streamJpg); + image.Mutate(x => x.Resize(256, 256)); - return streamJpg.ToArray(); - } - } + using MemoryStream streamJpg = new(); + + image.SaveAsJpeg(streamJpg); + + return streamJpg.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/User/UserRecovererView.axaml.cs b/src/Ryujinx.Ava/UI/Views/User/UserRecovererView.axaml.cs index 0c53e53d7..31934349d 100644 --- a/src/Ryujinx.Ava/UI/Views/User/UserRecovererView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/User/UserRecovererView.axaml.cs @@ -48,4 +48,4 @@ namespace Ryujinx.Ava.UI.Views.User _parent?.RecoverLostAccounts(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/User/UserSaveManagerView.axaml.cs b/src/Ryujinx.Ava/UI/Views/User/UserSaveManagerView.axaml.cs index 08fef27d0..00a229fae 100644 --- a/src/Ryujinx.Ava/UI/Views/User/UserSaveManagerView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/User/UserSaveManagerView.axaml.cs @@ -18,6 +18,7 @@ using Ryujinx.HLE.HOS.Services.Account.Acc; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; +using Button = Avalonia.Controls.Button; using UserId = LibHac.Fs.UserId; namespace Ryujinx.Ava.UI.Views.User @@ -47,12 +48,12 @@ namespace Ryujinx.Ava.UI.Views.User switch (arg.NavigationMode) { case NavigationMode.New: - var args = ((NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem))arg.Parameter; - _accountManager = args.accountManager; - _horizonClient = args.client; - _virtualFileSystem = args.virtualFileSystem; + var (parent, accountManager, client, virtualFileSystem) = ((NavigationDialogHost parent, AccountManager accountManager, HorizonClient client, VirtualFileSystem virtualFileSystem))arg.Parameter; + _accountManager = accountManager; + _horizonClient = client; + _virtualFileSystem = virtualFileSystem; - _parent = args.parent; + _parent = parent; break; } @@ -94,7 +95,7 @@ namespace Ryujinx.Ava.UI.Views.User var save = saveDataInfo[i]; if (save.ProgramId.Value != 0) { - var saveModel = new SaveModel(save, _virtualFileSystem); + var saveModel = new SaveModel(save); saves.Add(saveModel); } } @@ -114,7 +115,7 @@ namespace Ryujinx.Ava.UI.Views.User private void OpenLocation(object sender, RoutedEventArgs e) { - if (sender is Avalonia.Controls.Button button) + if (sender is Button button) { if (button.DataContext is SaveModel saveModel) { @@ -125,7 +126,7 @@ namespace Ryujinx.Ava.UI.Views.User private async void Delete(object sender, RoutedEventArgs e) { - if (sender is Avalonia.Controls.Button button) + if (sender is Button button) { if (button.DataContext is SaveModel saveModel) { @@ -144,4 +145,4 @@ namespace Ryujinx.Ava.UI.Views.User } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Views/User/UserSelectorView.axaml.cs b/src/Ryujinx.Ava/UI/Views/User/UserSelectorView.axaml.cs index aa89fea9e..fa3383aa9 100644 --- a/src/Ryujinx.Ava/UI/Views/User/UserSelectorView.axaml.cs +++ b/src/Ryujinx.Ava/UI/Views/User/UserSelectorView.axaml.cs @@ -5,8 +5,9 @@ using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Navigation; using Ryujinx.Ava.Common.Locale; using Ryujinx.Ava.UI.Controls; +using Ryujinx.Ava.UI.Models; using Ryujinx.Ava.UI.ViewModels; -using UserProfile = Ryujinx.Ava.UI.Models.UserProfile; +using Button = Avalonia.Controls.Button; namespace Ryujinx.Ava.UI.Views.User { @@ -101,7 +102,7 @@ namespace Ryujinx.Ava.UI.Views.User private void EditUser(object sender, RoutedEventArgs e) { - if (sender is Avalonia.Controls.Button button) + if (sender is Button button) { if (button.DataContext is UserProfile userProfile) { @@ -125,4 +126,4 @@ namespace Ryujinx.Ava.UI.Views.User ((ContentDialog)_parent.Parent).Hide(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/AboutWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/AboutWindow.axaml.cs index 36a28605f..ca1c40350 100644 --- a/src/Ryujinx.Ava/UI/Windows/AboutWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/AboutWindow.axaml.cs @@ -1,6 +1,7 @@ using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.Layout; using Avalonia.Styling; using FluentAvalonia.UI.Controls; using Ryujinx.Ava.Common.Locale; @@ -25,17 +26,17 @@ namespace Ryujinx.Ava.UI.Windows { ContentDialog contentDialog = new() { - PrimaryButtonText = "", + PrimaryButtonText = "", SecondaryButtonText = "", - CloseButtonText = LocaleManager.Instance[LocaleKeys.UserProfilesClose], - Content = new AboutWindow() + CloseButtonText = LocaleManager.Instance[LocaleKeys.UserProfilesClose], + Content = new AboutWindow(), }; Style closeButton = new(x => x.Name("CloseButton")); closeButton.Setters.Add(new Setter(WidthProperty, 80d)); Style closeButtonParent = new(x => x.Name("CommandSpace")); - closeButtonParent.Setters.Add(new Setter(HorizontalAlignmentProperty, Avalonia.Layout.HorizontalAlignment.Right)); + closeButtonParent.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Right)); contentDialog.Styles.Add(closeButton); contentDialog.Styles.Add(closeButtonParent); @@ -59,4 +60,4 @@ namespace Ryujinx.Ava.UI.Windows } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/AmiiboWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/AmiiboWindow.axaml.cs index 206d0a7ea..57106638a 100644 --- a/src/Ryujinx.Ava/UI/Windows/AmiiboWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/AmiiboWindow.axaml.cs @@ -9,9 +9,10 @@ namespace Ryujinx.Ava.UI.Windows { public AmiiboWindow(bool showAll, string lastScannedAmiiboId, string titleId) { - ViewModel = new AmiiboWindowViewModel(this, lastScannedAmiiboId, titleId); - - ViewModel.ShowAllAmiibo = showAll; + ViewModel = new AmiiboWindowViewModel(this, lastScannedAmiiboId, titleId) + { + ShowAllAmiibo = showAll, + }; DataContext = ViewModel; @@ -56,4 +57,4 @@ namespace Ryujinx.Ava.UI.Windows Close(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/CheatWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/CheatWindow.axaml.cs index f5bba7d2d..df6b123bd 100644 --- a/src/Ryujinx.Ava/UI/Windows/CheatWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/CheatWindow.axaml.cs @@ -1,11 +1,12 @@ -using Avalonia; -using Avalonia.Collections; +using Avalonia.Collections; using Ryujinx.Ava.Common.Locale; using Ryujinx.Ava.UI.Models; using Ryujinx.HLE.FileSystem; using Ryujinx.HLE.HOS; using Ryujinx.Ui.App.Common; +using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; @@ -36,16 +37,16 @@ namespace Ryujinx.Ava.UI.Windows Heading = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.CheatWindowHeading, titleName, titleId.ToUpper()); BuildId = ApplicationData.GetApplicationBuildId(virtualFileSystem, titlePath); - + InitializeComponent(); string modsBasePath = ModLoader.GetModsBasePath(); string titleModsPath = ModLoader.GetTitleDir(modsBasePath, titleId); - ulong titleIdValue = ulong.Parse(titleId, System.Globalization.NumberStyles.HexNumber); + ulong titleIdValue = ulong.Parse(titleId, NumberStyles.HexNumber); _enabledCheatsPath = Path.Combine(titleModsPath, "cheats", "enabled.txt"); - string[] enabled = { }; + string[] enabled = Array.Empty(); if (File.Exists(_enabledCheatsPath)) { @@ -60,7 +61,6 @@ namespace Ryujinx.Ava.UI.Windows string currentCheatFile = string.Empty; string buildId = string.Empty; - string parentPath = string.Empty; CheatsList currentGroup = null; @@ -69,7 +69,7 @@ namespace Ryujinx.Ava.UI.Windows if (cheat.Path.FullName != currentCheatFile) { currentCheatFile = cheat.Path.FullName; - parentPath = currentCheatFile.Replace(titleModsPath, ""); + string parentPath = currentCheatFile.Replace(titleModsPath, ""); buildId = Path.GetFileNameWithoutExtension(currentCheatFile).ToUpper(); currentGroup = new CheatsList(buildId, parentPath); @@ -89,7 +89,7 @@ namespace Ryujinx.Ava.UI.Windows } DataContext = this; - + Title = $"Ryujinx {Program.Version} - " + LocaleManager.Instance[LocaleKeys.CheatWindowTitle]; } @@ -100,7 +100,7 @@ namespace Ryujinx.Ava.UI.Windows return; } - List enabledCheats = new List(); + List enabledCheats = new(); foreach (var cheats in LoadedCheats) { @@ -120,4 +120,4 @@ namespace Ryujinx.Ava.UI.Windows Close(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/ContentDialogOverlayWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/ContentDialogOverlayWindow.axaml.cs index 3f77124d9..a33ee518b 100644 --- a/src/Ryujinx.Ava/UI/Windows/ContentDialogOverlayWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/ContentDialogOverlayWindow.axaml.cs @@ -1,7 +1,8 @@ -using Avalonia; using Avalonia.Controls; -using Avalonia.Markup.Xaml; using Avalonia.Media; +#if DEBUG +using Avalonia; +#endif namespace Ryujinx.Ava.UI.Windows { @@ -22,4 +23,4 @@ namespace Ryujinx.Ava.UI.Windows CanResize = false; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/DownloadableContentManagerWindow.axaml b/src/Ryujinx.Ava/UI/Windows/DownloadableContentManagerWindow.axaml index fe446fb3e..f4ba4f9c9 100644 --- a/src/Ryujinx.Ava/UI/Windows/DownloadableContentManagerWindow.axaml +++ b/src/Ryujinx.Ava/UI/Windows/DownloadableContentManagerWindow.axaml @@ -89,8 +89,8 @@ - - + + x.OfType().Name("DialogSpace").Child().OfType()); @@ -112,4 +112,4 @@ namespace Ryujinx.Ava.UI.Windows } } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/IconColorPicker.cs b/src/Ryujinx.Ava/UI/Windows/IconColorPicker.cs index a4c6287f3..4c75a5ff9 100644 --- a/src/Ryujinx.Ava/UI/Windows/IconColorPicker.cs +++ b/src/Ryujinx.Ava/UI/Windows/IconColorPicker.cs @@ -68,8 +68,10 @@ namespace Ryujinx.Ava.UI.Windows int w8 = w << 8; int h8 = image.Height << 8; +#pragma warning disable IDE0059 // Unnecessary assignment int xStep = w8 / ColorsPerLine; int yStep = h8 / ColorsPerLine; +#pragma warning restore IDE0059 int i = 0; int maxHitCount = 0; diff --git a/src/Ryujinx.Ava/UI/Windows/MainWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/MainWindow.axaml.cs index 66988c4b3..d79bdc56a 100644 --- a/src/Ryujinx.Ava/UI/Windows/MainWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/MainWindow.axaml.cs @@ -155,7 +155,7 @@ namespace Ryujinx.Ava.UI.Windows Dispatcher.UIThread.Post(() => { - ViewModel.StatusBarProgressValue = e.NumAppsLoaded; + ViewModel.StatusBarProgressValue = e.NumAppsLoaded; ViewModel.StatusBarProgressMaximum = e.NumAppsFound; if (e.NumAppsFound == 0) @@ -323,7 +323,7 @@ namespace Ryujinx.Ava.UI.Windows ShowKeyErrorOnLoad = false; Dispatcher.UIThread.Post(async () => await - UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys, this)); + UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys)); } if (OperatingSystem.IsLinux() && LinuxHelper.VmMaxMapCount < LinuxHelper.RecommendedVmMaxMapCount) @@ -373,24 +373,26 @@ namespace Ryujinx.Ava.UI.Windows private void SetWindowSizePosition() { - PixelPoint SavedPoint = new PixelPoint(ConfigurationState.Instance.Ui.WindowStartup.WindowPositionX, + PixelPoint savedPoint = new(ConfigurationState.Instance.Ui.WindowStartup.WindowPositionX, ConfigurationState.Instance.Ui.WindowStartup.WindowPositionY); ViewModel.WindowHeight = ConfigurationState.Instance.Ui.WindowStartup.WindowSizeHeight * Program.WindowScaleFactor; ViewModel.WindowWidth = ConfigurationState.Instance.Ui.WindowStartup.WindowSizeWidth * Program.WindowScaleFactor; ViewModel.WindowState = ConfigurationState.Instance.Ui.WindowStartup.WindowMaximized.Value is true ? WindowState.Maximized : WindowState.Normal; - - if (CheckScreenBounds(SavedPoint)) - { - Position = SavedPoint; - } - else WindowStartupLocation = WindowStartupLocation.CenterScreen; + if (CheckScreenBounds(savedPoint)) + { + Position = savedPoint; + } + else + { + WindowStartupLocation = WindowStartupLocation.CenterScreen; + } } private bool CheckScreenBounds(PixelPoint configPoint) - { + { for (int i = 0; i < Screens.ScreenCount; i++) { if (Screens.All[i].Bounds.Contains(configPoint)) @@ -399,7 +401,7 @@ namespace Ryujinx.Ava.UI.Windows } } - Logger.Warning?.Print(LogClass.Application, $"Failed to find valid start-up coordinates. Defaulting to primary monitor center."); + Logger.Warning?.Print(LogClass.Application, "Failed to find valid start-up coordinates. Defaulting to primary monitor center."); return false; } @@ -425,10 +427,7 @@ namespace Ryujinx.Ava.UI.Windows private void SetMainContent(Control content = null) { - if (content == null) - { - content = GameLibrary; - } + content ??= GameLibrary; if (MainContent.Content != content) { @@ -438,21 +437,25 @@ namespace Ryujinx.Ava.UI.Windows public static void UpdateGraphicsConfig() { +#pragma warning disable IDE0055 // Disable formatting GraphicsConfig.ResScale = ConfigurationState.Instance.Graphics.ResScale == -1 ? ConfigurationState.Instance.Graphics.ResScaleCustom : ConfigurationState.Instance.Graphics.ResScale; GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy; GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath; GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache; GraphicsConfig.EnableTextureRecompression = ConfigurationState.Instance.Graphics.EnableTextureRecompression; GraphicsConfig.EnableMacroHLE = ConfigurationState.Instance.Graphics.EnableMacroHLE; +#pragma warning restore IDE0055 } public void LoadHotKeys() { +#pragma warning disable IDE0055 // Disable formatting HotKeyManager.SetHotKey(FullscreenHotKey, new KeyGesture(Key.Enter, KeyModifiers.Alt)); HotKeyManager.SetHotKey(FullscreenHotKey2, new KeyGesture(Key.F11)); HotKeyManager.SetHotKey(FullscreenHotKeyMacOS, new KeyGesture(Key.F, KeyModifiers.Control | KeyModifiers.Meta)); HotKeyManager.SetHotKey(DockToggleHotKey, new KeyGesture(Key.F9)); HotKeyManager.SetHotKey(ExitHotKey, new KeyGesture(Key.Escape)); +#pragma warning restore IDE0055 } private void VolumeStatus_CheckedChanged(object sender, SplitButtonClickEventArgs e) @@ -536,8 +539,8 @@ namespace Ryujinx.Ava.UI.Windows ViewModel.Applications.Clear(); StatusBarView.LoadProgressBar.IsVisible = true; - ViewModel.StatusBarProgressMaximum = 0; - ViewModel.StatusBarProgressValue = 0; + ViewModel.StatusBarProgressMaximum = 0; + ViewModel.StatusBarProgressValue = 0; LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarGamesLoaded, 0, 0); }); @@ -559,4 +562,4 @@ namespace Ryujinx.Ava.UI.Windows _isLoading = false; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml b/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml index a44cbfe7d..4b248db79 100644 --- a/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml +++ b/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml @@ -34,7 +34,7 @@ IsVisible="False" KeyboardNavigation.IsTabStop="False"/> - + @@ -125,4 +125,4 @@ Command="{ReflectionBinding ApplyButton}" /> - \ No newline at end of file + diff --git a/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml.cs index bdf7e94d8..518c2d328 100644 --- a/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/SettingsWindow.axaml.cs @@ -16,7 +16,7 @@ namespace Ryujinx.Ava.UI.Windows { Title = $"Ryujinx {Program.Version} - {LocaleManager.Instance[LocaleKeys.Settings]}"; - ViewModel = new SettingsViewModel(virtualFileSystem, contentManager); + ViewModel = new SettingsViewModel(virtualFileSystem, contentManager); DataContext = ViewModel; ViewModel.CloseWindow += Close; @@ -28,7 +28,7 @@ namespace Ryujinx.Ava.UI.Windows public SettingsWindow() { - ViewModel = new SettingsViewModel(); + ViewModel = new SettingsViewModel(); DataContext = ViewModel; InitializeComponent(); @@ -100,4 +100,4 @@ namespace Ryujinx.Ava.UI.Windows base.OnClosing(e); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/StyleableWindow.cs b/src/Ryujinx.Ava/UI/Windows/StyleableWindow.cs index a157f1547..ca23a5ba3 100644 --- a/src/Ryujinx.Ava/UI/Windows/StyleableWindow.cs +++ b/src/Ryujinx.Ava/UI/Windows/StyleableWindow.cs @@ -2,6 +2,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Media.Imaging; using Avalonia.Platform; +using Ryujinx.Ui.Common.Configuration; using System; using System.IO; using System.Reflection; @@ -17,7 +18,7 @@ namespace Ryujinx.Ava.UI.Windows WindowStartupLocation = WindowStartupLocation.CenterOwner; TransparencyLevelHint = WindowTransparencyLevel.None; - using Stream stream = Assembly.GetAssembly(typeof(Ryujinx.Ui.Common.Configuration.ConfigurationState)).GetManifestResourceStream("Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); + using Stream stream = Assembly.GetAssembly(typeof(ConfigurationState)).GetManifestResourceStream("Ryujinx.Ui.Common.Resources.Logo_Ryujinx.png"); Icon = new WindowIcon(stream); stream.Position = 0; @@ -36,4 +37,4 @@ namespace Ryujinx.Ava.UI.Windows ExtendClientAreaChromeHints = ExtendClientAreaChromeHints.SystemChrome | ExtendClientAreaChromeHints.OSXThickTitleBar; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Ava/UI/Windows/TitleUpdateWindow.axaml.cs b/src/Ryujinx.Ava/UI/Windows/TitleUpdateWindow.axaml.cs index 153ce95d2..f4fcad319 100644 --- a/src/Ryujinx.Ava/UI/Windows/TitleUpdateWindow.axaml.cs +++ b/src/Ryujinx.Ava/UI/Windows/TitleUpdateWindow.axaml.cs @@ -24,9 +24,9 @@ namespace Ryujinx.Ava.UI.Windows InitializeComponent(); } - public TitleUpdateWindow(VirtualFileSystem virtualFileSystem, ulong titleId, string titleName) + public TitleUpdateWindow(VirtualFileSystem virtualFileSystem, ulong titleId) { - DataContext = ViewModel = new TitleUpdateViewModel(virtualFileSystem, titleId, titleName); + DataContext = ViewModel = new TitleUpdateViewModel(virtualFileSystem, titleId); InitializeComponent(); } @@ -35,11 +35,11 @@ namespace Ryujinx.Ava.UI.Windows { ContentDialog contentDialog = new() { - PrimaryButtonText = "", + PrimaryButtonText = "", SecondaryButtonText = "", - CloseButtonText = "", - Content = new TitleUpdateWindow(virtualFileSystem, titleId, titleName), - Title = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.GameUpdateWindowHeading, titleName, titleId.ToString("X16")) + CloseButtonText = "", + Content = new TitleUpdateWindow(virtualFileSystem, titleId), + Title = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.GameUpdateWindowHeading, titleName, titleId.ToString("X16")), }; Style bottomBorder = new(x => x.OfType().Name("DialogSpace").Child().OfType()); @@ -93,4 +93,4 @@ namespace Ryujinx.Ava.UI.Windows ViewModel.SortUpdates(); } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/AsyncWorkQueue.cs b/src/Ryujinx.Common/AsyncWorkQueue.cs index 746ef4cac..e9f758985 100644 --- a/src/Ryujinx.Common/AsyncWorkQueue.cs +++ b/src/Ryujinx.Common/AsyncWorkQueue.cs @@ -25,7 +25,7 @@ namespace Ryujinx.Common _workerThread = new Thread(DoWork) { Name = name, - IsBackground = true + IsBackground = true, }; _workerThread.Start(); } diff --git a/src/Ryujinx.Common/Collections/IntervalTree.cs b/src/Ryujinx.Common/Collections/IntervalTree.cs index b5188cc7e..2ea260a5f 100644 --- a/src/Ryujinx.Common/Collections/IntervalTree.cs +++ b/src/Ryujinx.Common/Collections/IntervalTree.cs @@ -7,9 +7,9 @@ namespace Ryujinx.Common.Collections /// /// An Augmented Interval Tree based off of the "TreeDictionary"'s Red-Black Tree. Allows fast overlap checking of ranges. /// - /// Key - /// Value - public class IntervalTree : IntrusiveRedBlackTreeImpl> where K : IComparable + /// Key + /// Value + public class IntervalTree : IntrusiveRedBlackTreeImpl> where TKey : IComparable { private const int ArrayGrowthSize = 32; @@ -22,11 +22,11 @@ namespace Ryujinx.Common.Collections /// Overlaps array to place results in /// Number of values found /// is null - public int Get(K key, ref V[] overlaps) + public int Get(TKey key, ref TValue[] overlaps) { ArgumentNullException.ThrowIfNull(key); - IntervalTreeNode node = GetNode(key); + IntervalTreeNode node = GetNode(key); if (node == null) { @@ -39,7 +39,7 @@ namespace Ryujinx.Common.Collections } int overlapsCount = 0; - foreach (RangeNode value in node.Values) + foreach (RangeNode value in node.Values) { overlaps[overlapsCount++] = value.Value; } @@ -56,7 +56,7 @@ namespace Ryujinx.Common.Collections /// Index to start writing results into the array. Defaults to 0 /// Number of values found /// or is null - public int Get(K start, K end, ref V[] overlaps, int overlapCount = 0) + public int Get(TKey start, TKey end, ref TValue[] overlaps, int overlapCount = 0) { ArgumentNullException.ThrowIfNull(start); ArgumentNullException.ThrowIfNull(end); @@ -73,7 +73,7 @@ namespace Ryujinx.Common.Collections /// End of the range to insert /// Value to add /// , or are null - public void Add(K start, K end, V value) + public void Add(TKey start, TKey end, TValue value) { ArgumentNullException.ThrowIfNull(start); ArgumentNullException.ThrowIfNull(end); @@ -89,7 +89,7 @@ namespace Ryujinx.Common.Collections /// Value to remove /// is null /// Number of deleted values - public int Remove(K key, V value) + public int Remove(TKey key, TValue value) { ArgumentNullException.ThrowIfNull(key); @@ -104,9 +104,9 @@ namespace Ryujinx.Common.Collections /// Adds all the nodes in the dictionary into . /// /// A list of all RangeNodes sorted by Key Order - public List> AsList() + public List> AsList() { - List> list = new List>(); + List> list = new(); AddToList(Root, list); @@ -122,7 +122,7 @@ namespace Ryujinx.Common.Collections /// /// The node to search for RangeNodes within /// The list to add RangeNodes to - private void AddToList(IntervalTreeNode node, List> list) + private void AddToList(IntervalTreeNode node, List> list) { if (node == null) { @@ -142,11 +142,11 @@ namespace Ryujinx.Common.Collections /// Key of the node to get /// Node reference in the tree /// is null - private IntervalTreeNode GetNode(K key) + private IntervalTreeNode GetNode(TKey key) { ArgumentNullException.ThrowIfNull(key); - IntervalTreeNode node = Root; + IntervalTreeNode node = Root; while (node != null) { int cmp = key.CompareTo(node.Start); @@ -173,7 +173,7 @@ namespace Ryujinx.Common.Collections /// End of the range /// Overlaps array to place results in /// Overlaps count to update - private void GetValues(IntervalTreeNode node, K start, K end, ref V[] overlaps, ref int overlapCount) + private void GetValues(IntervalTreeNode node, TKey start, TKey end, ref TValue[] overlaps, ref int overlapCount) { if (node == null || start.CompareTo(node.Max) >= 0) { @@ -188,7 +188,7 @@ namespace Ryujinx.Common.Collections if (start.CompareTo(node.End) < 0) { // Contains this node. Add overlaps to list. - foreach (RangeNode overlap in node.Values) + foreach (RangeNode overlap in node.Values) { if (start.CompareTo(overlap.End) < 0) { @@ -212,9 +212,9 @@ namespace Ryujinx.Common.Collections /// Start of the range to insert /// End of the range to insert /// Value to insert - private void Insert(K start, K end, V value) + private void Insert(TKey start, TKey end, TValue value) { - IntervalTreeNode newNode = BSTInsert(start, end, value); + IntervalTreeNode newNode = BSTInsert(start, end, value); RestoreBalanceAfterInsertion(newNode); } @@ -223,10 +223,10 @@ namespace Ryujinx.Common.Collections /// This should only be called if the max increases - not for rebalancing or removals. /// /// The node to start propagating from - private void PropagateIncrease(IntervalTreeNode node) + private static void PropagateIncrease(IntervalTreeNode node) { - K max = node.Max; - IntervalTreeNode ptr = node; + TKey max = node.Max; + IntervalTreeNode ptr = node; while ((ptr = ptr.Parent) != null) { @@ -246,13 +246,13 @@ namespace Ryujinx.Common.Collections /// This fully recalculates the max value from all children when there is potential for it to decrease. /// /// The node to start propagating from - private void PropagateFull(IntervalTreeNode node) + private static void PropagateFull(IntervalTreeNode node) { - IntervalTreeNode ptr = node; + IntervalTreeNode ptr = node; do { - K max = ptr.End; + TKey max = ptr.End; if (ptr.Left != null && ptr.Left.Max.CompareTo(max) > 0) { @@ -278,10 +278,10 @@ namespace Ryujinx.Common.Collections /// End of the range to insert /// Value to insert /// The inserted Node - private IntervalTreeNode BSTInsert(K start, K end, V value) + private IntervalTreeNode BSTInsert(TKey start, TKey end, TValue value) { - IntervalTreeNode parent = null; - IntervalTreeNode node = Root; + IntervalTreeNode parent = null; + IntervalTreeNode node = Root; while (node != null) { @@ -297,7 +297,7 @@ namespace Ryujinx.Common.Collections } else { - node.Values.Add(new RangeNode(start, end, value)); + node.Values.Add(new RangeNode(start, end, value)); if (end.CompareTo(node.End) > 0) { @@ -313,7 +313,7 @@ namespace Ryujinx.Common.Collections return node; } } - IntervalTreeNode newNode = new IntervalTreeNode(start, end, value, parent); + IntervalTreeNode newNode = new(start, end, value, parent); if (newNode.Parent == null) { Root = newNode; @@ -338,9 +338,9 @@ namespace Ryujinx.Common.Collections /// Key to search for /// Value to delete /// Number of deleted values - private int Delete(K key, V value) + private int Delete(TKey key, TValue value) { - IntervalTreeNode nodeToDelete = GetNode(key); + IntervalTreeNode nodeToDelete = GetNode(key); if (nodeToDelete == null) { @@ -362,7 +362,7 @@ namespace Ryujinx.Common.Collections return removed; } - IntervalTreeNode replacementNode; + IntervalTreeNode replacementNode; if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null) { @@ -373,7 +373,7 @@ namespace Ryujinx.Common.Collections replacementNode = PredecessorOf(nodeToDelete); } - IntervalTreeNode tmp = LeftOf(replacementNode) ?? RightOf(replacementNode); + IntervalTreeNode tmp = LeftOf(replacementNode) ?? RightOf(replacementNode); if (tmp != null) { @@ -413,7 +413,7 @@ namespace Ryujinx.Common.Collections #endregion - protected override void RotateLeft(IntervalTreeNode node) + protected override void RotateLeft(IntervalTreeNode node) { if (node != null) { @@ -423,7 +423,7 @@ namespace Ryujinx.Common.Collections } } - protected override void RotateRight(IntervalTreeNode node) + protected override void RotateRight(IntervalTreeNode node) { if (node != null) { @@ -433,7 +433,7 @@ namespace Ryujinx.Common.Collections } } - public bool ContainsKey(K key) + public bool ContainsKey(TKey key) { ArgumentNullException.ThrowIfNull(key); @@ -444,15 +444,15 @@ namespace Ryujinx.Common.Collections /// /// Represents a value and its start and end keys. /// - /// - /// - public readonly struct RangeNode + /// + /// + public readonly struct RangeNode { - public readonly K Start; - public readonly K End; - public readonly V Value; + public readonly TKey Start; + public readonly TKey End; + public readonly TValue Value; - public RangeNode(K start, K end, V value) + public RangeNode(TKey start, TKey end, TValue value) { Start = start; End = end; @@ -463,36 +463,36 @@ namespace Ryujinx.Common.Collections /// /// Represents a node in the IntervalTree which contains start and end keys of type K, and a value of generic type V. /// - /// Key type of the node - /// Value type of the node - public class IntervalTreeNode : IntrusiveRedBlackTreeNode> + /// Key type of the node + /// Value type of the node + public class IntervalTreeNode : IntrusiveRedBlackTreeNode> { /// /// The start of the range. /// - internal K Start; + internal TKey Start; /// /// The end of the range - maximum of all in the Values list. /// - internal K End; + internal TKey End; /// /// The maximum end value of this node and all its children. /// - internal K Max; + internal TKey Max; /// /// Values contained on the node that shares a common Start value. /// - internal List> Values; + internal List> Values; - internal IntervalTreeNode(K start, K end, V value, IntervalTreeNode parent) + internal IntervalTreeNode(TKey start, TKey end, TValue value, IntervalTreeNode parent) { Start = start; End = end; Max = end; - Values = new List> { new RangeNode(start, end, value) }; + Values = new List> { new RangeNode(start, end, value) }; Parent = parent; } } diff --git a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs index 0063d91e4..9e56f707b 100644 --- a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs +++ b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTree.cs @@ -180,11 +180,6 @@ namespace Ryujinx.Common.Collections parent.Right = child; } - if (ParentOf(element) == old) - { - parent = element; - } - element.Color = old.Color; element.Left = old.Left; element.Right = old.Right; @@ -258,11 +253,11 @@ namespace Ryujinx.Common.Collections /// Tree to search at /// Key of the node to be found /// Node that is equal to - public static N GetNodeByKey(this IntrusiveRedBlackTree tree, K key) - where N : IntrusiveRedBlackTreeNode, IComparable, IComparable - where K : struct + public static TNode GetNodeByKey(this IntrusiveRedBlackTree tree, TKey key) + where TNode : IntrusiveRedBlackTreeNode, IComparable, IComparable + where TKey : struct { - N node = tree.RootNode; + TNode node = tree.RootNode; while (node != null) { int cmp = node.CompareTo(key); diff --git a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs index bcb2e2a23..49f97223a 100644 --- a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs +++ b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeImpl.cs @@ -10,7 +10,7 @@ namespace Ryujinx.Common.Collections { protected const bool Black = true; protected const bool Red = false; - protected T Root = null; + protected T Root; internal T RootNode => Root; diff --git a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs index 7143240da..8480d51ad 100644 --- a/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs +++ b/src/Ryujinx.Common/Collections/IntrusiveRedBlackTreeNode.cs @@ -13,4 +13,4 @@ namespace Ryujinx.Common.Collections public T Predecessor => IntrusiveRedBlackTreeImpl.PredecessorOf((T)this); public T Successor => IntrusiveRedBlackTreeImpl.SuccessorOf((T)this); } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Collections/TreeDictionary.cs b/src/Ryujinx.Common/Collections/TreeDictionary.cs index d118a30cc..ff1794883 100644 --- a/src/Ryujinx.Common/Collections/TreeDictionary.cs +++ b/src/Ryujinx.Common/Collections/TreeDictionary.cs @@ -8,9 +8,9 @@ namespace Ryujinx.Common.Collections /// /// Dictionary that provides the ability for O(logN) Lookups for keys that exist in the Dictionary, and O(logN) lookups for keys immediately greater than or less than a specified key. /// - /// Key - /// Value - public class TreeDictionary : IntrusiveRedBlackTreeImpl>, IDictionary where K : IComparable + /// Key + /// Value + public class TreeDictionary : IntrusiveRedBlackTreeImpl>, IDictionary where TKey : IComparable { #region Public Methods @@ -20,11 +20,11 @@ namespace Ryujinx.Common.Collections /// Key of the node value to get /// Value associated w/ /// is null - public V Get(K key) + public TValue Get(TKey key) { ArgumentNullException.ThrowIfNull(key); - Node node = GetNode(key); + Node node = GetNode(key); if (node == null) { @@ -42,7 +42,7 @@ namespace Ryujinx.Common.Collections /// Key of the node to add /// Value of the node to add /// or are null - public void Add(K key, V value) + public void Add(TKey key, TValue value) { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(value); @@ -55,7 +55,7 @@ namespace Ryujinx.Common.Collections /// /// Key of the node to remove /// is null - public void Remove(K key) + public void Remove(TKey key) { ArgumentNullException.ThrowIfNull(key); @@ -71,9 +71,9 @@ namespace Ryujinx.Common.Collections /// Key for which to find the floor value of /// Key of node immediately less than /// is null - public K Floor(K key) + public TKey Floor(TKey key) { - Node node = FloorNode(key); + Node node = FloorNode(key); if (node != null) { return node.Key; @@ -87,9 +87,9 @@ namespace Ryujinx.Common.Collections /// Key for which to find the ceiling node of /// Key of node immediately greater than /// is null - public K Ceiling(K key) + public TKey Ceiling(TKey key) { - Node node = CeilingNode(key); + Node node = CeilingNode(key); if (node != null) { return node.Key; @@ -102,12 +102,12 @@ namespace Ryujinx.Common.Collections /// /// Key to find the successor of /// Value - public K SuccessorOf(K key) + public TKey SuccessorOf(TKey key) { - Node node = GetNode(key); + Node node = GetNode(key); if (node != null) { - Node successor = SuccessorOf(node); + Node successor = SuccessorOf(node); return successor != null ? successor.Key : default; } @@ -119,12 +119,12 @@ namespace Ryujinx.Common.Collections /// /// Key to find the predecessor of /// Value - public K PredecessorOf(K key) + public TKey PredecessorOf(TKey key) { - Node node = GetNode(key); + Node node = GetNode(key); if (node != null) { - Node predecessor = PredecessorOf(node); + Node predecessor = PredecessorOf(node); return predecessor != null ? predecessor.Key : default; } @@ -137,19 +137,19 @@ namespace Ryujinx.Common.Collections /// The key/value pairs will be added in Level Order. /// /// List to add the tree pairs into - public List> AsLevelOrderList() + public List> AsLevelOrderList() { - List> list = new List>(); + List> list = new(); - Queue> nodes = new Queue>(); + Queue> nodes = new(); if (this.Root != null) { nodes.Enqueue(this.Root); } - while (nodes.TryDequeue(out Node node)) + while (nodes.TryDequeue(out Node node)) { - list.Add(new KeyValuePair(node.Key, node.Value)); + list.Add(new KeyValuePair(node.Key, node.Value)); if (node.Left != null) { nodes.Enqueue(node.Left); @@ -166,9 +166,9 @@ namespace Ryujinx.Common.Collections /// Adds all the nodes in the dictionary into . /// /// A list of all KeyValuePairs sorted by Key Order - public List> AsList() + public List> AsList() { - List> list = new List>(); + List> list = new(); AddToList(Root, list); @@ -184,7 +184,7 @@ namespace Ryujinx.Common.Collections /// /// The node to search for nodes within /// The list to add node to - private void AddToList(Node node, List> list) + private void AddToList(Node node, List> list) { if (node == null) { @@ -193,7 +193,7 @@ namespace Ryujinx.Common.Collections AddToList(node.Left, list); - list.Add(new KeyValuePair(node.Key, node.Value)); + list.Add(new KeyValuePair(node.Key, node.Value)); AddToList(node.Right, list); } @@ -204,11 +204,11 @@ namespace Ryujinx.Common.Collections /// Key of the node to get /// Node reference in the tree /// is null - private Node GetNode(K key) + private Node GetNode(TKey key) { ArgumentNullException.ThrowIfNull(key); - Node node = Root; + Node node = Root; while (node != null) { int cmp = key.CompareTo(node.Key); @@ -235,9 +235,9 @@ namespace Ryujinx.Common.Collections /// /// Key of the node to insert /// Value of the node to insert - private void Insert(K key, V value) + private void Insert(TKey key, TValue value) { - Node newNode = BSTInsert(key, value); + Node newNode = BSTInsert(key, value); RestoreBalanceAfterInsertion(newNode); } @@ -251,10 +251,10 @@ namespace Ryujinx.Common.Collections /// Key of the node to insert /// Value of the node to insert /// The inserted Node - private Node BSTInsert(K key, V value) + private Node BSTInsert(TKey key, TValue value) { - Node parent = null; - Node node = Root; + Node parent = null; + Node node = Root; while (node != null) { @@ -274,7 +274,7 @@ namespace Ryujinx.Common.Collections return node; } } - Node newNode = new Node(key, value, parent); + Node newNode = new(key, value, parent); if (newNode.Parent == null) { Root = newNode; @@ -296,14 +296,17 @@ namespace Ryujinx.Common.Collections /// /// Key of the node to delete /// The deleted Node - private Node Delete(K key) + private Node Delete(TKey key) { // O(1) Retrieval - Node nodeToDelete = GetNode(key); + Node nodeToDelete = GetNode(key); - if (nodeToDelete == null) return null; + if (nodeToDelete == null) + { + return null; + } - Node replacementNode; + Node replacementNode; if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null) { @@ -314,7 +317,7 @@ namespace Ryujinx.Common.Collections replacementNode = PredecessorOf(nodeToDelete); } - Node tmp = LeftOf(replacementNode) ?? RightOf(replacementNode); + Node tmp = LeftOf(replacementNode) ?? RightOf(replacementNode); if (tmp != null) { @@ -354,11 +357,11 @@ namespace Ryujinx.Common.Collections /// Key for which to find the floor node of /// Node whose key is immediately less than or equal to , or null if no such node is found. /// is null - private Node FloorNode(K key) + private Node FloorNode(TKey key) { ArgumentNullException.ThrowIfNull(key); - Node tmp = Root; + Node tmp = Root; while (tmp != null) { @@ -382,8 +385,8 @@ namespace Ryujinx.Common.Collections } else { - Node parent = tmp.Parent; - Node ptr = tmp; + Node parent = tmp.Parent; + Node ptr = tmp; while (parent != null && ptr == parent.Left) { ptr = parent; @@ -406,11 +409,11 @@ namespace Ryujinx.Common.Collections /// Key for which to find the ceiling node of /// Node whose key is immediately greater than or equal to , or null if no such node is found. /// is null - private Node CeilingNode(K key) + private Node CeilingNode(TKey key) { ArgumentNullException.ThrowIfNull(key); - Node tmp = Root; + Node tmp = Root; while (tmp != null) { @@ -434,8 +437,8 @@ namespace Ryujinx.Common.Collections } else { - Node parent = tmp.Parent; - Node ptr = tmp; + Node parent = tmp.Parent; + Node ptr = tmp; while (parent != null && ptr == parent.Right) { ptr = parent; @@ -457,44 +460,44 @@ namespace Ryujinx.Common.Collections #region Interface Implementations // Method descriptions are not provided as they are already included as part of the interface. - public bool ContainsKey(K key) + public bool ContainsKey(TKey key) { ArgumentNullException.ThrowIfNull(key); return GetNode(key) != null; } - bool IDictionary.Remove(K key) + bool IDictionary.Remove(TKey key) { int count = Count; Remove(key); return count > Count; } - public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { ArgumentNullException.ThrowIfNull(key); - Node node = GetNode(key); + Node node = GetNode(key); value = node != null ? node.Value : default; return node != null; } - public void Add(KeyValuePair item) + public void Add(KeyValuePair item) { ArgumentNullException.ThrowIfNull(item.Key); Add(item.Key, item.Value); } - public bool Contains(KeyValuePair item) + public bool Contains(KeyValuePair item) { if (item.Key == null) { return false; } - Node node = GetNode(item.Key); + Node node = GetNode(item.Key); if (node != null) { return node.Key.Equals(item.Key) && node.Value.Equals(item.Value); @@ -502,27 +505,27 @@ namespace Ryujinx.Common.Collections return false; } - public void CopyTo(KeyValuePair[] array, int arrayIndex) + public void CopyTo(KeyValuePair[] array, int arrayIndex) { if (arrayIndex < 0 || array.Length - arrayIndex < this.Count) { throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } - SortedList list = GetKeyValues(); + SortedList list = GetKeyValues(); int offset = 0; for (int i = arrayIndex; i < array.Length && offset < list.Count; i++) { - array[i] = new KeyValuePair(list.Keys[i], list.Values[i]); + array[i] = new KeyValuePair(list.Keys[i], list.Values[i]); offset++; } } - public bool Remove(KeyValuePair item) + public bool Remove(KeyValuePair item) { - Node node = GetNode(item.Key); + Node node = GetNode(item.Key); if (node == null) { @@ -539,7 +542,7 @@ namespace Ryujinx.Common.Collections return false; } - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { return GetKeyValues().GetEnumerator(); } @@ -549,13 +552,13 @@ namespace Ryujinx.Common.Collections return GetKeyValues().GetEnumerator(); } - public ICollection Keys => GetKeyValues().Keys; + public ICollection Keys => GetKeyValues().Keys; - public ICollection Values => GetKeyValues().Values; + public ICollection Values => GetKeyValues().Values; public bool IsReadOnly => false; - public V this[K key] + public TValue this[TKey key] { get => Get(key); set => Add(key, value); @@ -569,16 +572,16 @@ namespace Ryujinx.Common.Collections /// Returns a sorted list of all the node keys / values in the tree. /// /// List of node keys - private SortedList GetKeyValues() + private SortedList GetKeyValues() { - SortedList set = new SortedList(); - Queue> queue = new Queue>(); + SortedList set = new(); + Queue> queue = new(); if (Root != null) { queue.Enqueue(Root); } - while (queue.TryDequeue(out Node node)) + while (queue.TryDequeue(out Node node)) { set.Add(node.Key, node.Value); if (null != node.Left) @@ -600,14 +603,14 @@ namespace Ryujinx.Common.Collections /// /// Represents a node in the TreeDictionary which contains a key and value of generic type K and V, respectively. /// - /// Key of the node - /// Value of the node - public class Node : IntrusiveRedBlackTreeNode> where K : IComparable + /// Key of the node + /// Value of the node + public class Node : IntrusiveRedBlackTreeNode> where TKey : IComparable { - internal K Key; - internal V Value; + internal TKey Key; + internal TValue Value; - internal Node(K key, V value, Node parent) + internal Node(TKey key, TValue value, Node parent) { Key = key; Value = value; diff --git a/src/Ryujinx.Common/Configuration/AntiAliasing.cs b/src/Ryujinx.Common/Configuration/AntiAliasing.cs index 159108ae4..9ab0458cd 100644 --- a/src/Ryujinx.Common/Configuration/AntiAliasing.cs +++ b/src/Ryujinx.Common/Configuration/AntiAliasing.cs @@ -11,6 +11,6 @@ namespace Ryujinx.Common.Configuration SmaaLow, SmaaMedium, SmaaHigh, - SmaaUltra + SmaaUltra, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/AppDataManager.cs b/src/Ryujinx.Common/Configuration/AppDataManager.cs index d6e778430..1dbc1f0ce 100644 --- a/src/Ryujinx.Common/Configuration/AppDataManager.cs +++ b/src/Ryujinx.Common/Configuration/AppDataManager.cs @@ -18,7 +18,7 @@ namespace Ryujinx.Common.Configuration { UserProfile, Portable, - Custom + Custom, } public static LaunchMode Mode { get; private set; } @@ -34,7 +34,7 @@ namespace Ryujinx.Common.Configuration private const string DefaultModsDir = "mods"; public static string CustomModsPath { get; set; } - public static string CustomSdModsPath {get; set; } + public static string CustomSdModsPath { get; set; } public static string CustomNandPath { get; set; } // TODO: Actually implement this into VFS public static string CustomSdCardPath { get; set; } // TODO: Actually implement this into VFS @@ -96,7 +96,7 @@ namespace Ryujinx.Common.Configuration if (OperatingSystem.IsMacOS() && Mode == LaunchMode.UserProfile) { string oldConfigPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), DefaultBaseDir); - if (Path.Exists(oldConfigPath) && !Path.Exists(BaseDirPath)) + if (Path.Exists(oldConfigPath) && !IsPathSymlink(oldConfigPath) && !Path.Exists(BaseDirPath)) { CopyDirectory(oldConfigPath, BaseDirPath); Directory.Delete(oldConfigPath, true); @@ -115,6 +115,14 @@ namespace Ryujinx.Common.Configuration Directory.CreateDirectory(KeysDirPath = Path.Combine(BaseDirPath, KeysDir)); } + // Check if existing old baseDirPath is a symlink, to prevent possible errors. + // Should be removed, when the existance of the old directory isn't checked anymore. + private static bool IsPathSymlink(string path) + { + FileAttributes attributes = File.GetAttributes(path); + return (attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint; + } + private static void CopyDirectory(string sourceDir, string destinationDir) { var dir = new DirectoryInfo(sourceDir); @@ -143,7 +151,7 @@ namespace Ryujinx.Common.Configuration } } - public static string GetModsPath() => CustomModsPath ?? Directory.CreateDirectory(Path.Combine(BaseDirPath, DefaultModsDir)).FullName; + public static string GetModsPath() => CustomModsPath ?? Directory.CreateDirectory(Path.Combine(BaseDirPath, DefaultModsDir)).FullName; public static string GetSdModsPath() => CustomSdModsPath ?? Directory.CreateDirectory(Path.Combine(BaseDirPath, DefaultSdcardDir, "atmosphere")).FullName; } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/AspectRatioExtensions.cs b/src/Ryujinx.Common/Configuration/AspectRatioExtensions.cs index 5e97ed19c..c9bf24650 100644 --- a/src/Ryujinx.Common/Configuration/AspectRatioExtensions.cs +++ b/src/Ryujinx.Common/Configuration/AspectRatioExtensions.cs @@ -11,7 +11,7 @@ namespace Ryujinx.Common.Configuration Fixed16x10, Fixed21x9, Fixed32x9, - Stretched + Stretched, } public static class AspectRatioExtensions @@ -25,12 +25,14 @@ namespace Ryujinx.Common.Configuration { return aspectRatio switch { +#pragma warning disable IDE0055 // Disable formatting AspectRatio.Fixed4x3 => 4.0f, AspectRatio.Fixed16x9 => 16.0f, AspectRatio.Fixed16x10 => 16.0f, AspectRatio.Fixed21x9 => 21.0f, AspectRatio.Fixed32x9 => 32.0f, - _ => 16.0f + _ => 16.0f, +#pragma warning restore IDE0055 }; } @@ -38,12 +40,14 @@ namespace Ryujinx.Common.Configuration { return aspectRatio switch { +#pragma warning disable IDE0055 // Disable formatting AspectRatio.Fixed4x3 => 3.0f, AspectRatio.Fixed16x9 => 9.0f, AspectRatio.Fixed16x10 => 10.0f, AspectRatio.Fixed21x9 => 9.0f, AspectRatio.Fixed32x9 => 9.0f, - _ => 9.0f + _ => 9.0f, +#pragma warning restore IDE0055 }; } @@ -51,13 +55,15 @@ namespace Ryujinx.Common.Configuration { return aspectRatio switch { +#pragma warning disable IDE0055 // Disable formatting AspectRatio.Fixed4x3 => "4:3", AspectRatio.Fixed16x9 => "16:9", AspectRatio.Fixed16x10 => "16:10", AspectRatio.Fixed21x9 => "21:9", AspectRatio.Fixed32x9 => "32:9", - _ => "Stretched" + _ => "Stretched", +#pragma warning restore IDE0055 }; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/BackendThreading.cs b/src/Ryujinx.Common/Configuration/BackendThreading.cs index 8833b3f07..44aa422e4 100644 --- a/src/Ryujinx.Common/Configuration/BackendThreading.cs +++ b/src/Ryujinx.Common/Configuration/BackendThreading.cs @@ -8,6 +8,6 @@ namespace Ryujinx.Common.Configuration { Auto, Off, - On + On, } } diff --git a/src/Ryujinx.Common/Configuration/DownloadableContentContainer.cs b/src/Ryujinx.Common/Configuration/DownloadableContentContainer.cs index b6ae2f3fb..f9e68a3c2 100644 --- a/src/Ryujinx.Common/Configuration/DownloadableContentContainer.cs +++ b/src/Ryujinx.Common/Configuration/DownloadableContentContainer.cs @@ -10,4 +10,4 @@ namespace Ryujinx.Common.Configuration [JsonPropertyName("dlc_nca_list")] public List DownloadableContentNcaList { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/DownloadableContentJsonSerializerContext.cs b/src/Ryujinx.Common/Configuration/DownloadableContentJsonSerializerContext.cs index 132c45a44..0dbc0a301 100644 --- a/src/Ryujinx.Common/Configuration/DownloadableContentJsonSerializerContext.cs +++ b/src/Ryujinx.Common/Configuration/DownloadableContentJsonSerializerContext.cs @@ -8,4 +8,4 @@ namespace Ryujinx.Common.Configuration public partial class DownloadableContentJsonSerializerContext : JsonSerializerContext { } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/DownloadableContentNca.cs b/src/Ryujinx.Common/Configuration/DownloadableContentNca.cs index 80b67300e..dded719cf 100644 --- a/src/Ryujinx.Common/Configuration/DownloadableContentNca.cs +++ b/src/Ryujinx.Common/Configuration/DownloadableContentNca.cs @@ -7,8 +7,8 @@ namespace Ryujinx.Common.Configuration [JsonPropertyName("path")] public string FullPath { get; set; } [JsonPropertyName("title_id")] - public ulong TitleId { get; set; } + public ulong TitleId { get; set; } [JsonPropertyName("is_enabled")] - public bool Enabled { get; set; } + public bool Enabled { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/GraphicsBackend.cs b/src/Ryujinx.Common/Configuration/GraphicsBackend.cs index d74dd6e19..8957c5ccc 100644 --- a/src/Ryujinx.Common/Configuration/GraphicsBackend.cs +++ b/src/Ryujinx.Common/Configuration/GraphicsBackend.cs @@ -7,6 +7,6 @@ namespace Ryujinx.Common.Configuration public enum GraphicsBackend { Vulkan, - OpenGl + OpenGl, } } diff --git a/src/Ryujinx.Common/Configuration/GraphicsDebugLevel.cs b/src/Ryujinx.Common/Configuration/GraphicsDebugLevel.cs index ad12302a6..dfe28405c 100644 --- a/src/Ryujinx.Common/Configuration/GraphicsDebugLevel.cs +++ b/src/Ryujinx.Common/Configuration/GraphicsDebugLevel.cs @@ -9,6 +9,6 @@ namespace Ryujinx.Common.Configuration None, Error, Slowdowns, - All + All, } } diff --git a/src/Ryujinx.Common/Configuration/Hid/Controller/GamepadInputId.cs b/src/Ryujinx.Common/Configuration/Hid/Controller/GamepadInputId.cs index ad1fa6673..78bc46f21 100644 --- a/src/Ryujinx.Common/Configuration/Hid/Controller/GamepadInputId.cs +++ b/src/Ryujinx.Common/Configuration/Hid/Controller/GamepadInputId.cs @@ -53,6 +53,6 @@ namespace Ryujinx.Common.Configuration.Hid.Controller SingleLeftTrigger1, SingleRightTrigger1, - Count + Count, } -} \ No newline at end of file +} diff --git a/src/Ryujinx.Common/Configuration/Hid/Controller/GenericControllerInputConfig.cs b/src/Ryujinx.Common/Configuration/Hid/Controller/GenericControllerInputConfig.cs index d7f0e7881..abc245bc4 100644 --- a/src/Ryujinx.Common/Configuration/Hid/Controller/GenericControllerInputConfig.cs +++ b/src/Ryujinx.Common/Configuration/Hid/Controller/GenericControllerInputConfig.cs @@ -4,7 +4,7 @@ using System.Text.Json.Serialization; namespace Ryujinx.Common.Configuration.Hid.Controller { - public class GenericControllerInputConfig : GenericInputConfigurationCommon