Index: llvm/lib/IR/ConstantFold.cpp =================================================================== --- llvm/lib/IR/ConstantFold.cpp +++ llvm/lib/IR/ConstantFold.cpp @@ -1582,13 +1582,21 @@ static Constant *constantFoldCompareGlobalToNull(CmpInst::Predicate Predicate, Constant *C1, Constant *C2) { const GlobalValue *GV = dyn_cast(C2); - if (!GV || !C1->isNullValue()) + if (!GV) return nullptr; // Don't try to evaluate aliases. External weak GV can be null. - if (!isa(GV) && !GV->hasExternalWeakLinkage() && + if (isa(GV) || GV->hasExternalWeakLinkage()) + return nullptr; + + // Strip away addrspacecast to see if this is derived from null. + C1 = C1->stripPointerCasts(); + + // A null pointer in the default address space cannot point to any valid + // object, regardless of the address space. + if (isa(C1) && !NullPointerIsDefined(nullptr /* F */, - GV->getType()->getAddressSpace())) { + cast(C1->getType())->getAddressSpace())) { if (Predicate == ICmpInst::ICMP_EQ) return ConstantInt::getFalse(C1->getContext()); else if (Predicate == ICmpInst::ICMP_NE) Index: llvm/test/Assembler/constant-fold-compare-null-to-global-issue58617.ll =================================================================== --- llvm/test/Assembler/constant-fold-compare-null-to-global-issue58617.ll +++ llvm/test/Assembler/constant-fold-compare-null-to-global-issue58617.ll @@ -7,7 +7,7 @@ define i1 @cmp_addrspacecast_null() { ; CHECK-LABEL: @cmp_addrspacecast_null( ; CHECK-NEXT: bb0: -; CHECK-NEXT: ret i1 icmp eq (ptr addrspace(3) addrspacecast (ptr null to ptr addrspace(3)), ptr addrspace(3) @lds) +; CHECK-NEXT: ret i1 false ; bb0: ret i1 icmp eq (ptr addrspace(3) addrspacecast (ptr null to ptr addrspace(3)), ptr addrspace(3) @lds) @@ -15,7 +15,7 @@ define i1 @cmp_addrspacecast_null_commute() { ; CHECK-LABEL: @cmp_addrspacecast_null_commute( -; CHECK-NEXT: ret i1 icmp eq (ptr addrspace(3) addrspacecast (ptr null to ptr addrspace(3)), ptr addrspace(3) @lds) +; CHECK-NEXT: ret i1 false ; ret i1 icmp eq (ptr addrspace(3) @lds, ptr addrspace(3) addrspacecast (ptr null to ptr addrspace(3))) }