From 02867f0fa3e6bb1586a313a3cf4540f80538b02a Mon Sep 17 00:00:00 2001 From: Craig Topper Date: Wed, 11 Jul 2018 06:57:42 +0000 Subject: [X86] The TEST instruction is eliminated when BSF/TZCNT is used Summary: These changes cover the PR#31399. Now the ffs(x) function is lowered to (x != 0) ? llvm.cttz(x) + 1 : 0 and it corresponds to the following llvm code: %cnt = tail call i32 @llvm.cttz.i32(i32 %v, i1 true) %tobool = icmp eq i32 %v, 0 %.op = add nuw nsw i32 %cnt, 1 %add = select i1 %tobool, i32 0, i32 %.op and x86 asm code: bsfl %edi, %ecx addl $1, %ecx testl %edi, %edi movl $0, %eax cmovnel %ecx, %eax In this case the 'test' instruction can't be eliminated because the 'add' instruction modifies the EFLAGS, namely, ZF flag that is set by the 'bsf' instruction when 'x' is zero. We now produce the following code: bsfl %edi, %ecx movl $-1, %eax cmovnel %ecx, %eax addl $1, %eax Patch by Ivan Kulagin Reviewers: davide, craig.topper, spatel, RKSimon Reviewed By: craig.topper Subscribers: llvm-commits Differential Revision: https://reviews.llvm.org/D48765 llvm-svn: 336768 --- llvm/lib/Target/X86/X86ISelLowering.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'llvm/lib/Target/X86/X86ISelLowering.cpp') diff --git a/llvm/lib/Target/X86/X86ISelLowering.cpp b/llvm/lib/Target/X86/X86ISelLowering.cpp index 9c74575916e..fb923436959 100644 --- a/llvm/lib/Target/X86/X86ISelLowering.cpp +++ b/llvm/lib/Target/X86/X86ISelLowering.cpp @@ -33452,6 +33452,36 @@ static SDValue combineCMov(SDNode *N, SelectionDAG &DAG, } } + // Handle (CMOV (ADD (CTTZ X), C), C-1, (X != 0)) -> + // (ADD (CMOV (CTTZ X), -1, (X != 0)), C) or + // (CMOV C-1, (ADD (CTTZ X), C), (X == 0)) -> + // (ADD (CMOV C-1, (CTTZ X), (X == 0)), C) + if (CC == X86::COND_NE || CC == X86::COND_E) { + auto *Cnst = CC == X86::COND_E ? dyn_cast(TrueOp) + : dyn_cast(FalseOp); + SDValue Add = CC == X86::COND_E ? FalseOp : TrueOp; + + if (Cnst && Add.getOpcode() == ISD::ADD && Add.hasOneUse()) { + auto *AddOp1 = dyn_cast(Add.getOperand(1)); + SDValue AddOp2 = Add.getOperand(0); + if (AddOp1 && (AddOp2.getOpcode() == ISD::CTTZ_ZERO_UNDEF || + AddOp2.getOpcode() == ISD::CTTZ)) { + APInt Diff = Cnst->getAPIntValue() - AddOp1->getAPIntValue(); + if (CC == X86::COND_NE) { + Add = DAG.getNode(X86ISD::CMOV, DL, Add.getValueType(), AddOp2, + DAG.getConstant(Diff, DL, Add.getValueType()), + DAG.getConstant(CC, DL, MVT::i8), Cond); + } else { + Add = DAG.getNode(X86ISD::CMOV, DL, Add.getValueType(), + DAG.getConstant(Diff, DL, Add.getValueType()), + AddOp2, DAG.getConstant(CC, DL, MVT::i8), Cond); + } + return DAG.getNode(X86ISD::ADD, DL, Add.getValueType(), Add, + SDValue(AddOp1, 0)); + } + } + } + return SDValue(); } -- cgit v1.2.3