diff --git a/src/coreclr/src/jit/flowgraph.cpp b/src/coreclr/src/jit/flowgraph.cpp index 8ba6d2f8cc7e0c..846677f482f88c 100644 --- a/src/coreclr/src/jit/flowgraph.cpp +++ b/src/coreclr/src/jit/flowgraph.cpp @@ -25869,6 +25869,14 @@ void Compiler::fgTailMergeThrows() // and there is less jumbled flow to sort out later. for (BasicBlock* block = fgLastBB; block != nullptr; block = block->bbPrev) { + // Workaround: don't consider try entry blocks as candidates + // for merging; if the canonical throw is later in the same try, + // we'll create invalid flow. + if ((block->bbFlags & BBF_TRY_BEG) != 0) + { + continue; + } + // For throw helpers the block should have exactly one statement.... // (this isn't guaranteed, but seems likely) Statement* stmt = block->firstStmt(); diff --git a/src/coreclr/tests/src/JIT/opt/ThrowHelper/ThrowHelperAtTryEntry.cs b/src/coreclr/tests/src/JIT/opt/ThrowHelper/ThrowHelperAtTryEntry.cs new file mode 100644 index 00000000000000..4b32e35247d67e --- /dev/null +++ b/src/coreclr/tests/src/JIT/opt/ThrowHelper/ThrowHelperAtTryEntry.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +// Test case where throw helper is in the try entry block. +// +// Throw helper merging is run lexically backwards, +// so the optimization may introduce a jump into the middle of the try. + +class ThrowHelperAtTryEntry +{ + static void ThrowHelper() + { + throw new Exception(); + } + + public static int Main() + { + int x = 0; + bool p = true; + try + { + ThrowHelper(); + x = -1; + if (p) ThrowHelper(); + } + catch (Exception) + { + x = 100; + } + + return x; + } +} diff --git a/src/coreclr/tests/src/JIT/opt/ThrowHelper/ThrowHelperAtTryEntry.csproj b/src/coreclr/tests/src/JIT/opt/ThrowHelper/ThrowHelperAtTryEntry.csproj new file mode 100644 index 00000000000000..4202eda08a014a --- /dev/null +++ b/src/coreclr/tests/src/JIT/opt/ThrowHelper/ThrowHelperAtTryEntry.csproj @@ -0,0 +1,13 @@ + + + Exe + + + None + True + false + + + + +