dotnet / fsharp

The F# compiler, F# core library, F# language service, and F# tooling integration for Visual Studio
https://dotnet.microsoft.com/languages/fsharp
MIT License
3.82k stars 773 forks source link

Integral range optimizations in resumable code computation expressions #17253

Open brianrourkeboll opened 1 month ago

brianrourkeboll commented 1 month ago

13573 would have included one optimization which #16650, et seq., did not, namely the optimization of for-loops over integral ranges with steps other than 1 and -1 in resumable code computation expressions (like task). I figured I might as well record it here (cc @psfinaki).

It seems like it might be relatively straightforward to add this optimization now by wiring up the IntegralRange and mkOptimizedRangeLoop constructs exposed in #16650.

  1. Supplement the existing match on IntegerForLoopExpr with another match on CompiledForEachExpr and IntegralRange:

    https://github.com/dotnet/fsharp/blob/5fd6800a984c59267c406305c15e9f7efb1e8519/src/Compiler/Optimize/LowerStateMachines.fs#L485-L486

  2. There is an existing translation using mkIntegerForLoop; add a new one that uses mkOptimizedRangeLoop:

    https://github.com/dotnet/fsharp/blob/5fd6800a984c59267c406305c15e9f7efb1e8519/src/Compiler/Optimize/LowerStateMachines.fs#L692

However, the existing optimization for for-loops over int32 ranges with steps of 1 or -1 doesn't always seem to kick in — in fact, I haven't been able to get it to kick in at all, even when using the syntax for n = start to finish do … instead of for n in start..finish do …. So figuring out why that is, and what the TAST actually looks like by the time it gets to LowerStateMachines.fs, might end up being the harder problem to solve.