[KnownBits] Add support for X*X self-multiplication

Add KnownBits handling and unit tests for X*X self-multiplication cases which guarantee that bit1 of their results will be zero - see PR48683.

https://alive2.llvm.org/ce/z/NN_eaR

The next step will be to add suitable test coverage so this can be enabled in ValueTracking/DAG/GlobalISel - currently only a single Analysis/ScalarEvolution test is affected.

Differential Revision: https://reviews.llvm.org/D108992
This commit is contained in:
Simon Pilgrim 2021-09-07 11:43:26 +01:00
parent 36527cbe02
commit 0a07ae6ebf
3 changed files with 31 additions and 2 deletions

View File

@ -304,7 +304,8 @@ public:
KnownBits RHS);
/// Compute known bits resulting from multiplying LHS and RHS.
static KnownBits mul(const KnownBits &LHS, const KnownBits &RHS);
static KnownBits mul(const KnownBits &LHS, const KnownBits &RHS,
bool SelfMultiply = false);
/// Compute known bits from sign-extended multiply-hi.
static KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS);

View File

@ -412,10 +412,13 @@ KnownBits KnownBits::abs(bool IntMinIsPoison) const {
return KnownAbs;
}
KnownBits KnownBits::mul(const KnownBits &LHS, const KnownBits &RHS) {
KnownBits KnownBits::mul(const KnownBits &LHS, const KnownBits &RHS,
bool SelfMultiply) {
unsigned BitWidth = LHS.getBitWidth();
assert(BitWidth == RHS.getBitWidth() && !LHS.hasConflict() &&
!RHS.hasConflict() && "Operand mismatch");
assert((!SelfMultiply || (LHS.One == RHS.One && LHS.Zero == RHS.Zero)) &&
"Self multiplication knownbits mismatch");
// Compute a conservative estimate for high known-0 bits.
unsigned LeadZ =
@ -489,6 +492,14 @@ KnownBits KnownBits::mul(const KnownBits &LHS, const KnownBits &RHS) {
Res.Zero.setHighBits(LeadZ);
Res.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
Res.One = BottomKnown.getLoBits(ResultBitsKnown);
// If we're self-multiplying then bit[1] is guaranteed to be zero.
if (SelfMultiply && BitWidth > 1) {
assert(Res.One[1] == 0 &&
"Self-multiplication failed Quadratic Reciprocity!");
Res.Zero.setBit(1);
}
return Res;
}

View File

@ -267,6 +267,23 @@ TEST(KnownBitsTest, BinaryExhaustive) {
EXPECT_TRUE(ComputedAShr.One.isSubsetOf(KnownAShr.One));
});
});
// Also test 'unary' binary cases where the same argument is repeated.
ForeachKnownBits(Bits, [&](const KnownBits &Known) {
KnownBits KnownMul(Bits);
KnownMul.Zero.setAllBits();
KnownMul.One.setAllBits();
ForeachNumInKnownBits(Known, [&](const APInt &N) {
APInt Res = N * N;
KnownMul.One &= Res;
KnownMul.Zero &= ~Res;
});
KnownBits ComputedMul = KnownBits::mul(Known, Known, /*SelfMultiply*/ true);
EXPECT_TRUE(ComputedMul.Zero.isSubsetOf(KnownMul.Zero));
EXPECT_TRUE(ComputedMul.One.isSubsetOf(KnownMul.One));
});
}
TEST(KnownBitsTest, UnaryExhaustive) {