dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.91k stars 4.63k forks source link

[mono][aot] Prevent method to LLVM function mapping where possible #82936

Open jandupej opened 1 year ago

ivanpovazan commented 1 year ago

Providing some context based on offline discussions.

Description

The main focus of this effort is to enable optimizations on Mono fullAOT platforms, mainly WASM and iOS.
The plan is to initially conduct experiments on both platforms WASM (first) and iOS (in a later stage) to estimate potential improvements (size savings and better performance) before proceeding with the concrete implementation. This is especially true for requirement 2. (listed in Prerequisites section) as it requires changes in an external tool.

Limitation

For every compiled method MonoAOT compiler generates an implicit reference to a method, by adding an entry into method_id->method tables which are used by the runtime to perform the method lookup/dispatch during its invocation. This prevents optimization passes to better optimize the generated code.

Prerequisites

In order to remove the limitation, several tasks have to be done:

  1. Identify for which methods types the optimization can be applied - example: private and/or internal members
  2. Provide MonoAOT compiler with additional information about a method usage - method_id->method entries cannot be removed for methods accessed via reflection or referenced from other assemblies. This information could come from ILLinker as it has a global view of the program and performs reflection analysis. It would be required to implement an ILLinker pass which would decorate:
    • private members with a custom attribute that ensures a member is not accessed via reflection (similar to DisablePrivateReflectionAttribute)
    • internal members with a custom attribute that ensures a member is not accessed via reflection or from a different assembly InternalsVisibleToAttribute
  3. Generate direct calls for the chosen method type: https://github.com/dotnet/runtime/blob/b69b359b30e0c62099b919024d099a3cb013540d/src/mono/mono/mini/aot-compiler.c#L4608
  4. For the chosen method type adjust relevant tables:
    • no_method_table_lmethods (add entry) - WASM
    • method_addresses (remove entry) - iOS
    • llvm.used
  5. Set linkage to internal for the chosen method

Additional notes

SamMonoRT commented 1 year ago

Moving this to 9.0.0, and will consider a backport if perf metrics are beyond expectations.