Index: lib/Analysis/ConstantFolding.cpp =================================================================== --- lib/Analysis/ConstantFolding.cpp +++ lib/Analysis/ConstantFolding.cpp @@ -1170,7 +1170,9 @@ const DataLayout &DL, const TargetLibraryInfo *TLI) { // fold: icmp (inttoptr x), null -> icmp x, 0 + // fold: icmp null, (inttoptr x) -> icmp 0, x // fold: icmp (ptrtoint x), 0 -> icmp x, null + // fold: icmp 0, (ptrtoint x) -> icmp null, x // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y // @@ -1240,6 +1242,29 @@ Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL); } + } else if (auto *CE1 = dyn_cast(Ops1)) { + if (Ops0->isNullValue()) { + if (CE1->getOpcode() == Instruction::IntToPtr) { + Type *IntPtrTy = DL.getIntPtrType(CE1->getType()); + // Convert the integer value to the right size to ensure we get the + // proper extension or truncation. + Constant *C = ConstantExpr::getIntegerCast(CE1->getOperand(0), + IntPtrTy, false); + Constant *Null = Constant::getNullValue(C->getType()); + return ConstantFoldCompareInstOperands(Predicate, Null, C, DL, TLI); + } + + // Only do this transformation if the int is intptrty in size, otherwise + // there is a truncation or extension that we aren't modeling. + if (CE1->getOpcode() == Instruction::PtrToInt) { + Type *IntPtrTy = DL.getIntPtrType(CE1->getOperand(0)->getType()); + if (CE1->getType() == IntPtrTy) { + Constant *C = CE1->getOperand(0); + Constant *Null = Constant::getNullValue(C->getType()); + return ConstantFoldCompareInstOperands(Predicate, Null, C, DL, TLI); + } + } + } } return ConstantExpr::getCompare(Predicate, Ops0, Ops1); Index: test/Transforms/InstSimplify/compare.ll =================================================================== --- test/Transforms/InstSimplify/compare.ll +++ test/Transforms/InstSimplify/compare.ll @@ -1289,7 +1289,7 @@ define i1 @constant_fold_null_inttoptr() { ; CHECK-LABEL: @constant_fold_null_inttoptr( -; CHECK-NEXT: ret i1 icmp eq (i32* inttoptr (i64 32 to i32*), i32* null) +; CHECK-NEXT: ret i1 false ; %x = icmp eq i32* null, inttoptr (i64 32 to i32*) ret i1 %x