[PowerPC] fix a bug in redundant compare elimination
This patch fixes a bug in the redundant compare elimination reported in https://reviews.llvm.org/rL320786 and re-enables the optimization.
The redundant compare elimination assumes that we can replace signed comparison with unsigned comparison for the equality check. But due to the difference in the sign extension behavior we cannot change the opcode if the comparison is against an immediate and the most significant bit of the immediate is one.
Differential Revision: https://reviews.llvm.org/D41385
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@321147 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Target/PowerPC/PPCMIPeephole.cpp b/lib/Target/PowerPC/PPCMIPeephole.cpp
index a264072..474661a 100644
--- a/lib/Target/PowerPC/PPCMIPeephole.cpp
+++ b/lib/Target/PowerPC/PPCMIPeephole.cpp
@@ -1025,9 +1025,6 @@
// bge 0, .LBB0_4
bool PPCMIPeephole::eliminateRedundantCompare(void) {
- // FIXME: this transformation is causing miscompiles. Disabling it for now
- // until we can resolve the issue.
- return false;
bool Simplified = false;
for (MachineBasicBlock &MBB2 : *MF) {
@@ -1087,10 +1084,21 @@
// we replace it with a signed comparison if the comparison
// to be merged is a signed comparison.
// In other cases of opcode mismatch, we cannot optimize this.
- if (isEqOrNe(BI2) &&
+
+ // We cannot change opcode when comparing against an immediate
+ // if the most significant bit of the immediate is one
+ // due to the difference in sign extension.
+ auto CmpAgainstImmWithSignBit = [](MachineInstr *I) {
+ if (!I->getOperand(2).isImm())
+ return false;
+ int16_t Imm = (int16_t)I->getOperand(2).getImm();
+ return Imm < 0;
+ };
+
+ if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) &&
CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode()))
NewOpCode = CMPI1->getOpcode();
- else if (isEqOrNe(BI1) &&
+ else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) &&
getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode())
NewOpCode = CMPI2->getOpcode();
else continue;