Repository navigation
ILC: do not root delegates that are only stored into fields nobody reads - #138030
Sergio0694 wants to merge 3 commits into
Conversation
A delegate whose creation is ldftn + newobj roots its target as soon as it is created, even if the delegate can never be invoked. The System.Text.Json source generator stores one such lambda per property (AttributeProviderFactory), which is only read by JsonPropertyInfo.AttributeProvider, and keeps both the lambdas and the reflection metadata they cause alive in apps that never read that property. Track, in the scanner, which delegate typed fields may have their contents observed. A delegate creation that is directly stored into a tracked field (or into one through a trivial setter, optionally through the C# lambda caching pattern) only roots its target if the field is read. Copies between fields and trivial getters forward the question to the destination. Any other use of a tracked field marks it as read. The compilation phase replaces the creation of delegates that turned out to be unobserved with null. Dataflow dependencies that come from the body of a non-generic lambda or local function are now conditional on the body of the lambda being compiled, so a dead lambda does not cause reflection metadata either. Co-authored-by: Copilot App <[email protected]>
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
|
Tagging subscribers to this area: @agocke, @dotnet/ilc-contrib |
|
@eiriktsarpalis this fixes #137809, however it does add complexity, and it doesn't work if anyone in the app does use |
| if (i >= 5 | ||
| && i + 4 < count | ||
| && instructions[i - 5].Opcode == ILOpcode.ldsfld | ||
| && instructions[i - 4].Opcode == ILOpcode.dup | ||
| && instructions[i - 3].Opcode is ILOpcode.brtrue or ILOpcode.brtrue_s | ||
| && instructions[i - 2].Opcode == ILOpcode.pop | ||
| && instructions[i - 1].Opcode is ILOpcode.ldsfld or ILOpcode.ldnull | ||
| && instructions[i + 2].Opcode == ILOpcode.dup | ||
| && instructions[i + 3].Opcode == ILOpcode.stsfld | ||
| && instructions[i - 3].BranchDestination == instructions[i + 4].Offset | ||
| && !isTarget[instructions[i - 4].Offset] | ||
| && !isTarget[instructions[i - 3].Offset] | ||
| && !isTarget[instructions[i - 2].Offset] | ||
| && !isTarget[instructions[i - 1].Offset] | ||
| && !isTarget[ldftn.Offset] | ||
| && !isTarget[instructions[i + 2].Offset] | ||
| && !isTarget[instructions[i + 3].Offset]) |
There was a problem hiding this comment.
In theory if we had #85014, this could be simplified a fair amount.
There was a problem hiding this comment.
Note that even if we had #85014, this would still be needed. I'm just saying that building this on top of that would simplify the logic we need in ILC to detect delegate instantiations. But all the rest of the data flow analysis in this PR would still be needed. That is, or we just add that generator option to STJ and then this PR isn't needed as much.
…ield The singleton receiver check now looks at the shape of the field (static initonly field of the containing closure class) instead of its name, and delegate cache containers are also recognized for generic methods (<Method>O__ordinal_id), not only <>O. Co-authored-by: Copilot App <[email protected]>
|
@MichalStrehovsky opening this up as draft to get some feedback on it. Is this change in general something you'd want to consider for ILC, or is data flow intentionally not part of ILC? Either case would also help us understand how much to prioritize #137566 🙂 |
The IL patterns are now matched where the scanner imports the instructions, with peeks at the following instructions like the other pattern matching in the importer, instead of a pre-pass that decodes every method. The compilation phase no longer matches anything: it replaces every delegate creation of a target in a method when the scanner found all of them to be dead, so the scanner registers a use for the delegate creations it does not understand. A read of a delegate cache that is forwarded to another field now requires the null case to be the creation that refills the cache. Co-authored-by: Copilot App <[email protected]>
MichalStrehovsky/rt-sz#307 (comment) says all I need to know. Don't even need to look at code |
|
@eiriktsarpalis given what @MichalStrehovsky said (and the fact that this change adds substantial complexity with basically no benefits outside of that very specific scenario in System.Text.Json), can we go with the proposed generator option instead and bring that to API review? I am happy to also look into adding the analyzer @jkotas suggested if that would help, I agree it should be possible to at least statically flag cases that are provably incorrect in theory. |
System.Text.Json is designed as a reflection first serializer. You can wrap it with layers of options to cut down some of the gross inefficiencies, but I doubt that you will be able to get close to optimal. How many different types do you need to serialize as json in the store app? How much total binary size do you pay for it? It may be interesting to get a number for how much you can save by a vibe-coded precompiled serializer that avoids the cruft from System.Text.Json. |
|
@Sergio0694 given your stated requirement of needing to mix and match uses of the attribute provider in a single app, it is true that this change will not help a lot. We can look at the source gen opt out mechanism as proposed, although due to overridding priorities we the libraries team don't have the bandwidth to look at .NET 12 features at this moment. I would suggest pinging me again after the holidays. |
In my experiments, you stand to save ~20% of application size (in a basic console app that roundtrips a JSON value), but that's assuming your app doesn't have any special requirements such as conditional writes, reference preservation, async, number handling, property naming policies, etc. As these features stack up a fully inlined serializer tends to grow bigger than a metadata-based one. |
We have about 460 distinct types we serialize (~340 are our own models, ~120 are built-in types/collections), for a total of 660 generated type metadata entries (which also includes e.g. arrays/collections over those types). So we have quite a lot of stuff. And for us migrating to System.Text.Json isn't really viable, we heavily rely on its infrastructure to implement e.g. custom converters etc., we use its APIs both to serialize into buffers/
@eiriktsarpalis I actually investigated this in the Store, and we can easily stop using it entirely (I'll probably do this regardless given that looking up attributes is less efficient anyway and not consistent with how we handle JSON models in other projects), so in my case I don't even need the per-context opt-out anymore either, I'd be fine with a global switch as well if that simplifies things. I still feel like the per-context switch might make sense in general, but I'm saying if you have a strong preference for either approach, both would work just as well for us, as long as we can still stop emitting all that code 🙂 |
A delegate created with
ldftn+newobjroots its target as soon as the creation is reachable, even if the delegate can never be invoked. The System.Text.Json source generator emits one such lambda per property (AttributeProviderFactory, andConstructorAttributeProviderFactoryper constructor). They are only read throughJsonPropertyInfo.AttributeProviderandJsonParameterInfo.AttributeProvider, but in an app that never reads those they still keep the lambdas, and the reflection metadata their bodies cause (typeof(T).GetProperty("Name")), alive.This teaches the dependency scanner to skip delegates that are only stored into fields whose value is never observed:
ldfld,ldflda,ldsfld, reflection, calls to the getter that are not themselves forwarded, and so on) counts as a read.null, so both phases see the same IL.Size impact
Microsoft Store (
WinStore.App.dll, Release x64,OptimizationPreference=Size), same inputs, ILC with and without this change. The Store can't be built with the current main compiler yet, so this was measured on the equivalent change on top of the release/11.0 gate backport.WinStore.App.dllThe removed code is the expected one: the
AttributeProviderFactorylambdas of the source generated contexts and the reflection metadata, invoke map entries and accessors they kept alive, plus three dead stores outside System.Text.Json. An earlier build of this change was smoke tested in Windows Sandbox (no app errors or crashes); the binary was not re-tested after the final review fixes.Testing
TestDeadDelegateStoresto theTrimmingBehaviorssmoke test: dead and live stores, setters and getters, copies, shared generic code, reflection, and a regression case for delegates created in code run by a static constructor.ILCompiler.Trimming.Tests: 622 passed, 4 failed (ilasmisn't built in my tree, unrelated).Part of #137567.
Resolves #137809
Note
This PR description and the change were prepared with GitHub Copilot.