Skip to content
1 change: 1 addition & 0 deletions docs/release-notes/.FSharp.Compiler.Service/11.0.200.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
* Preserve SRTP extension scopes across source files and competing witnesses through imported inline calls. Compile generic extension forwarding, including quotations, in unoptimized builds. Preserve applicable built-in operator priority in imported inline quotations. Do not reuse SRTP specializations across different selected witnesses. ([Issue #20683](https://github.com/dotnet/fsharp/issues/20683), [Issue #20684](https://github.com/dotnet/fsharp/issues/20684), [Issue #20685](https://github.com/dotnet/fsharp/issues/20685), [PR #20717](https://github.com/dotnet/fsharp/pull/20717))
* Transparent compiler: with `enablePartialTypeChecking`, a project that is only referenced by another project is type checked from its signatures. Implementation files that have a signature file are no longer parsed or type checked to produce the referenced assembly. `ParseAndCheckProject` still checks all files. ([PR #20703](https://github.com/dotnet/fsharp/pull/20703))
* With `enablePartialTypeChecking`, a project that is only referenced by another project no longer type checks its implementation files that have a signature file. Producing the referenced assembly only needs the signatures, but finalizing the project also collected the diagnostics of the skipped files, which type checked all of them and kept their results in memory. `ParseAndCheckProject` still reports the diagnostics of these files. ([PR #20699](https://github.com/dotnet/fsharp/pull/20699))
* Bound the copies of `when` guards in compiled pattern matches. A match whose decision tree would repeat its guards more than 32 times is compiled in groups, each falling through to the rest of the match once. This halves the IL of `LexFilter.hwTokenFetch` (110 KB to 48 KB), so the JIT optimizes it again, and parsing is about 27% faster where FCS is JIT-compiled. ([Issue #20632](https://github.com/dotnet/fsharp/issues/20632), [PR #20718](https://github.com/dotnet/fsharp/pull/20718))

### Changed

Expand Down
190 changes: 151 additions & 39 deletions src/Compiler/Checking/PatternMatchCompilation.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1080,11 +1080,76 @@ let mkThrowUsingEDICapture (infoReader: InfoReader) tcVal m resultTy exnExpr =
| _ ->
mkThrow m resultTy exnExpr

exception private GuardCopyBudgetExceeded

/// Whether the input is read through an immutable byref. A struct union input read this way is tested
/// in place, not through a copy.
let private isCopyableInputExpr origInputExpr =
match origInputExpr with
| Expr.Op (TOp.LValueOp (LByrefGet, v), [], [], _) when not v.IsMutable -> true
| _ -> false

/// Whether the pattern tests an array element or a mutable record field, which a 'when' guard can write.
let rec private testsMutableData inpPat =
match inpPat with
| TPat_array _ -> true
| TPat_recd (tcref, _, subPats, _) ->
(tcref.TrueInstanceFieldsAsList, subPats)
||> List.exists2 (fun field subPat ->
match subPat with
| TPat_wild _ -> false
| _ -> field.IsMutable || testsMutableData subPat)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A [<CLIMutable>] record gets past this check. Its fields have public setters, but field.IsMutable is false for them, so a match whose guard writes the record through a setter is still cut:

[<CLIMutable>]
type R = { T: int }

let f (r: R) c =
    match r, c with
    | { T = 0 }, 0 when (typeof<R>.GetProperty("T").SetValue(r, 6); false) -> 0
    | _, 0 when c < 0 -> 10
    // ... the same rule for 1 to 3
    | _, 4 when c < 0 -> 14
    | { T = 1 }, _ -> 1
    // ... the same rule for 2 to 5
    | { T = 6 }, _ -> 6
    | _ -> -1

f { T = 0 } 0 returns 6 with the head and -1 with the merge base. Reflection stands in for C# code or a serializer, which is what the attribute is for. TryOptimizeRecordFieldGet already skips these records with the CLIMutableAttribute check, and the same check here would cover it.

| TPat_query (_, subPat, _)
| TPat_as (subPat, _, _) -> testsMutableData subPat
Comment on lines +1102 to +1103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The cut can still change which rule a match picks when a total active pattern reads data that a guard writes, because this arm only checks the patterns on the active pattern's result. Here is the array case from Guards that write the tested data keep the rule the whole match would pick, with the array read through an active pattern:

let (|Elems|) (a: int[]) = a.[0], a.[1]

let array (arr: int[]) col =
    match arr with
    | Elems (0, 0) when (arr.[0] <- 7; arr.[1] <- 7; false) -> 0
    | Elems (_, 0) when col <= 0 -> 10
    // ... the same rule for 1 to 6
    | Elems (_, 7) when col <= 7 -> 17
    | Elems (1, _) -> 1
    // ... the same rule for 2 to 6
    | Elems (7, _) -> 7
    | _ -> -1

With this PR's build, array [| 0; 0 |] 100 returns 7 and calls Elems twice, with --optimize- and with --optimize+. The merge-base build returns -1 and calls Elems once, as SDK 10.0.402 does. In a variant where the eight col <= c guards call a non-inlined le c col instead, the merge-base build's IL has 72 calls to le. One call per guard would give 8, so that is 64 extra copies, well over this PR's budget of 32. The patterns matched against the result of Elems contain no array, mutable field or byref, so canRetestInput allows the cut, and the rest of the match calls Elems again, on [| 7; 7 |].

The obvious fix, TPat_query _ -> true, would also turn the cut off for hwTokenFetch, because its match uses the partial TokenRExprParen (LexFilter.fs line 1702). An Elems variant in guardWritesTestedDataSource would cover whichever fix you choose.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for this, I took a look at it, see cc97109

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks, that covers it. Reading cc97109, a cut can no longer separate the clauses that apply Elems, so they stay in one tree and Elems runs once. Moving the cut, rather than treating TPat_query as mutable data, also avoids the hwTokenFetch cost I was worried about, going by your commit message.

| TPat_disjs (subPats, _)
| TPat_conjs (subPats, _)
| TPat_tuple (_, subPats, _, _)
| TPat_exnconstr (_, subPats, _)
| TPat_unioncase (_, _, subPats, _) -> List.exists testsMutableData subPats
| TPat_isinst (_, _, subPatOpt, _) -> Option.exists testsMutableData subPatOpt
| TPat_const _
| TPat_wild _
| TPat_null _
| TPat_error _ -> false

/// The stamps of the named active patterns the pattern applies. The decision tree can share one call of such a
/// pattern between clauses, so a cut must not separate clauses that apply the same one. A generic pattern, or one
/// applied to a different input, counts as shared too, which only forbids cuts that would be safe.
let rec private activePatternStamps acc inpPat =
match inpPat with
| TPat_query ((_, _, _, apatVrefOpt, _, _), subPat, _) ->
let acc =
match apatVrefOpt with
| Some (vref, _) -> Set.add vref.Stamp acc
| None -> acc
activePatternStamps acc subPat
| TPat_as (subPat, _, _) -> activePatternStamps acc subPat
| TPat_disjs (subPats, _)
| TPat_conjs (subPats, _)
| TPat_tuple (_, subPats, _, _)
| TPat_exnconstr (_, subPats, _)
| TPat_recd (_, _, subPats, _)
| TPat_unioncase (_, _, subPats, _)
| TPat_array (subPats, _, _) -> List.fold activePatternStamps acc subPats
| TPat_isinst (_, _, subPatOpt, _) -> Option.fold activePatternStamps acc subPatOpt
| TPat_const _
| TPat_wild _
| TPat_null _
| TPat_error _ -> acc

[<Struct; NoEquality; NoComparison>]
type private CompiledMatch =
{ Tree: DecisionTree
Targets: DecisionTreeTarget list
Joins: Bindings
GuardCopies: int }

let private CompilePatternBasic
(g: TcGlobals) denv amap tcVal infoReader mExpr mMatch
warnOnUnused
warnOnIncomplete
(joinPromotion: JoinPromotion)
(guardCopyBudget: int voption)
actionOnFailure
(origInputVal, origInputValTypars, _origInputExprOpt: Expr option)
(clauses: MatchClause list)
Expand Down Expand Up @@ -1270,6 +1335,9 @@ let private CompilePatternBasic
let idx = matchBuilder.AddTarget(TTarget(targetParams, mkApps g ((joinE, joinThunkTy), [], args, mMatch), None))
TDSuccess(caps |> List.map (exprForVal mMatch), idx)

let guardEmitted = HashSet<ClauseNumber>()
let mutable guardCopies = 0

let rec InvestigateFrontiers refuted frontiers =
Cancellable.CheckAndThrow()
stackGuard.Guard(fun () -> InvestigateFrontiersImpl refuted frontiers)
Expand Down Expand Up @@ -1324,6 +1392,11 @@ let private CompilePatternBasic
match GetWhenGuardOfClause i refuted with
| Some whenExpr ->
let m = whenExpr.Range
if not (guardEmitted.Add i) then
guardCopies <- guardCopies + 1
match guardCopyBudget with
| ValueSome budget when guardCopies > budget -> raise GuardCopyBudgetExceeded
| _ -> ()
let whenExprWithBindings = mkLetsFromBindings m (mkInvisibleBinds vs2 es2) whenExpr
let failureTree = investigateMemoized (RefutedWhenClause :: refuted) rest
mkBoolSwitch m whenExprWithBindings successTree failureTree
Expand Down Expand Up @@ -1388,11 +1461,6 @@ let private CompilePatternBasic
else
None)

and IsCopyableInputExpr origInputExpr =
match origInputExpr with
| Expr.Op (TOp.LValueOp (LByrefGet, v), [], [], _) when not v.IsMutable -> true
| _ -> false

and ChoosePreBinder simulSetOfEdgeDiscrims subexpr =
match simulSetOfEdgeDiscrims with
// Very simple 'isinst' tests: put the result of 'isinst' in a local variable
Expand Down Expand Up @@ -1424,7 +1492,7 @@ let private CompilePatternBasic
let argExpr = GetSubExprOfInput subexpr
let argExpr =
match argExpr, _origInputExprOpt with
| Expr.Val (v1, _, _), Some origInputExpr when valEq origInputVal v1.Deref && IsCopyableInputExpr origInputExpr -> origInputExpr
| Expr.Val (v1, _, _), Some origInputExpr when valEq origInputVal v1.Deref && isCopyableInputExpr origInputExpr -> origInputExpr
| _ -> argExpr
let vOpt, addrExp, _readonly, _writeonly = mkExprAddrOfExprAux g true false NeverMutates argExpr None mMatch
match vOpt with
Expand Down Expand Up @@ -1823,7 +1891,7 @@ let private CompilePatternBasic
if warnOnUnused then
ReportUnusedTargets clauses dtree

dtree, matchBuilder.CloseTargets(), List.ofSeq joinBindings
{ Tree = dtree; Targets = matchBuilder.CloseTargets(); Joins = List.ofSeq joinBindings; GuardCopies = guardCopies }

// Three pattern constructs can cause significant code expansion in various combinations
// - Partial active patterns
Expand Down Expand Up @@ -1887,41 +1955,85 @@ let isProblematicClause (clause: MatchClause) =
let ips = investigationPoints clause.Pattern
ips.Length > 0 && Span.exists id (ips.AsSpan (0, ips.Length - 1))

let rec CompilePattern g denv amap tcVal infoReader mExpr mMatch warnOnUnused actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (clausesL: MatchClause list) inputTy resultTy =
match clausesL with
| _ when List.exists isProblematicClause clausesL ->

// First make sure we generate at least some of the obvious incomplete match warnings.
let warnOnUnused = false // we can't turn this on since we're pretending all partials fail in order to control the complexity of this.
let warnOnIncomplete = true
let clausesPretendAllPartialFail = clausesL |> List.collect (fun (MatchClause(p, whenOpt, tg, m)) -> [MatchClause(erasePartialPatterns p, whenOpt, tg, m)])
let _ = CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete JoinPromotion.Disabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesPretendAllPartialFail inputTy resultTy
let warnOnIncomplete = false
/// Extra copies of 'when' guards a decision tree may hold. A match over this budget is cut into
/// groups, each compiled with the rest of the match as a single fall-through target.
let private guardCopyBudget = 32

let CompilePattern g denv amap tcVal infoReader mExpr mMatch warnOnUnused actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (clausesL: MatchClause list) inputTy resultTy =
let compile warnOnUnused warnOnIncomplete joinPromotion budget clauses =
CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete joinPromotion budget actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clauses inputTy resultTy

let restPlaceholder = MatchClause(TPat_wild mMatch, None, TTarget([], mkDefault (mMatch, resultTy), None), mMatch)

let fitsBudget clauses =
try
compile false false JoinPromotion.Enabled (ValueSome guardCopyBudget) (clauses @ [ restPlaceholder ]) |> ignore
true
with GuardCopyBudgetExceeded ->
false

// The longest prefix of the group that fits the budget, at least one clause. A cut between two clauses
// that apply the same active pattern would call it a second time, after the guards before the cut ran,
// so the cut moves back to a point where no active pattern is shared. Without one, the group stays whole.
let cutToBudget (group: MatchClause list) rest =
let rec search lo hi =
if lo >= hi then
lo
else
let mid = (lo + hi + 1) / 2
if fitsBudget (List.take mid group) then search mid hi else search lo (mid - 1)

// Partial and when clauses cause major code explosion if treated naively
// Hence treat any pattern matches with any partial clauses clause-by-clause
let rec atMostOneProblematicClauseAtATime clauses =
if fitsBudget group then
group, rest
else
let stamps = group |> List.map (fun clause -> activePatternStamps Set.empty clause.Pattern)
let before = List.scan Set.union Set.empty stamps |> List.toArray
let after = List.scanBack Set.union stamps Set.empty |> List.toArray
let canCutAt k = Set.isEmpty (Set.intersect before[k] after[k])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This catches a pattern applied on both sides of the cut. One applied only after the cut can still run where the whole match never runs it, because the rest is compiled without what the tests before the cut ruled out. With (|Parity|) counting its calls and returning its input modulo 2:

let f (t: int) (c: int) (col: int) =
    match t, c with
    | 0, 0 -> 0
    | _, 0 when col <= 0 -> 10
    // ... the same rule for 1 to 3
    | _, 4 when col <= 4 -> 14
    | 1, _ -> 1
    // ... the same rule for 2 to 5
    | 6, _ -> 6
    | Parity 1, 9 -> 90
    | _ -> -1

f 7 0 100 returns -1 with both builds, but only the head calls Parity: the merge base's switch on c has already ruled out Parity 1, 9. If the pattern throws, the head throws. A record rule works the same way: in a 17-rule variant with a null record and | { A = 1 }, 4, _ after the guards, the head reads .A and throws NullReferenceException, where the merge base has ruled that rule out on the int.


let rec lastCut k =
if k < 1 then ValueNone
elif canCutAt k then ValueSome k
else lastCut (k - 1)

match lastCut (search 1 (group.Length - 1)) with
| ValueSome k -> List.take k group, List.skip k group @ rest
| ValueNone -> group, rest

// Partial patterns and 'when' clauses cause major code explosion if treated naively, as every
// path that falls through a group would get its own copy of the clauses after it. So each group
// ends at a problematic clause or at the budget, and the rest of the match is compiled once.
// The groups report no warnings: the whole-match compile already did.
let rec compileGroups cutLargeGroups clauses =
let group, rest =
match List.takeUntil isProblematicClause clauses with
| l, [] ->
CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete JoinPromotion.Enabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) l inputTy resultTy
| l, h :: t ->
// Add the problematic clause.
doGroupWithAtMostOneProblematic (l @ [h]) t
| l, [] -> l, []
| l, h :: t -> l @ [ h ], t

and doGroupWithAtMostOneProblematic group rest =
// Compile the remaining clauses.
let decisionTree, targets, joins = atMostOneProblematicClauseAtATime rest
let group, rest = if cutLargeGroups then cutToBudget group rest else group, rest

// Make the expression that represents the remaining cases of the pattern match.
let expr = mkLetsBind mMatch joins (mkAndSimplifyMatch DebugPointAtBinding.NoneAtInvisible mExpr mMatch resultTy decisionTree targets)

// Make the clause that represents the remaining cases of the pattern match
match rest with
| [] -> compile false false JoinPromotion.Enabled ValueNone group
| _ ->
let rest = compileGroups cutLargeGroups rest
let expr = mkLetsBind mMatch rest.Joins (mkAndSimplifyMatch DebugPointAtBinding.NoneAtInvisible mExpr mMatch resultTy rest.Tree rest.Targets)
let clauseForRestOfMatch = MatchClause(TPat_wild mMatch, None, TTarget(List.empty, expr, None), mMatch)
compile false false JoinPromotion.Enabled ValueNone (group @ [ clauseForRestOfMatch ])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The same gap runs the other way. The prefix is compiled with the rest as a wildcard, so a type test in the rest can no longer rule out a clause before the cut:

let f (t: int) (c: int) (o: obj) (col: int) =
    match t, c, o with
    | 0, 0, _ when col < 0 -> 0
    | _, 0, _ when col <= 0 -> 10
    // ... the same rule for 1 to 4
    | _, 5, _ when col <= 5 -> 15
    | _, _, (:? Animal) -> 20
    | Q 5, _, (:? IFoo) -> 30
    | 1, _, _ -> 1
    // ... the same rule for 2 to 4
    | 5, _, _ -> 5
    | _, _, (:? string) -> 40
    | _ -> -1

Animal is an empty class, IFoo an empty interface, and (|Q|) a total pattern counting its calls. The whole match adds :? string to the :? Animal switch, and that branch drops the IFoo rule, because a string is never an IFoo. After the cut the prefix never sees :? string, so f 9 9 (box "s") 100 calls Q once with the head and never with the merge base. Both return 40. A null test with a null input does the same.


// The rest of a cut match tests the input again, and sees what a failed guard wrote to it, where
// the whole tree would not. So only a match whose tested data no guard can write is cut by the budget.
let canRetestInput () =
not (Option.exists isCopyableInputExpr origInputExprOpt)
&& not (clausesL |> List.exists (fun clause -> testsMutableData clause.Pattern))

let result =
if List.exists isProblematicClause clausesL then
// Partial patterns are treated as failing here, so unused clauses can't be reported.
let clausesPretendAllPartialFail = clausesL |> List.map (fun (MatchClause(p, whenOpt, tg, m)) -> MatchClause(erasePartialPatterns p, whenOpt, tg, m))
let whole = compile false true JoinPromotion.Disabled ValueNone clausesPretendAllPartialFail
compileGroups (whole.GuardCopies > guardCopyBudget && canRetestInput ()) clausesL
else
let whole = compile warnOnUnused true JoinPromotion.Disabled ValueNone clausesL
if whole.GuardCopies > guardCopyBudget && canRetestInput () then compileGroups true clausesL else whole

CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete JoinPromotion.Enabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (group @ [clauseForRestOfMatch]) inputTy resultTy


atMostOneProblematicClauseAtATime clausesL

| _ ->
CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused true JoinPromotion.Disabled actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesL inputTy resultTy
result.Tree, result.Targets, result.Joins
Loading
Loading