Skip to content
This repository was archived by the owner on Sep 25, 2026. It is now read-only.

[DAM analyzer] Add basic dataflow analysis - #2360

Merged
sbomer merged 18 commits into
dotnet:feature/damAnalyzerfrom
sbomer:damDataflow
Nov 17, 2021
Merged

sbomer merged 18 commits into
dotnet:feature/damAnalyzerfrom
sbomer:damDataflow

Conversation

@sbomer

@sbomer sbomer commented Nov 9, 2021 •

Copy link
Copy Markdown
Member

This adds basic dataflow analysis for the Roslyn analyzer. So far it only tracks DAM annotations (not known types, reflection intrinsics, and similar). It also doesn't handle exceptional control flow, but unlike the linker's analysis it does handle backwards branches.

The dataflow framework is set up to (hopefully) facilitate code sharing going forward - the core abstractions don't depend on Roslyn constructs, but there's more work that would need to be done to actually share this code with the linker.

As the analysis runs, it caches any reflection access patterns it encounters, and warnings are reported after it converges. The caching is intended to be additive - it should ensure that we increase the set of possible reflection accesses as we go, but it should never lose track of a pattern encountered in a previous iteration of the analysis.

The core logic for creating and propagating the tracked values is in DynamicallyAccessedMembersVisitor, similar to ReflectionMethodBodyScanner. There is a base class LocalDataFlowVisitor, similar to MethodBodyScanner, which knows how to propagate values across locals in Roslyn in a generic way.

The actual dataflow algorithm (ForwardDataFlowAnalysis) does the simplest possible thing in this change. The goal is to set it up in a way that the core abstractions don't need to change even when we go optimize the algorithm (and ideally for any optimizations to be generic, not tightly bound with our particular analysis). This should make it easier to reuse the code in the linker and possibly in other future analyses.

PTAL! I am particularly interested in feedback on naming of some of the wrapper classes which exist only to implement interfaces or to provide generic instantiations.

@agocke I know you were interested in seeing a spec for the dataflow analysis - I still plan on doing that but wanted to get this change out for now.

Add back support for
- Generics (limited to generic method invocation)
- Conversion operators

Clean up representation of annotated values. We used to use a
NamedTypeSymbol for annotated methods (to represent the 'this' parameter).
Now this is hidden inside of AnnotatedSymbol, which tracks the method, and whether
it represents the receiver, or the return parameter.

This fixes an ambiguity where AnnotatedSymbol needs to track type symbols
that don't represent 'this' parameters.
Use test attributes to track disabled tests
- Cache access patterns by the originating operation
- Validate that running dataflow analysis only adds new
  reflection access patterns
- Use return operation as origin for returned values
ExpectedWarning matches multiple warnings
@vitek-karas

Copy link
Copy Markdown
Member

First batch of comments - still working on this

@vitek-karas vitek-karas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually adding some comments

Comment thread src/ILLink.Shared/Dataflow/ITransfer.cs Resolved
Comment thread src/ILLink.Shared/Dataflow/ITransfer.cs Resolved
Comment thread src/ILLink.Shared/Dataflow/ILattice.cs Resolved
- HashSetWrapper -> ValueSet
- DynamicallyAccessedMembersValue ->
  ValueWithDynamicallyAccessedMembers
- Add helper to avoid constants in GetHashCode
- Make DefaultValueDictionary a wrapper struct
  to hide Dictionary methods that shouldn't be used
- Add comments explaining dataflow abstractions,
  generic parameters, and the unoptimized analysis.
Comment thread src/ILLink.Shared/Dataflow/ILattice.cs Resolved
Comment thread src/ILLink.Shared/Dataflow/ILattice.cs Resolved
public interface ITransfer<TOperation, TValue, TLattice>
where TValue : IEquatable<TValue>
where TLattice : ILattice<TValue>
{

@agocke agocke Nov 11, 2021 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this abstraction is right -- a lattice isn't used by the transfer function, instead the mathematical structure is that

  1. A data-flow analysis is a program for calculating the set of possible values
  2. It requires a domain, which consists of a set of values being tracked, a control flow graph made of basic blocks, a transfer function between those blocks, a defined top state, and a joining function for control flow edges.

I think this means that the right abstraction combines all these things into one. They wouldn't be seperable:

interface IDataFlowAnalysis<TValueSet, TBlock>
{
    public Run(ControlFlowGraph graph)
    {
        ...
    }

    public TValue Transfer (TBlock, TValue startingValue);
    public TValue Top { get; }
    public TValue Meet (TValue, TValue);
}

In other words, a lattice is a structure that a data-flow analysis is, not something that other things have

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see -- you're abstracting away local variable analysis as well, so you need to need two lattice implementations: one for the variable state, and one for the global state.

I'll see if I can come up with a shorter way to express this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, I think the biggest simplification would be getting rid of support for general data flow and just doing DAM, but I'm not sure if there was another data flow analysis we need to support.

The other simplification could be creating an IDataFlowAnalysis : ILattice and adding Transfer to IDataFlowAnalysis. Having those split out doesn't seem to providing a lot of generality.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'd like to keep the lattice abstraction separate because it allows defining the dictionary lattices in terms of another lattices - I personally think it makes the algebraic structure clearer. One simplification that would be really nice is to combine TValue and TValueLattice, by having an interface like ILatticeValue where Top is a static virtual interface method. But AFAIK we can't do that with netstandard2.0.

I don't think we need to support another analysis yet. If we don't think there's value in abstracting this out I can make everything DAM-specific, but one of my original design goals was to make this a reusable framework (or at least for the core pieces to be a reasonable starting point for such a framework). I also think using these abstractions forces thinking in more mathematical terms which I believe is going to help with correctness - but that might just be the way I think. :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally don't mind this abstraction. Precisely for the point that it nicely maps to all of the theoretical work in this space.
I wonder if we could use a similar approach (haven't really thought it through) for constant propagation and branch removal.... in the linker/native AOT.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the second suggestion (combining the flow analysis with the transfer functions under an IDataFlowAnalysis or similar): as discussed, we can't use default interface implementations so this would prevent the current approach where the core dataflow analysis is generic. Alternatively, it would require the visitor state to be stored together with the class implementing the dataflow analysis, but this state doesn't need to live as long as the analysis results. For now I've left them separate but it's easy enough to change if we want to choose a different tradeoff later.

@vitek-karas

Copy link
Copy Markdown
Member

Some more comments

@vitek-karas vitek-karas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some more comments - still working through this

Comment thread src/ILLink.Shared/Dataflow/ValueSet.cs Resolved
- Wrapper -> Proxy
- DAMSymbol -> SymbolValue
- DAMAnalysis -> TrimDataFlowAnalysis
- DAMVisitor -> TrimAnalysisVisitor
- Use "DataFlow" and "TrimAnalysis" namespaces
- Fix override of Visit to take nullable IOperation
- Use string.Join
- Comments about forward analysis
- Simplify GetPredecessors
- Keep ToString in release builds
- Use records
And use records in a couple more places

@vitek-karas vitek-karas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More comments... still working on it.

Comment thread src/ILLink.Shared/DataFlow/ITransfer.cs Resolved
Comment thread src/ILLink.Shared/DataFlow/ILattice.cs Resolved

@agocke agocke left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM as first pass

- GetTrimAnalysisPatterns -> ComputeTrimAnalysisPatterns
- Comments about unsupported throw operations
- Clarify HandleReceiverArgument
- Comment about tracking unsupported values
- Don't expose Predecessors in BlockProxy
- Comments about DefaultValueDictionary

Also:
- Make LocalState a class so that all changes
  are visible in the caller of the visitor.
- Use readonly structs in more places
@sbomer

sbomer commented Nov 17, 2021

Copy link
Copy Markdown
Member Author

Thanks for all the feedback!

@sbomer
sbomer merged commit 32f2c6d into dotnet:feature/damAnalyzer Nov 17, 2021
@sbomer sbomer mentioned this pull request Nov 17, 2021
17 of 18 tasks
@sbomer
sbomer deleted the damDataflow branch February 22, 2022 18:13
agocke pushed a commit to dotnet/runtime that referenced this pull request Nov 16, 2022
This adds basic dataflow analysis for the Roslyn analyzer. So far it only tracks DAM annotations (not known types, reflection intrinsics, and similar). It also doesn't handle exceptional control flow, but unlike the linker's analysis it does handle backwards branches.

The dataflow framework is set up to (hopefully) facilitate code sharing going forward - the core abstractions don't depend on Roslyn constructs, but there's more work that would need to be done to actually share this code with the linker.

As the analysis runs, it caches any trim analysis patterns it encounters, and warnings are reported after it converges. The caching is intended to be additive - it should ensure that we increase the set of possible analysis patterns as we go, but it should never lose track of a pattern encountered in a previous iteration of the analysis.

The core logic for creating and propagating the tracked values is in TrimAnalysisVisitor, similar to ReflectionMethodBodyScanner. There is a base class LocalDataFlowVisitor, similar to MethodBodyScanner, which knows how to propagate values across locals in Roslyn in a generic way.

The actual dataflow algorithm (ForwardDataFlowAnalysis) does the simplest possible thing in this change. The goal is to set it up in a way that the core abstractions don't need to change even when we go optimize the algorithm (and ideally for any optimizations to be generic, not tightly bound with our particular analysis). This should make it easier to reuse the code in the linker and possibly in other future analyses.

This also cleans up the representation of annotated values. We used to use a NamedTypeSymbol for annotated methods (to represent the 'this' parameter). Now this is hidden inside of SymbolValue, which tracks the method, and whether it represents the receiver, or the return parameter.
This fixes an ambiguity where AnnotatedSymbol needs to track type symbols that don't represent 'this' parameters.


Commit migrated from dotnet/linker@32f2c6d
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants