diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp index 24713d7681b21e..fe342dc2fc6c33 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp @@ -3174,6 +3174,18 @@ Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp, unsigned BitWidth = C.getBitWidth(); ICmpInst::Predicate Pred = Cmp.getPredicate(); switch (II->getIntrinsicID()) { + case Intrinsic::ctpop: { + // (ctpop X > BitWidth - 1) --> X == -1 + Value *X = II->getArgOperand(0); + if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT) + return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X, + ConstantInt::getAllOnesValue(Ty)); + // (ctpop X < BitWidth) --> X != -1 + if (C == BitWidth && Pred == ICmpInst::ICMP_ULT) + return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X, + ConstantInt::getAllOnesValue(Ty)); + break; + } case Intrinsic::ctlz: { // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) { diff --git a/llvm/test/Transforms/InstCombine/cmp-intrinsic.ll b/llvm/test/Transforms/InstCombine/cmp-intrinsic.ll index 6519eda4149956..599a749954d2d5 100644 --- a/llvm/test/Transforms/InstCombine/cmp-intrinsic.ll +++ b/llvm/test/Transforms/InstCombine/cmp-intrinsic.ll @@ -495,7 +495,7 @@ define i1 @ctpop_ugt_bitwidth_minus_one_i8(i8 %x, i8* %p) { ; CHECK-LABEL: @ctpop_ugt_bitwidth_minus_one_i8( ; CHECK-NEXT: [[POP:%.*]] = tail call i8 @llvm.ctpop.i8(i8 [[X:%.*]]), [[RNG2:!range !.*]] ; CHECK-NEXT: store i8 [[POP]], i8* [[P:%.*]], align 1 -; CHECK-NEXT: [[CMP:%.*]] = icmp ugt i8 [[POP]], 7 +; CHECK-NEXT: [[CMP:%.*]] = icmp eq i8 [[X]], -1 ; CHECK-NEXT: ret i1 [[CMP]] ; %pop = tail call i8 @llvm.ctpop.i8(i8 %x) @@ -506,8 +506,7 @@ define i1 @ctpop_ugt_bitwidth_minus_one_i8(i8 %x, i8* %p) { define <2 x i1> @ctpop_ult_bitwidth_v2i32(<2 x i32> %x) { ; CHECK-LABEL: @ctpop_ult_bitwidth_v2i32( -; CHECK-NEXT: [[POP:%.*]] = tail call <2 x i32> @llvm.ctpop.v2i32(<2 x i32> [[X:%.*]]) -; CHECK-NEXT: [[CMP:%.*]] = icmp ult <2 x i32> [[POP]], +; CHECK-NEXT: [[CMP:%.*]] = icmp ne <2 x i32> [[X:%.*]], ; CHECK-NEXT: ret <2 x i1> [[CMP]] ; %pop = tail call <2 x i32> @llvm.ctpop.v2i32(<2 x i32> %x)