Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not fold away double negation if the tree is a CSE candidate #50373

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/coreclr/jit/morph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14397,8 +14397,12 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac)

case GT_NOT:
case GT_NEG:
// Remove double negation/not
if (op1->OperIs(oper) && opts.OptimizationEnabled())
// Remove double negation/not.
// Note: this is not a safe tranformation if "tree" is a CSE candidate.
// Consider for example the following expression: NEG(NEG(OP)), where the top-level
// NEG is a CSE candidate. Were we to morph this to just OP, CSE would fail to find
// the original NEG in the statement.
if (op1->OperIs(oper) && opts.OptimizationEnabled() && !gtIsActiveCSE_Candidate(tree))
{
GenTree* child = op1->AsOp()->gtGetOp1();
return child;
Expand Down
34 changes: 34 additions & 0 deletions src/tests/JIT/opt/CSE/CSEWithDoubleNegation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.CompilerServices;

namespace CSEWithDoubleNegation
{
class DoNotMorphAwayCSEThatRepresentsDoubleNegation
{
private static int _static = 0;

static int Main(string[] args)
{
if (DoubleNeg() != 22)
{
Console.WriteLine("DoubleNeg() failed to return the expected value of 22");
return -1;
}

return 100;
}

[MethodImpl(MethodImplOptions.NoInlining)]
private static int DoubleNeg()
{
var a = 21;
_static = 42;

return 43 - (0 - (a - _static));
}
}
}

13 changes: 13 additions & 0 deletions src/tests/JIT/opt/CSE/CSEWithDoubleNegation.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
SingleAccretion marked this conversation as resolved.
Show resolved Hide resolved
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="CSEWithDoubleNegation.cs" />
</ItemGroup>
</Project>