[clang] ca946f7 - [CIR] Implement null check for CXXNewExpr (#192848)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Apr 28 13:07:46 PDT 2026
Author: AbdallahRashed
Date: 2026-04-28T13:07:41-07:00
New Revision: ca946f7faea970ebea2a71394d428857d0e05205
URL: https://github.com/llvm/llvm-project/commit/ca946f7faea970ebea2a71394d428857d0e05205
DIFF: https://github.com/llvm/llvm-project/commit/ca946f7faea970ebea2a71394d428857d0e05205.diff
LOG: [CIR] Implement null check for CXXNewExpr (#192848)
When operator new is allowed to return null (e.g. nothrow new), the
initialization needs to be guarded by a null check,Previously this was
an errorNYI.
This wraps the initialization in a cir.if conditioned on the allocation
being non null, then uses cir.select to pick between the allocation
pointer and null as the result. Also removes
MissingFeatures::exprNewNullCheck.
part of https://github.com/llvm/llvm-project/issues/192328
Added:
clang/test/CIR/CodeGen/new-null.cpp
Modified:
clang/include/clang/CIR/MissingFeatures.h
clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
Removed:
################################################################################
diff --git a/clang/include/clang/CIR/MissingFeatures.h b/clang/include/clang/CIR/MissingFeatures.h
index eea858e3aa8cb..57dc48c5484ea 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -114,9 +114,6 @@ struct MissingFeatures {
static bool opCallChain() { return false; }
static bool opCallExceptionAttr() { return false; }
- // CXXNewExpr
- static bool exprNewNullCheck() { return false; }
-
// FnInfoOpts -- This is used to track whether calls are chain calls or
// instance methods. Classic codegen uses chain call to track and extra free
// register for x86 and uses instance method as a condition for a thunk
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp b/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
index 384f4679228dd..39a2068a7073f 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
@@ -1617,9 +1617,6 @@ mlir::Value CIRGenFunction::emitCXXNewExpr(const CXXNewExpr *e) {
// interesting initializer will be running sanitizers on the initialization.
bool nullCheck = e->shouldNullCheckAllocation() &&
(!allocType.isPODType(getContext()) || e->hasInitializer());
- assert(!cir::MissingFeatures::exprNewNullCheck());
- if (nullCheck)
- cgm.errorNYI(e->getSourceRange(), "emitCXXNewExpr: null check");
// If there's an operator delete, enter a cleanup to call it if an
// exception is thrown. If we do this, we'll be creating the result pointer
@@ -1629,73 +1626,115 @@ mlir::Value CIRGenFunction::emitCXXNewExpr(const CXXNewExpr *e) {
bool useNewDeleteCleanup =
e->getOperatorDelete() &&
!e->getOperatorDelete()->isReservedGlobalPlacementOperator();
- EHScopeStack::stable_iterator operatorDeleteCleanup;
- mlir::Operation *cleanupDominator = nullptr;
- if (useNewDeleteCleanup) {
- assert(!cir::MissingFeatures::typeAwareAllocation());
- enterNewDeleteCleanup(*this, e, allocation, allocSize, allocAlign,
- allocatorArgs);
- operatorDeleteCleanup = ehStack.stable_begin();
- cleanupDominator =
- cir::UnreachableOp::create(builder, getLoc(e->getSourceRange()))
- .getOperation();
- }
-
- if (allocSize != allocSizeWithoutCookie) {
- assert(e->isArray());
- allocation = cgm.getCXXABI().initializeArrayCookie(
- *this, allocation, numElements, e, allocType);
- }
mlir::Type elementTy;
- if (e->isArray()) {
- // For array new, use the allocated type to handle multidimensional arrays
- // correctly
+ // For array new, use the allocated type to handle multidimensional arrays
+ // correctly.
+ if (e->isArray())
elementTy = convertTypeForMem(e->getAllocatedType());
- } else {
+ else
elementTy = convertTypeForMem(allocType);
- }
- Address result = builder.createElementBitCast(getLoc(e->getSourceRange()),
- allocation, elementTy);
- // If we're inside a new delete cleanup, store the result pointer.
+ // Lambda that emits the init sequence: cleanup setup, cookie init,
+ // bitcast + initializer, and cleanup deactivation.
+ Address result = Address::invalid();
Address resultPtr = Address::invalid();
- if (useNewDeleteCleanup) {
- resultPtr =
- createTempAlloca(builder.getPointerTo(elementTy), result.getAlignment(),
- getLoc(e->getSourceRange()), "__new_result");
- builder.createStore(getLoc(e->getSourceRange()), result.getPointer(),
- resultPtr);
- }
+ auto emitInit = [&]() {
+ EHScopeStack::stable_iterator operatorDeleteCleanup;
+ mlir::Operation *cleanupDominator = nullptr;
+ if (useNewDeleteCleanup) {
+ assert(!cir::MissingFeatures::typeAwareAllocation());
+ enterNewDeleteCleanup(*this, e, allocation, allocSize, allocAlign,
+ allocatorArgs);
+ operatorDeleteCleanup = ehStack.stable_begin();
+ cleanupDominator =
+ cir::UnreachableOp::create(builder, getLoc(e->getSourceRange()))
+ .getOperation();
+ resultPtr = createTempAlloca(builder.getPointerTo(elementTy),
+ allocation.getAlignment(),
+ getLoc(e->getSourceRange()), "__new_result");
+ }
- // Passing pointer through launder.invariant.group to avoid propagation of
- // vptrs information which may be included in previous type.
- // To not break LTO with
diff erent optimizations levels, we do it regardless
- // of optimization level.
- if (cgm.getCodeGenOpts().StrictVTablePointers &&
- allocator->isReservedGlobalPlacementOperator())
- cgm.errorNYI(e->getSourceRange(), "emitCXXNewExpr: strict vtable pointers");
+ if (allocSize != allocSizeWithoutCookie) {
+ assert(e->isArray());
+ allocation = cgm.getCXXABI().initializeArrayCookie(
+ *this, allocation, numElements, e, allocType);
+ }
- assert(!cir::MissingFeatures::sanitizers());
+ result = builder.createElementBitCast(getLoc(e->getSourceRange()),
+ allocation, elementTy);
+
+ // Store the result pointer before initialization so that it is available
+ // to the cleanup if the initializer throws.
+ if (resultPtr.isValid())
+ builder.createStore(getLoc(e->getSourceRange()), result.getPointer(),
+ resultPtr);
+
+ // Passing pointer through launder.invariant.group to avoid propagation of
+ // vptrs information which may be included in previous type. To not break
+ // LTO with
diff erent optimizations levels, we do it regardless of
+ // optimization level.
+ if (cgm.getCodeGenOpts().StrictVTablePointers &&
+ allocator->isReservedGlobalPlacementOperator())
+ cgm.errorNYI(e->getSourceRange(),
+ "emitCXXNewExpr: strict vtable pointers");
- emitNewInitializer(*this, e, allocType, elementTy, result, numElements,
- allocSizeWithoutCookie);
+ assert(!cir::MissingFeatures::sanitizers());
- // Deactivate the 'operator delete' cleanup if we finished
- // initialization.
- if (useNewDeleteCleanup) {
- assert(operatorDeleteCleanup.isValid());
- assert(resultPtr.isValid());
- deactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
- cleanupDominator->erase();
- cir::LoadOp loadResult =
- builder.createLoad(getLoc(e->getSourceRange()), resultPtr);
- result = result.withPointer(loadResult.getResult());
+ emitNewInitializer(*this, e, allocType, elementTy, result, numElements,
+ allocSizeWithoutCookie);
+
+ // Deactivate the 'operator delete' cleanup if we finished
+ // initialization.
+ if (useNewDeleteCleanup) {
+ deactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
+ cleanupDominator->erase();
+ cir::LoadOp loadResult =
+ builder.createLoad(getLoc(e->getSourceRange()), resultPtr);
+ result = result.withPointer(loadResult.getResult());
+ }
+ };
+
+ cir::IfOp nullCheckOp;
+ if (nullCheck) {
+ mlir::Value isNotNull = builder.createPtrIsNotNull(allocation.getPointer());
+ nullCheckOp =
+ cir::IfOp::create(builder, getLoc(e->getSourceRange()), isNotNull,
+ /*withElseRegion=*/false,
+ /*thenBuilder=*/
+ [&](mlir::OpBuilder &, mlir::Location loc) {
+ emitInit();
+ builder.createYield(loc);
+ });
+ } else {
+ emitInit();
}
- assert(!cir::MissingFeatures::exprNewNullCheck());
+ mlir::Value resultValue = result.getPointer();
+
+ if (nullCheck) {
+ mlir::Type resultTy = resultValue.getType();
+
+ // If we needed a NewDeleteCleanup, allocation may have been modified
+ // inside the cir.if (e.g. by cookie adjustment). Use the result stored
+ // in the alloca instead, since the alloca dominates this point.
+ mlir::Value trueVal;
+ if (useNewDeleteCleanup) {
+ trueVal = builder.createLoad(getLoc(e->getSourceRange()), resultPtr)
+ .getResult();
+ } else {
+ trueVal = allocation.getPointer();
+ }
+ if (trueVal.getType() != resultTy)
+ trueVal = builder.createBitcast(trueVal, resultTy);
+ mlir::Value nullPtr =
+ builder.getNullPtr(resultTy, getLoc(e->getSourceRange())).getResult();
+ resultValue =
+ builder.createSelect(getLoc(e->getSourceRange()),
+ nullCheckOp.getCondition(), trueVal, nullPtr);
+ }
- return result.getPointer();
+ return resultValue;
}
void CIRGenFunction::emitDeleteCall(const FunctionDecl *deleteFD,
diff --git a/clang/test/CIR/CodeGen/new-null.cpp b/clang/test/CIR/CodeGen/new-null.cpp
new file mode 100644
index 0000000000000..1aa085e6d95d0
--- /dev/null
+++ b/clang/test/CIR/CodeGen/new-null.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fexceptions -fcxx-exceptions -fclangir -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fexceptions -fcxx-exceptions -fclangir -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --check-prefix=LLVM --input-file=%t-cir.ll %s
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-linux-gnu -fexceptions -fcxx-exceptions -emit-llvm %s -o %t.ll
+// RUN: FileCheck --check-prefix=OGCG --input-file=%t.ll %s
+
+typedef __typeof__(sizeof(int)) size_t;
+
+namespace std {
+ struct nothrow_t {};
+}
+std::nothrow_t nothrow;
+
+void *operator new(size_t, const std::nothrow_t &) throw();
+void operator delete(void *, const std::nothrow_t &) throw();
+
+struct S {
+ S();
+ ~S();
+ int a;
+};
+
+// nothrow new with non-POD type triggers null check
+S *test_nothrow_new() {
+ return new (nothrow) S;
+}
+
+// CHECK: cir.func {{.*}} @_Z16test_nothrow_newv()
+// CHECK: %[[ALLOC:.*]] = cir.call @_ZnwmRKSt9nothrow_t({{.*}}) nothrow
+// CHECK: %[[NULL:.*]] = cir.const #cir.ptr<null> : !cir.ptr<!void>
+// CHECK: %[[IS_NOT_NULL:.*]] = cir.cmp ne %[[ALLOC]], %[[NULL]] : !cir.ptr<!void>
+// CHECK: cir.if %[[IS_NOT_NULL]] {
+// CHECK: cir.cleanup.scope {
+// CHECK: %[[CAST:.*]] = cir.cast bitcast %[[ALLOC]] : !cir.ptr<!void> -> !cir.ptr<!rec_S>
+// CHECK: cir.call @_ZN1SC1Ev(%[[CAST]])
+// CHECK: } cleanup eh {
+// CHECK: cir.call @_ZdlPvRKSt9nothrow_t(%[[ALLOC]], {{.*}}) nothrow
+// CHECK: } loc(
+// CHECK: } loc(
+// CHECK-NEXT: %[[LOADED:.*]] = cir.load
+// CHECK: %[[NULL_S:.*]] = cir.const #cir.ptr<null> : !cir.ptr<!rec_S>
+// CHECK: cir.select if %[[IS_NOT_NULL]] then %[[LOADED]] else %[[NULL_S]]
+
+// LLVM: define {{.*}} ptr @_Z16test_nothrow_newv() {{.*}}personality ptr @__gxx_personality_v0
+// LLVM: %[[ALLOC:.*]] = call {{.*}} ptr @_ZnwmRKSt9nothrow_t(i64 noundef 4, {{.*}})
+// LLVM: %[[CMP:.*]] = icmp ne ptr %[[ALLOC]], null
+// LLVM: br i1 %[[CMP]], label %[[NOT_NULL:.*]], label %[[CONT:.*]]
+// LLVM: [[NOT_NULL]]:
+// LLVM: invoke void @_ZN1SC1Ev({{.*}} %[[ALLOC]])
+// LLVM: to label {{.*}} unwind label %[[LPAD:.*]]
+// LLVM: [[LPAD]]:
+// LLVM: landingpad { ptr, i32 }
+// LLVM: cleanup
+// LLVM: call void @_ZdlPvRKSt9nothrow_t({{.*}} %[[ALLOC]], {{.*}})
+// LLVM: resume
+// LLVM: [[CONT]]:
+// LLVM: select i1 %[[CMP]], ptr {{.*}}, ptr null
+
+// OGCG: define {{.*}} ptr @_Z16test_nothrow_newv() {{.*}}personality ptr @__gxx_personality_v0
+// OGCG: %[[ALLOC:.*]] = call {{.*}} ptr @_ZnwmRKSt9nothrow_t(i64 noundef 4, {{.*}})
+// OGCG: %[[IS_NULL:.*]] = icmp eq ptr %[[ALLOC]], null
+// OGCG: br i1 %[[IS_NULL]], label %[[CONT:.*]], label %[[NOT_NULL:.*]]
+// OGCG: [[NOT_NULL]]:
+// OGCG: invoke void @_ZN1SC1Ev({{.*}} %[[ALLOC]])
+// OGCG: to label %[[OK:.*]] unwind label %[[LPAD:.*]]
+// OGCG: [[OK]]:
+// OGCG: br label %[[CONT]]
+// OGCG: [[CONT]]:
+// OGCG: phi ptr
+// OGCG: [[LPAD]]:
+// OGCG: landingpad { ptr, i32 }
+// OGCG: cleanup
+// OGCG: call void @_ZdlPvRKSt9nothrow_t({{.*}} %[[ALLOC]], {{.*}})
+// OGCG: resume
+
+// nothrow new with POD + initializer triggers null check
+int *test_nothrow_new_init() {
+ return new (nothrow) int(42);
+}
+
+// CHECK: cir.func {{.*}} @_Z21test_nothrow_new_initv()
+// CHECK: %[[ALLOC:.*]] = cir.call @_ZnwmRKSt9nothrow_t({{.*}}) nothrow
+// CHECK: %[[NULL:.*]] = cir.const #cir.ptr<null> : !cir.ptr<!void>
+// CHECK: %[[IS_NOT_NULL:.*]] = cir.cmp ne %[[ALLOC]], %[[NULL]] : !cir.ptr<!void>
+// CHECK: cir.if %[[IS_NOT_NULL]] {
+// CHECK: cir.cleanup.scope {
+// CHECK: %[[CAST:.*]] = cir.cast bitcast %[[ALLOC]] : !cir.ptr<!void> -> !cir.ptr<!s32i>
+// CHECK: %[[FORTY_TWO:.*]] = cir.const #cir.int<42> : !s32i
+// CHECK: cir.store {{.*}} %[[FORTY_TWO]], %[[CAST]]
+// CHECK: } cleanup eh {
+// CHECK: cir.call @_ZdlPvRKSt9nothrow_t(%[[ALLOC]], {{.*}}) nothrow
+// CHECK: } loc(
+// CHECK: } loc(
+// CHECK-NEXT: %[[LOADED_I:.*]] = cir.load
+// CHECK: %[[NULL_I:.*]] = cir.const #cir.ptr<null> : !cir.ptr<!s32i>
+// CHECK: cir.select if %[[IS_NOT_NULL]] then %[[LOADED_I]] else %[[NULL_I]]
+
+// LLVM: define {{.*}} ptr @_Z21test_nothrow_new_initv()
+// LLVM: %[[ALLOC:.*]] = call {{.*}} ptr @_ZnwmRKSt9nothrow_t(i64 noundef 4, {{.*}})
+// LLVM: %[[CMP:.*]] = icmp ne ptr %[[ALLOC]], null
+// LLVM: br i1 %[[CMP]], label %[[NOT_NULL:.*]], label %[[CONT:.*]]
+// LLVM: [[NOT_NULL]]:
+// LLVM: store i32 42, ptr %[[ALLOC]], align 4
+// LLVM: [[CONT]]:
+// LLVM: select i1 %[[CMP]], ptr {{.*}}, ptr null
+
+// OGCG: define {{.*}} ptr @_Z21test_nothrow_new_initv()
+// OGCG: %[[ALLOC:.*]] = call {{.*}} ptr @_ZnwmRKSt9nothrow_t(i64 noundef 4, {{.*}})
+// OGCG: %[[IS_NULL:.*]] = icmp eq ptr %[[ALLOC]], null
+// OGCG: br i1 %[[IS_NULL]], label %[[CONT:.*]], label %[[NOT_NULL:.*]]
+// OGCG: [[NOT_NULL]]:
+// OGCG: store i32 42, ptr %[[ALLOC]], align 4
+// OGCG: br label %[[CONT]]
+// OGCG: [[CONT]]:
+// OGCG: phi ptr
More information about the cfe-commits
mailing list