Skip to content

Commit

Permalink
Add small morph peep (#45463)
Browse files Browse the repository at this point in the history
Convert `x % 2^c == 0` to `x & (2^c-1) == 0` to generate better code.
  • Loading branch information
BruceForstall committed Apr 29, 2021
1 parent 964b500 commit eb7ef11
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/coreclr/jit/morph.cpp
Expand Up @@ -13444,6 +13444,31 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac)
break;
}

// Pattern-matching optimization:
// (a % c) ==/!= 0
// for power-of-2 constant `c`
// =>
// a & (c - 1) ==/!= 0
// For integer `a`, even if negative.
if (opts.OptimizationEnabled())
{
GenTree* op1 = tree->AsOp()->gtOp1;
GenTree* op2 = tree->AsOp()->gtOp2;
if (op1->OperIs(GT_MOD) && varTypeIsIntegral(op1->TypeGet()) && op2->IsIntegralConst(0))
{
GenTree* op1op2 = op1->AsOp()->gtOp2;
if (op1op2->IsCnsIntOrI())
{
ssize_t modValue = op1op2->AsIntCon()->IconValue();
if (isPow2(modValue))
{
op1->SetOper(GT_AND); // Change % => &
op1op2->AsIntConCommon()->SetIconValue(modValue - 1); // Change c => c - 1
}
}
}
}

cns2 = op2;

/* Check for "(expr +/- icon1) ==/!= (non-zero-icon2)" */
Expand Down

0 comments on commit eb7ef11

Please sign in to comment.