diff --git a/src/coreclr/jit/optimizer.cpp b/src/coreclr/jit/optimizer.cpp index 8e5124745e9e79..e01b125d9ff238 100644 --- a/src/coreclr/jit/optimizer.cpp +++ b/src/coreclr/jit/optimizer.cpp @@ -1377,6 +1377,19 @@ bool Compiler::optTryUnrollLoop(FlowGraphNaturalLoop* loop, bool* changedIR) return false; } + // The loop test must be both an exit and a backedge. + // FlowGraphNaturalLoop::AnalyzeIteration ensures it is an exit but we must + // make sure it is a backedge so that we can legally redirect it to the + // next iteration. If it isn't a backedge then redirecting it would skip + // all code between the loop test and the backedge. + assert(loop->ContainsBlock(iterInfo.TestBlock->GetTrueTarget()) != + loop->ContainsBlock(iterInfo.TestBlock->GetFalseTarget())); + if (!iterInfo.TestBlock->TrueTargetIs(loop->GetHeader()) && !iterInfo.TestBlock->FalseTargetIs(loop->GetHeader())) + { + JITDUMP("Failed to unroll loop " FMT_LP ": test block is not a backedge\n", loop->GetIndex()); + return false; + } + // Get the loop data: // - initial constant // - limit constant diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_97321/Runtime_97321.cs b/src/tests/JIT/Regression/JitBlue/Runtime_97321/Runtime_97321.cs new file mode 100644 index 00000000000000..240a2afab9bbb0 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_97321/Runtime_97321.cs @@ -0,0 +1,33 @@ +using System.Runtime.CompilerServices; +using Xunit; + +public class Runtime_97321 +{ + [Fact] + public static int TestEntryPoint() => Foo(false); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int Foo(bool b) + { + int sum = 1; + int i = 0; + goto Header; +Top:; + sum += 33; + +Header:; + if (b) + { + goto Header; + } + +Bottom: + i++; + if (i < 4) + { + goto Top; + } + + return sum; + } +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_97321/Runtime_97321.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_97321/Runtime_97321.csproj new file mode 100644 index 00000000000000..de6d5e08882e86 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_97321/Runtime_97321.csproj @@ -0,0 +1,8 @@ + + + True + + + + +