LocalRewriter_PatternSwitchStatement.cs 33.7 KB
Newer Older
N
Neal Gafter 已提交
1 2
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

3 4
using System;
using System.Collections.Generic;
N
Neal Gafter 已提交
5 6 7 8 9 10 11 12 13 14 15
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal partial class LocalRewriter
    {
        public override BoundNode VisitPatternSwitchStatement(BoundPatternSwitchStatement node)
        {
16 17
            return PatternSwitchLocalRewriter.MakeLoweredForm(this, node);
        }
18

19 20 21 22 23 24 25 26 27 28
        /// <summary>
        /// Helper class for rewriting a pattern switch statement by lowering it to a decision tree and
        /// then to a sequence of statements.
        /// </summary>
        private class PatternSwitchLocalRewriter : DecisionTreeBuilder
        {
            private readonly LocalRewriter _localRewriter;
            private readonly HashSet<LocalSymbol> _declaredTempSet = new HashSet<LocalSymbol>();
            private readonly ArrayBuilder<LocalSymbol> _declaredTemps = ArrayBuilder<LocalSymbol>.GetInstance();
            private readonly SyntheticBoundNodeFactory _factory;
29

30 31 32 33
            /// <summary>
            /// Map from switch section's syntax to the lowered code for the section.
            /// </summary>
            private readonly Dictionary<SyntaxNode, ArrayBuilder<BoundStatement>> _switchSections = new Dictionary<SyntaxNode, ArrayBuilder<BoundStatement>>();
N
Neal Gafter 已提交
34

35 36 37 38 39 40 41 42 43 44 45 46 47
            private ArrayBuilder<BoundStatement> _loweredDecisionTree = ArrayBuilder<BoundStatement>.GetInstance();

            private PatternSwitchLocalRewriter(LocalRewriter localRewriter, BoundPatternSwitchStatement node)
                : base(localRewriter._factory.CurrentMethod, localRewriter._factory.Compilation.Conversions)
            {
                this._localRewriter = localRewriter;
                this._factory = localRewriter._factory;
                this._factory.Syntax = node.Syntax;
                foreach (var section in node.SwitchSections)
                {
                    _switchSections.Add((SyntaxNode)section.Syntax, ArrayBuilder<BoundStatement>.GetInstance());
                }
            }
48

49
            internal static BoundStatement MakeLoweredForm(LocalRewriter localRewriter, BoundPatternSwitchStatement node)
50
            {
51
                return new PatternSwitchLocalRewriter(localRewriter, node).MakeLoweredForm(node);
52
            }
N
Neal Gafter 已提交
53

54
            private BoundStatement MakeLoweredForm(BoundPatternSwitchStatement node)
N
Neal Gafter 已提交
55
            {
56 57
                var expression = _localRewriter.VisitExpression(node.Expression);
                var result = ArrayBuilder<BoundStatement>.GetInstance();
58

59 60 61
                // if the expression is "too complex", we copy it to a temp.
                LocalSymbol initialTemp = null;
                if (expression.ConstantValue == null)
N
Neal Gafter 已提交
62
                {
63 64 65
                    initialTemp = _factory.SynthesizedLocal(expression.Type, expression.Syntax);
                    result.Add(_factory.Assignment(_factory.Local(initialTemp), expression));
                    expression = _factory.Local(initialTemp);
N
Neal Gafter 已提交
66 67
                }

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
                // EnC: We need to insert a hidden sequence point to handle function remapping in case 
                // the containing method is edited while methods invoked in the expression are being executed.
                if (!node.WasCompilerGenerated && _localRewriter.Instrument)
                {
                    expression = _localRewriter._instrumenter.InstrumentSwitchStatementExpression(node, expression, _factory);
                }

                // output the decision tree part
                LowerPatternSwitch(expression, node, result);

                // if the endpoint is reachable, we exit the switch
                if (!node.IsComplete)
                {
                    result.Add(_factory.Goto(node.BreakLabel));
                }
83
                // at this point the end of result is unreachable.
N
Neal Gafter 已提交
84

85 86 87
                _declaredTemps.AddOptional(initialTemp);
                _declaredTemps.AddRange(node.InnerLocals);

88 89 90
                // output the sections of code
                foreach (var section in node.SwitchSections)
                {
91 92 93
                    // Lifetime of these locals is expanded to the entire switch body.
                    _declaredTemps.AddRange(section.Locals);

94 95 96 97
                    // Start with the part of the decision tree that is in scope of the section variables.
                    // Its endpoint is not reachable (it jumps back into the decision tree code).
                    var sectionSyntax = (SyntaxNode)section.Syntax;
                    var sectionBuilder = _switchSections[sectionSyntax];
98

99 100 101 102 103
                    // Add labels corresponding to the labels of the switch section.
                    foreach (var label in section.SwitchLabels)
                    {
                        sectionBuilder.Add(_factory.Label(label.Label));
                    }
104

105 106
                    // Add the translated body of the switch section
                    sectionBuilder.AddRange(_localRewriter.VisitList(section.Statements));
107

108
                    sectionBuilder.Add(_factory.Goto(node.BreakLabel));
109 110 111 112 113 114 115 116 117 118

                    ImmutableArray<BoundStatement> statements = sectionBuilder.ToImmutableAndFree();
                    if (section.Locals.IsEmpty)
                    {
                        result.Add(_factory.StatementList(statements));
                    }
                    else
                    {
                        result.Add(new BoundScope(section.Syntax, section.Locals, statements));
                    }
119 120
                    // at this point the end of result is unreachable.
                }
N
Neal Gafter 已提交
121

122
                result.Add(_factory.Label(node.BreakLabel));
123

124
                BoundStatement translatedSwitch = _factory.Block(_declaredTemps.ToImmutableArray(), node.InnerLocalFunctions, result.ToImmutableAndFree());
125

126 127 128 129 130 131 132 133
                // Only add instrumentation (such as a sequence point) if the node is not compiler-generated.
                if (!node.WasCompilerGenerated && _localRewriter.Instrument)
                {
                    translatedSwitch = _localRewriter._instrumenter.InstrumentPatternSwitchStatement(node, translatedSwitch);
                }

                return translatedSwitch;
            }
134

135 136 137 138
            /// <summary>
            /// Lower the given pattern switch statement into a decision tree and then to a sequence of statements into the given statement builder.
            /// </summary>
            private void LowerPatternSwitch(BoundExpression loweredExpression, BoundPatternSwitchStatement node, ArrayBuilder<BoundStatement> loweredDecisionTree)
N
Neal Gafter 已提交
139
            {
140 141 142 143 144 145 146 147 148 149 150
                var decisionTree = LowerToDecisionTree(loweredExpression, node);
                LowerDecisionTree(loweredExpression, decisionTree, loweredDecisionTree);
            }

            private DecisionTree LowerToDecisionTree(
                BoundExpression loweredExpression,
                BoundPatternSwitchStatement node)
            {
                var loweredDecisionTree = DecisionTree.Create(loweredExpression, loweredExpression.Type, _enclosingSymbol);
                BoundPatternSwitchLabel defaultLabel = null;
                SyntaxNode defaultSection = null;
151 152
                foreach (var section in node.SwitchSections)
                {
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
                    var sectionSyntax = (SyntaxNode)section.Syntax;
                    foreach (var label in section.SwitchLabels)
                    {
                        var loweredLabel = LowerSwitchLabel(label);
                        if (loweredLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel)
                        {
                            if (defaultLabel != null)
                            {
                                // duplicate switch label will have been reported during initial binding.
                            }
                            else
                            {
                                defaultLabel = loweredLabel;
                                defaultSection = sectionSyntax;
                            }
                        }
                        else
                        {
                            Syntax = label.Syntax;
                            AddToDecisionTree(loweredDecisionTree, sectionSyntax, loweredLabel);
                        }
                    }
                }

                if (defaultLabel != null)
                {
                    Add(loweredDecisionTree, (e, t) => new DecisionTree.Guarded(loweredExpression, loweredExpression.Type, default(ImmutableArray<KeyValuePair<BoundExpression, BoundExpression>>), defaultSection, null, defaultLabel));
180
                }
181 182 183 184 185 186 187 188 189

                // We discard use-site diagnostics, as they have been reported during initial binding.
                _useSiteDiagnostics.Clear();
                return loweredDecisionTree;
            }

            private BoundPatternSwitchLabel LowerSwitchLabel(BoundPatternSwitchLabel label)
            {
                return label.Update(label.Label, _localRewriter.LowerPattern(label.Pattern), _localRewriter.VisitExpression(label.Guard), label.IsReachable);
190 191 192 193 194
            }

            /// <summary>
            /// Lower the given decision tree into the given statement builder.
            /// </summary>
195
            private void LowerDecisionTree(BoundExpression expression, DecisionTree decisionTree, ArrayBuilder<BoundStatement> loweredDecisionTree)
196
            {
197
                // build a decision tree to dispatch the switch statement
198 199
                var oldLoweredDecisionTree = this._loweredDecisionTree;
                this._loweredDecisionTree = loweredDecisionTree;
200
                LowerDecisionTree(expression, decisionTree);
201
                this._loweredDecisionTree = oldLoweredDecisionTree;
202 203
            }

204
            private void LowerDecisionTree(BoundExpression expression, DecisionTree decisionTree)
205
            {
206 207 208 209
                if (decisionTree == null)
                {
                    return;
                }
210 211 212 213 214 215 216 217

                // If the input expression was a constant or a simple read of a local, then that is the
                // decision tree's expression. Otherwise it is a newly created temp, to which we must
                // assign the switch expression.
                if (decisionTree.Temp != null)
                {
                    // Store the input expression into a temp
                    if (decisionTree.Expression != expression)
N
Neal Gafter 已提交
218
                    {
219
                        _loweredDecisionTree.Add(_factory.Assignment(decisionTree.Expression, expression));
N
Neal Gafter 已提交
220
                    }
221

222
                    if (_declaredTempSet.Add(decisionTree.Temp))
N
Neal Gafter 已提交
223
                    {
224
                        _declaredTemps.Add(decisionTree.Temp);
N
Neal Gafter 已提交
225
                    }
226
                    else
N
Neal Gafter 已提交
227
                    {
228 229
                        // we should only attempt to declare each temp once.
                        throw ExceptionUtilities.Unreachable;
N
Neal Gafter 已提交
230
                    }
231
                }
N
Neal Gafter 已提交
232

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                switch (decisionTree.Kind)
                {
                    case DecisionTree.DecisionKind.ByType:
                        {
                            LowerDecisionTree((DecisionTree.ByType)decisionTree);
                            return;
                        }
                    case DecisionTree.DecisionKind.ByValue:
                        {
                            LowerDecisionTree((DecisionTree.ByValue)decisionTree);
                            return;
                        }
                    case DecisionTree.DecisionKind.Guarded:
                        {
                            LowerDecisionTree((DecisionTree.Guarded)decisionTree);
                            return;
                        }
                    default:
                        throw ExceptionUtilities.UnexpectedValue(decisionTree.Kind);
                }
N
Neal Gafter 已提交
253 254
            }

255
            private void LowerDecisionTree(DecisionTree.ByType byType)
N
Neal Gafter 已提交
256
            {
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
                var inputConstant = byType.Expression.ConstantValue;
                if (inputConstant != null)
                {
                    if (inputConstant.IsNull)
                    {
                        // input is the constant null
                        LowerDecisionTree(byType.Expression, byType.WhenNull);
                        if (byType.WhenNull?.MatchIsComplete != true)
                        {
                            LowerDecisionTree(byType.Expression, byType.Default);
                        }
                    }
                    else
                    {
                        // input is a non-null constant
                        foreach (var kvp in byType.TypeAndDecision)
                        {
                            LowerDecisionTree(byType.Expression, kvp.Value);
275 276 277 278
                            if (kvp.Value.MatchIsComplete)
                            {
                                return;
                            }
279
                        }
280

281 282 283 284 285 286
                        LowerDecisionTree(byType.Expression, byType.Default);
                    }
                }
                else
                {
                    var defaultLabel = _factory.GenerateLabel("byTypeDefault");
N
Neal Gafter 已提交
287

288
                    // input is not a constant
289
                    if (byType.Type.CanContainNull())
290 291 292 293
                    {
                        // first test for null
                        var notNullLabel = _factory.GenerateLabel("notNull");
                        var inputExpression = byType.Expression;
294 295
                        var objectType = _factory.SpecialType(SpecialType.System_Object);
                        var nullValue = _factory.Null(objectType);
296
                        BoundExpression notNull = byType.Type.IsNullableType()
297
                            ? _localRewriter.RewriteNullableNullEquality(_factory.Syntax, BinaryOperatorKind.NullableNullNotEqual, byType.Expression, nullValue, _factory.SpecialType(SpecialType.System_Boolean))
298
                            : _factory.ObjectNotEqual(nullValue, _factory.Convert(objectType, byType.Expression));
299
                        _loweredDecisionTree.Add(_factory.ConditionalGoto(notNull, notNullLabel, true));
300
                        LowerDecisionTree(byType.Expression, byType.WhenNull);
301 302 303 304 305
                        if (byType.WhenNull?.MatchIsComplete != true)
                        {
                            _loweredDecisionTree.Add(_factory.Goto(defaultLabel));
                        }

306
                        _loweredDecisionTree.Add(_factory.Label(notNullLabel));
307 308 309 310 311
                    }
                    else
                    {
                        Debug.Assert(byType.WhenNull == null);
                    }
N
Neal Gafter 已提交
312

313 314 315 316 317 318 319
                    foreach (var td in byType.TypeAndDecision)
                    {
                        // then test for each type, sequentially
                        var type = td.Key;
                        var decision = td.Value;
                        var failLabel = _factory.GenerateLabel("failedDecision");
                        var testAndCopy = TypeTestAndCopyToTemp(byType.Expression, decision.Expression);
320
                        _loweredDecisionTree.Add(_factory.ConditionalGoto(testAndCopy, failLabel, false));
321
                        LowerDecisionTree(decision.Expression, decision);
322
                        _loweredDecisionTree.Add(_factory.Label(failLabel));
323 324 325
                    }

                    // finally, the default for when no type matches
326
                    _loweredDecisionTree.Add(_factory.Label(defaultLabel));
327 328
                    LowerDecisionTree(byType.Expression, byType.Default);
                }
N
Neal Gafter 已提交
329 330
            }

331 332 333 334 335 336 337
            private BoundExpression TypeTestAndCopyToTemp(BoundExpression input, BoundExpression temp)
            {
                // invariant: the input has already been tested, to ensure it is not null
                if (input == temp)
                {
                    return _factory.Literal(true);
                }
N
Neal Gafter 已提交
338

339
                Debug.Assert(temp.Kind == BoundKind.Local);
340
                return _localRewriter.MakeIsDeclarationPattern(_factory.Syntax, input, temp, requiresNullTest: false);
341 342 343
            }

            private void LowerDecisionTree(DecisionTree.ByValue byValue)
N
Neal Gafter 已提交
344
            {
345 346 347
                if (byValue.Expression.ConstantValue != null)
                {
                    LowerConstantValueDecision(byValue);
N
Neal Gafter 已提交
348
                    return;
349
                }
N
Neal Gafter 已提交
350

351 352 353 354 355 356
                if (byValue.ValueAndDecision.Count == 0)
                {
                    LowerDecisionTree(byValue.Expression, byValue.Default);
                    return;
                }

357
                if (byValue.Type.SpecialType == SpecialType.System_Boolean)
358
                {
359 360 361 362 363
                    LowerBooleanSwitch(byValue);
                }
                else
                {
                    LowerBasicSwitch(byValue);
364 365
                }
            }
N
Neal Gafter 已提交
366

367
            private void LowerConstantValueDecision(DecisionTree.ByValue byValue)
N
Neal Gafter 已提交
368
            {
369 370 371 372 373 374
                var value = byValue.Expression.ConstantValue.Value;
                Debug.Assert(value != null);
                DecisionTree onValue;
                if (byValue.ValueAndDecision.TryGetValue(value, out onValue))
                {
                    LowerDecisionTree(byValue.Expression, onValue);
375 376 377 378
                    if (onValue.MatchIsComplete)
                    {
                        return;
                    }
379
                }
380 381

                LowerDecisionTree(byValue.Expression, byValue.Default);
N
Neal Gafter 已提交
382 383
            }

384 385 386 387 388 389
            /// <summary>
            /// Add a branch in the lowered decision tree to a label for a matched
            /// pattern, and then produce a statement for the target of that branch
            /// that binds the pattern variables.
            /// </summary>
            /// <param name="bindings">The source/destination pairs for the assignments</param>
390 391 392 393
            /// <param name="addBindings">A builder to which the label and binding assignments are added</param>
            private void AddBindingsForCase(
                ImmutableArray<KeyValuePair<BoundExpression, BoundExpression>> bindings,
                ArrayBuilder<BoundStatement> addBindings)
394 395 396 397
            {
                var patternMatched = _factory.GenerateLabel("patternMatched");
                _loweredDecisionTree.Add(_factory.Goto(patternMatched));

398 399
                // Hide the code that binds pattern variables in a hidden sequence point
                addBindings.Add(_factory.HiddenSequencePoint());
400 401 402 403 404
                addBindings.Add(_factory.Label(patternMatched));
                if (!bindings.IsDefaultOrEmpty)
                {
                    foreach (var kv in bindings)
                    {
405 406
                        var loweredRight = kv.Key;
                        var loweredLeft = kv.Value;
V
VSadov 已提交
407
                        addBindings.Add(_factory.ExpressionStatement(
408 409
                            _localRewriter.MakeStaticAssignmentOperator(
                                _factory.Syntax, loweredLeft, loweredRight, RefKind.None, loweredLeft.Type, false)));
410 411 412 413
                    }
                }
            }

414
            private void LowerDecisionTree(DecisionTree.Guarded guarded)
N
Neal Gafter 已提交
415
            {
416
                var sectionBuilder = this._switchSections[guarded.SectionSyntax];
417 418 419 420 421
                var targetLabel = guarded.Label.Label;
                Debug.Assert(guarded.Guard?.ConstantValue != ConstantValue.False);
                if (guarded.Guard == null || guarded.Guard.ConstantValue == ConstantValue.True)
                {
                    // unconditional
422
                    Debug.Assert(guarded.Default == null);
423
                    if (guarded.Bindings.IsDefaultOrEmpty)
N
Neal Gafter 已提交
424
                    {
425
                        _loweredDecisionTree.Add(_factory.Goto(targetLabel));
N
Neal Gafter 已提交
426
                    }
427
                    else
N
Neal Gafter 已提交
428
                    {
429
                        // with bindings
430
                        AddBindingsForCase(guarded.Bindings, sectionBuilder);
431
                        sectionBuilder.Add(_factory.Goto(targetLabel));
N
Neal Gafter 已提交
432
                    }
433 434 435
                }
                else
                {
436 437
                    AddBindingsForCase(guarded.Bindings, sectionBuilder);
                    var guardTest = _factory.ConditionalGoto(guarded.Guard, targetLabel, true);
438 439

                    // Only add instrumentation (such as a sequence point) if the node is not compiler-generated.
440
                    if (!guarded.Guard.WasCompilerGenerated && _localRewriter.Instrument)
441
                    {
442
                        guardTest = _localRewriter._instrumenter.InstrumentPatternSwitchWhenClauseConditionalGotoBody(guarded.Guard, guardTest);
443 444 445 446
                    }

                    sectionBuilder.Add(guardTest);

447 448
                    var guardFailed = _factory.GenerateLabel("guardFailed");
                    sectionBuilder.Add(_factory.Goto(guardFailed));
449
                    _loweredDecisionTree.Add(_factory.Label(guardFailed));
450 451

                    LowerDecisionTree(guarded.Expression, guarded.Default);
452
                }
N
Neal Gafter 已提交
453
            }
N
Neal Gafter 已提交
454

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
            // For switch statements, we have an option of completely rewriting the switch header
            // and switch sections into simpler constructs, i.e. we can rewrite the switch header
            // using bound conditional goto statements and the rewrite the switch sections into
            // bound labeled statements.
            //
            // However, all the logic for emitting the switch jump tables is language agnostic
            // and includes IL optimizations. Hence we delay the switch jump table generation
            // till the emit phase. This way we also get additional benefit of sharing this code
            // between both VB and C# compilers.
            //
            // For string switch statements, we need to determine if we are generating a hash
            // table based jump table or a non hash jump table, i.e. linear string comparisons
            // with each case label. We use the Dev10 Heuristic to determine this
            // (see SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch() for details).
            // If we are generating a hash table based jump table, we use a simple
            // hash function to hash the string constants corresponding to the case labels.
            // See SwitchStringJumpTableEmitter.ComputeStringHash().
            // We need to emit this same function to compute the hash value into the compiler generated
            // <PrivateImplementationDetails> class.
            // If we have at least one string switch statement in a module that needs a
            // hash table based jump table, we generate a single public string hash synthesized method
            // that is shared across the module.
            private void LowerBasicSwitch(DecisionTree.ByValue byValue)
            {
                var switchSections = ArrayBuilder<BoundSwitchSection>.GetInstance();
                var noValueMatches = _factory.GenerateLabel("noValueMatches");
                var underlyingSwitchType = byValue.Type.IsEnumType() ? byValue.Type.GetEnumUnderlyingType() : byValue.Type;
                foreach (var vd in byValue.ValueAndDecision)
                {
                    var value = vd.Key;
                    var decision = vd.Value;
                    var constantValue = ConstantValue.Create(value, underlyingSwitchType.SpecialType);
                    var constantExpression = new BoundLiteral(_factory.Syntax, constantValue, underlyingSwitchType);
                    var label = _factory.GenerateLabel("case+" + value);
                    var switchLabel = new BoundSwitchLabel(_factory.Syntax, label, constantExpression, constantValue);
                    var forValue = ArrayBuilder<BoundStatement>.GetInstance();
                    LowerDecisionTree(byValue.Expression, decision, forValue);
492 493 494 495 496
                    if (!decision.MatchIsComplete)
                    {
                        forValue.Add(_factory.Goto(noValueMatches));
                    }

497 498 499 500 501 502
                    var section = new BoundSwitchSection(_factory.Syntax, ImmutableArray.Create(switchLabel), forValue.ToImmutableAndFree());
                    switchSections.Add(section);
                }

                var rewrittenSections = switchSections.ToImmutableAndFree();
                MethodSymbol stringEquality = null;
503
                if (underlyingSwitchType.SpecialType == SpecialType.System_String)
504
                {
505 506
                    _localRewriter.EnsureStringHashFunction(rewrittenSections, _factory.Syntax);
                    stringEquality = _localRewriter.GetSpecialTypeMethod(_factory.Syntax, SpecialMember.System_String__op_Equality);
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
                }

                // The BoundSwitchStatement requires a constant target when there are no sections, so we accomodate that here.
                var constantTarget = rewrittenSections.IsEmpty ? noValueMatches : null;
                var switchStatement = new BoundSwitchStatement(
                    _factory.Syntax, null, _factory.Convert(underlyingSwitchType, byValue.Expression),
                    constantTarget,
                    ImmutableArray<LocalSymbol>.Empty, ImmutableArray<LocalFunctionSymbol>.Empty,
                    rewrittenSections, noValueMatches, stringEquality);
                // The bound switch statement implicitly defines the label noValueMatches at the end, so we do not add it explicitly.

                switch (underlyingSwitchType.SpecialType)
                {
                    case SpecialType.System_Boolean:
                        // boolean switch is handled in LowerBooleanSwitch, not here.
                        throw ExceptionUtilities.Unreachable;
523

524
                    case SpecialType.System_String:
525 526 527 528 529 530 531 532 533 534
                    case SpecialType.System_Byte:
                    case SpecialType.System_Char:
                    case SpecialType.System_Int16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_SByte:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_UInt64:
                        {
535
                            // emit knows how to efficiently generate code for these kinds of switches.
536 537 538 539 540 541
                            _loweredDecisionTree.Add(switchStatement);
                            break;
                        }

                    default:
                        {
542 543 544
                            // other types, such as float, double, and decimal, are not currently
                            // handled by emit and must be lowered here.
                            _loweredDecisionTree.Add(LowerNonprimitiveSwitch(switchStatement));
545 546
                            break;
                        }
547 548 549 550 551
                }

                LowerDecisionTree(byValue.Expression, byValue.Default);
            }

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
            private BoundStatement LowerNonprimitiveSwitch(BoundSwitchStatement switchStatement)
            {
                // Here we handle "other" types, such as float, double, and decimal, by
                // lowering the BoundSwitchStatement.
                // We compare the constant values using value.Equals(input), using ordinary
                // overload resolution. Note that we cannot and do not rely on switching
                // on the hash code, as it may not be consistent with the behavior of Equals;
                // see https://github.com/dotnet/coreclr/issues/6237. Also, the hash code is
                // not guaranteed to be the same on the compilation platform as the runtime
                // platform.
                // CONSIDER: can we improve the quality of the code using comparisons, like
                //           we do for other numeric types, by generating a series of tests
                //           that use divide-and-conquer to efficiently find a matching value?
                //           If so, we should use the BoundSwitchStatement and do that in emit.
                //           Moreover, we should be able to use `==` rather than `.Equals`
                //           for cases (such as non-NaN) where we know the result to be the same.
                var rewrittenSections = switchStatement.SwitchSections;
                var expression = switchStatement.Expression;
                var noValueMatches = switchStatement.BreakLabel;
                Debug.Assert(switchStatement.LoweredPreambleOpt == null);
                Debug.Assert(switchStatement.InnerLocals.IsDefaultOrEmpty);
                Debug.Assert(switchStatement.InnerLocalFunctions.IsDefaultOrEmpty);
                Debug.Assert(switchStatement.StringEquality == null);
                LabelSymbol nextLabel = null;
                var builder = ArrayBuilder<BoundStatement>.GetInstance();
                foreach (var section in rewrittenSections)
                {
                    foreach (var boundSwitchLabel in section.SwitchLabels)
                    {
                        if (nextLabel != null)
                        {
                            builder.Add(_factory.Label(nextLabel));
                        }
                        nextLabel = _factory.GenerateLabel("failcase+" + section.SwitchLabels[0].ConstantValueOpt.Value);

                        Debug.Assert(boundSwitchLabel.ConstantValueOpt != null);
                        // generate (if (value.Equals(input)) goto label;
589
                        var literal = _localRewriter.MakeLiteral(_factory.Syntax, boundSwitchLabel.ConstantValueOpt, expression.Type);
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
                        var condition = _factory.InstanceCall(literal, "Equals", expression);
                        if (!condition.HasErrors && condition.Type.SpecialType != SpecialType.System_Boolean)
                        {
                            var call = (BoundCall)condition;
                            // '{1} {0}' has the wrong return type
                            _factory.Diagnostics.Add(ErrorCode.ERR_BadRetType, boundSwitchLabel.Syntax.GetLocation(), call.Method, call.Type);
                        }

                        builder.Add(_factory.ConditionalGoto(condition, boundSwitchLabel.Label, true));
                        builder.Add(_factory.Goto(nextLabel));
                    }

                    foreach (var boundSwitchLabel in section.SwitchLabels)
                    {
                        builder.Add(_factory.Label(boundSwitchLabel.Label));
                    }

                    builder.Add(_factory.Block(section.Statements));
                    // this location should not be reachable.
                }

                Debug.Assert(nextLabel != null);
                builder.Add(_factory.Label(nextLabel));
                builder.Add(_factory.Label(noValueMatches));
                return _factory.Block(builder.ToImmutableAndFree());
            }

617 618 619 620 621 622
            private void LowerBooleanSwitch(DecisionTree.ByValue byValue)
            {
                switch (byValue.ValueAndDecision.Count)
                {
                    case 0:
                        {
623 624
                            // this should have been handled in the caller.
                            throw ExceptionUtilities.Unreachable;
625 626 627 628 629
                        }
                    case 1:
                        {
                            DecisionTree decision;
                            bool onBoolean = byValue.ValueAndDecision.TryGetValue(true, out decision);
630 631 632 633 634
                            if (!onBoolean)
                            {
                                byValue.ValueAndDecision.TryGetValue(false, out decision);
                            }

635 636
                            Debug.Assert(decision != null);
                            var onOther = _factory.GenerateLabel("on" + !onBoolean);
637
                            _loweredDecisionTree.Add(_factory.ConditionalGoto(byValue.Expression, onOther, !onBoolean));
638 639
                            LowerDecisionTree(byValue.Expression, decision);
                            // if we fall through here, that means the match was not complete and we invoke the default part
640
                            _loweredDecisionTree.Add(_factory.Label(onOther));
641 642 643 644 645 646 647 648 649 650 651
                            LowerDecisionTree(byValue.Expression, byValue.Default);
                            break;
                        }
                    case 2:
                        {
                            DecisionTree trueDecision, falseDecision;
                            bool hasTrue = byValue.ValueAndDecision.TryGetValue(true, out trueDecision);
                            bool hasFalse = byValue.ValueAndDecision.TryGetValue(false, out falseDecision);
                            Debug.Assert(hasTrue && hasFalse);
                            var tryAnother = _factory.GenerateLabel("tryAnother");
                            var onFalse = _factory.GenerateLabel("onFalse");
652
                            _loweredDecisionTree.Add(_factory.ConditionalGoto(byValue.Expression, onFalse, false));
653
                            LowerDecisionTree(byValue.Expression, trueDecision);
654 655
                            _loweredDecisionTree.Add(_factory.Goto(tryAnother));
                            _loweredDecisionTree.Add(_factory.Label(onFalse));
656
                            LowerDecisionTree(byValue.Expression, falseDecision);
657
                            _loweredDecisionTree.Add(_factory.Label(tryAnother));
658 659 660 661 662 663 664 665 666
                            // if both true and false (i.e. all values) are fully handled, there should be no default.
                            Debug.Assert(!trueDecision.MatchIsComplete || !falseDecision.MatchIsComplete || byValue.Default == null);
                            LowerDecisionTree(byValue.Expression, byValue.Default);
                            break;
                        }
                    default:
                        throw ExceptionUtilities.UnexpectedValue(byValue.ValueAndDecision.Count);
                }
            }
N
Neal Gafter 已提交
667 668 669
        }
    }
}