Author: Akash Manna Date: 2026-11-19T03:37:18Z New Revision: 43d95c14fc54a4244a6ee736042a2dee4262133a
URL: https://github.com/llvm/llvm-project/commit/43d95c14fc54a4244a6ee736042a2dee4262133a DIFF: https://github.com/llvm/llvm-project/commit/43d95c14fc54a4244a6ee736042a2dee4262133a.diff LOG: [Clang] Fix crash on a block capturing this in an aggregate's default member initializer (#243509) Fixes #229323 `computeBlockInfo` typed a block's captured `this` from `CurFuncDecl`, assuming the literal is emitted in a member function of that class. A default member initializer is emitted wherever the object is initialized, which for an aggregate can be a free function, so the `cast<CXXMethodDecl>` asserted. Closures nested in such an initializer have no `CurFuncDecl` at all and failed the same way even inside a constructor. `BlockDecl` now records the type of the captured `this`, which Sema knows at the capture, serialized like the other captures; `computeBlockInfo` and the block debug info read it instead of inferring it. An enclosing block or captured region is no longer marked as capturing `*this` by copy when a nested lambda does, so the recorded type is always the pointer. AI Assisted! Added: Modified: clang/docs/ReleaseNotes.md clang/include/clang/AST/Decl.h clang/include/clang/AST/DeclBase.h clang/lib/AST/Decl.cpp clang/lib/CodeGen/CGBlocks.cpp clang/lib/CodeGen/CGDebugInfo.cpp clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/SemaExprCXX.cpp clang/lib/Sema/SemaLambda.cpp clang/lib/Serialization/ASTReaderDecl.cpp clang/lib/Serialization/ASTWriterDecl.cpp clang/test/CodeGenCXX/blocks.cpp clang/test/DebugInfo/ObjCXX/block-capture-this.mm clang/test/PCH/block-helpers.cpp clang/test/PCH/block-helpers.h Removed: ################################################################################ diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md index 060c9a2c917498..b0f07484695b54 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -909,6 +909,7 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and - Fixed an ICE that occurred when a structured binding pack is expanded outside the lambda where it was declared. (#GH214160) - Fixed a crash when a statement expression in the initializer of a new-expression starts with a loop or a label. (#GH175427) - Fixed a crash in an implicit assignment operator when a `noreturn` member or base `operator=` is followed by trivially copyable members. (#GH111612) +- Fixed a crash when a block in a default member initializer captures `this` and the class is aggregate-initialized outside of its member functions. (#GH229323) - Fixed a bug where a stray closing curley brace in an OpenMP/OpenACC pragma could cause pragma parsing issues when inside of a member function. (#GH214195) - Fixed a bug where preprocessor directives following comments were not correctly recognized when using -C. (#GH48361) - Fixed a crash when declaring a member template within a local class inside an OpenMP region. (#GH216052) diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h index 3048e14a2da1f0..4104ddc89c50f9 100644 --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -4919,6 +4919,9 @@ class BlockDecl : public Decl, public DeclContext { unsigned ManglingNumber = 0; Decl *ManglingContextDecl = nullptr; + /// The type of the captured 'this' pointer; null if not captured. + QualType CXXThisType; + protected: BlockDecl(DeclContext *DC, SourceLocation CaretLoc); @@ -4985,8 +4988,8 @@ class BlockDecl : public Decl, public DeclContext { capture_const_iterator capture_begin() const { return captures().begin(); } capture_const_iterator capture_end() const { return captures().end(); } - bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; } - void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; } + bool capturesCXXThis() const { return !CXXThisType.isNull(); } + QualType getCXXThisType() const { return CXXThisType; } bool blockMissingReturnType() const { return BlockDeclBits.BlockMissingReturnType; @@ -5017,7 +5020,7 @@ class BlockDecl : public Decl, public DeclContext { bool capturesVariable(const VarDecl *var) const; void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, - bool CapturesCXXThis); + QualType CXXThisType); unsigned getBlockManglingNumber() const { return ManglingNumber; } diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h index 317486e9c4ec6a..44caeae238d282 100644 --- a/clang/include/clang/AST/DeclBase.h +++ b/clang/include/clang/AST/DeclBase.h @@ -1995,8 +1995,6 @@ class DeclContext { LLVM_PREFERRED_TYPE(bool) uint64_t IsVariadic : 1; LLVM_PREFERRED_TYPE(bool) - uint64_t CapturesCXXThis : 1; - LLVM_PREFERRED_TYPE(bool) uint64_t BlockMissingReturnType : 1; LLVM_PREFERRED_TYPE(bool) uint64_t IsConversionFromLambda : 1; diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp index 39fa98e023c5db..e89938d230dbbf 100644 --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -5545,7 +5545,6 @@ unsigned RecordDecl::getODRHash() { BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc) : Decl(Block, DC, CaretLoc), DeclContext(Block) { setIsVariadic(false); - setCapturesCXXThis(false); setBlockMissingReturnType(true); setIsConversionFromLambda(false); setDoesNotEscape(false); @@ -5564,8 +5563,8 @@ void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { } void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, - bool CapturesCXXThis) { - this->setCapturesCXXThis(CapturesCXXThis); + QualType CXXThisType) { + this->CXXThisType = CXXThisType; this->NumCaptures = Captures.size(); if (Captures.empty()) { diff --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp index 26c34925b7a651..ba385b27c01917 100644 --- a/clang/lib/CodeGen/CGBlocks.cpp +++ b/clang/lib/CodeGen/CGBlocks.cpp @@ -582,9 +582,7 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF, // First, 'this'. if (block->capturesCXXThis()) { - assert(CGF && isa_and_nonnull<CXXMethodDecl>(CGF->CurFuncDecl) && - "Can't capture 'this' outside a method"); - QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(); + QualType thisType = block->getCXXThisType(); // Theoretically, this could be in a diff erent address space, so // don't assume standard pointer size/align. diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp index 249111b59fb965..279a7beceeba1f 100644 --- a/clang/lib/CodeGen/CGDebugInfo.cpp +++ b/clang/lib/CodeGen/CGDebugInfo.cpp @@ -6097,17 +6097,8 @@ void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, // If we have a null capture, this must be the C++ 'this' capture. if (!capture) { - QualType type; - if (auto *Method = - cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext())) - type = Method->getThisType(); - else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent())) - type = CGM.getContext().getCanonicalTagType(RDecl); - else - llvm_unreachable("unexpected block declcontext"); - - fields.push_back(createFieldType("this", type, loc, AS_public, - offsetInBits, tunit, tunit)); + fields.push_back(createFieldType("this", blockDecl->getCXXThisType(), loc, + AS_public, offsetInBits, tunit, tunit)); continue; } diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 5b63964b48daa3..571ef6ea6b19eb 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -17607,7 +17607,10 @@ ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, CopyExpr); Captures.push_back(NewCap); } - BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); + QualType CXXThisType; + if (BSI->isCXXThisCaptured()) + CXXThisType = BSI->getCXXThisCapture().getCaptureType(); + BD->setCaptures(Context, Captures, CXXThisType); // Pop the block scope now but keep it alive to the end of this function. AnalysisBasedWarnings::Policy WP = diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index 576393d4594062..e708de6981a54c 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -1395,13 +1395,15 @@ bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; --idx, --NumCapturingClosures) { CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); + // An enclosing block or captured region can only capture the pointer. + bool CaptureByCopy = ByCopy && isa<LambdaScopeInfo>(CSI); // The type of the corresponding data member (not a 'this' pointer if 'by // copy'). - QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy; + QualType CaptureType = CaptureByCopy ? ThisTy->getPointeeType() : ThisTy; bool isNested = NumCapturingClosures > 1; - CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); + CSI->addThisCapture(isNested, Loc, CaptureType, CaptureByCopy); } return false; } diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp index 970591d4801112..08526b7ec22b83 100644 --- a/clang/lib/Sema/SemaLambda.cpp +++ b/clang/lib/Sema/SemaLambda.cpp @@ -2486,7 +2486,7 @@ ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SC_None); BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false, /*nested=*/false, /*copy=*/Init.get()); - Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false); + Block->setCaptures(Context, Capture, /*CXXThisType=*/QualType()); // Add a fake function body to the block. IR generation is responsible // for filling in the actual body, which cannot be expressed as an AST. diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp b/clang/lib/Serialization/ASTReaderDecl.cpp index 145a2663424644..9412fe77abc2a9 100644 --- a/clang/lib/Serialization/ASTReaderDecl.cpp +++ b/clang/lib/Serialization/ASTReaderDecl.cpp @@ -1812,7 +1812,7 @@ void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) { BD->setDoesNotEscape(Record.readInt()); BD->setCanAvoidCopyToHeap(Record.readInt()); - bool capturesCXXThis = Record.readInt(); + QualType CXXThisType = Record.readType(); unsigned numCaptures = Record.readInt(); SmallVector<BlockDecl::Capture, 16> captures; captures.reserve(numCaptures); @@ -1825,7 +1825,7 @@ void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) { captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr)); } - BD->setCaptures(Reader.getContext(), captures, capturesCXXThis); + BD->setCaptures(Reader.getContext(), captures, CXXThisType); } void ASTDeclReader::VisitOutlinedFunctionDecl(OutlinedFunctionDecl *D) { diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp b/clang/lib/Serialization/ASTWriterDecl.cpp index bd8bc046f2874b..11a4be65ee4a21 100644 --- a/clang/lib/Serialization/ASTWriterDecl.cpp +++ b/clang/lib/Serialization/ASTWriterDecl.cpp @@ -1474,7 +1474,7 @@ void ASTDeclWriter::VisitBlockDecl(BlockDecl *D) { Record.push_back(D->isConversionFromLambda()); Record.push_back(D->doesNotEscape()); Record.push_back(D->canAvoidCopyToHeap()); - Record.push_back(D->capturesCXXThis()); + Record.AddTypeRef(D->getCXXThisType()); Record.push_back(D->getNumCaptures()); for (const auto &capture : D->captures()) { Record.AddDeclRef(capture.getVariable()); diff --git a/clang/test/CodeGenCXX/blocks.cpp b/clang/test/CodeGenCXX/blocks.cpp index d2da46b4ab48ff..a2099b22fac92a 100644 --- a/clang/test/CodeGenCXX/blocks.cpp +++ b/clang/test/CodeGenCXX/blocks.cpp @@ -274,6 +274,91 @@ namespace test10 { } } +namespace test11 { + // A block in a default member initializer captures the object being + // initialized, wherever the initializer happens to be emitted. + struct A { + int x; + int func(); + int (^callMember)() = ^{ return func(); }; + int (^useField)() = ^{ return x; }; + }; + template <class T> struct TA { + int func(); + int (^callMember)() = ^{ return func(); }; + }; + struct B { + int func(); + int (^nested)() = ^{ return ^{ return func(); }(); }; + int viaLambda = [this] { return ^{ return func(); }(); }(); + void m(); + }; + struct Other { + int y; + void m(); + static void s(); + }; + + // CHECK-LABEL: define{{.*}} void @_ZN6test112f1Ev() + // CHECK: [[T:%.*]] = alloca %"struct.test11::A", + // CHECK: [[BLOCK:%.*]] = alloca [[BLOCK_T:<{.*}>]], + // CHECK: store ptr @___ZN6test112f1Ev_block_invoke, ptr + // CHECK: [[THIS_ADDR:%.*]] = getelementptr inbounds nuw [[BLOCK_T]], ptr [[BLOCK]], i32 0, i32 5 + // CHECK-NEXT: store ptr [[T]], ptr [[THIS_ADDR]], + // CHECK: store ptr @___ZN6test112f1Ev_block_invoke_2, ptr + // CHECK: store ptr [[T]], ptr + void f1() { A t{}; } + + // CHECK-LABEL: define internal noundef i32 @___ZN6test112f1Ev_block_invoke( + // CHECK: [[THIS:%.*]] = load ptr, ptr + // CHECK-NEXT: call noundef i32 @_ZN6test111A4funcEv(ptr {{[^,]*}} [[THIS]]) + + // CHECK-LABEL: define internal noundef i32 @___ZN6test112f1Ev_block_invoke_2( + // CHECK: [[THIS:%.*]] = load ptr, ptr + // CHECK-NEXT: [[X:%.*]] = getelementptr inbounds nuw %"struct.test11::A", ptr [[THIS]], i32 0, i32 0 + // CHECK-NEXT: load i32, ptr [[X]], + + // Not the 'this' of the member function emitting the initializer. + // CHECK-LABEL: define{{.*}} void @_ZN6test115Other1mEv(ptr {{[^,]*}} %this) + // CHECK: [[T:%.*]] = alloca %"struct.test11::A", + // CHECK: [[BLOCK:%.*]] = alloca [[BLOCK_T]], + // CHECK: [[THIS_ADDR:%.*]] = getelementptr inbounds nuw [[BLOCK_T]], ptr [[BLOCK]], i32 0, i32 5 + // CHECK-NEXT: store ptr [[T]], ptr [[THIS_ADDR]], + void Other::m() { A t{}; } + + // CHECK-LABEL: define{{.*}} void @_ZN6test115Other1sEv() + // CHECK: [[T:%.*]] = alloca %"struct.test11::A", + // CHECK: store ptr [[T]], ptr + void Other::s() { A t{}; } + + // CHECK-LABEL: define{{.*}} void @_ZN6test112f2Ev() + // CHECK: [[T:%.*]] = alloca %"struct.test11::TA", + // CHECK: store ptr [[T]], ptr + void f2() { TA<int> t{}; } + + // CHECK-LABEL: define{{.*}} void @_ZN6test112f3Ev() + // CHECK: [[T:%.*]] = alloca %"struct.test11::B", + // CHECK: store ptr [[T]], ptr + void f3() { B t{}; } + + // CHECK-LABEL: define internal noundef i32 @___ZN6test112f3Ev_block_invoke( + // CHECK: [[THIS:%.*]] = load ptr, ptr + // CHECK: store ptr [[THIS]], ptr + + // CHECK-LABEL: define internal noundef i32 @___ZN6test112f3Ev_block_invoke_2( + // CHECK: [[THIS:%.*]] = load ptr, ptr + // CHECK-NEXT: call noundef i32 @_ZN6test111B4funcEv(ptr {{[^,]*}} [[THIS]]) + + // A block around a lambda that copies '*this' still captures the pointer. + // CHECK-LABEL: define{{.*}} void @_ZN6test111B1mEv( + // CHECK: alloca <{ ptr, i32, i32, ptr, ptr, ptr }>, + void B::m() { ^{ return [*this]() mutable { return func(); }(); }(); } + + // CHECK-LABEL: define internal void @__cxx_global_var_init() + // CHECK: store ptr @_ZN6test112gaE, ptr + A ga{}; +} + // Copy/dispose helper functions and block descriptors of blocks that capture // objects that are non-external and non-trivial have internal linkage. diff --git a/clang/test/DebugInfo/ObjCXX/block-capture-this.mm b/clang/test/DebugInfo/ObjCXX/block-capture-this.mm index 9464222b543b58..eafa24d6502b17 100644 --- a/clang/test/DebugInfo/ObjCXX/block-capture-this.mm +++ b/clang/test/DebugInfo/ObjCXX/block-capture-this.mm @@ -3,6 +3,7 @@ { int func() { return 1; } int (^block)() = ^{ return func(); }; + int viaLambda = [this] { return ^{ return func(); }(); }(); }; int main(int argc, const char * argv[]) { @@ -10,11 +11,21 @@ int main(int argc, const char * argv[]) { return t.block(); } +// The initializers are also emitted here, outside any member function. +void f() { + test t{}; +} + // CHECK: ![[TESTCT:[0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "test" -// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "__block_literal_1", -// CHECK-SAME: elements: ![[ELEMS:.*]]) -// CHECK: ![[ELEMS]] = !{{{.*}}, ![[THIS:[0-9]+]]} -// CHECK: ![[THIS]] = !DIDerivedType(tag: DW_TAG_member, name: "this", -// CHECK-SAME: baseType: ![[TESTCT]], +// CHECK: ![[THISPTR:[0-9]+]] = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: ![[TESTCT]], size: 64) +// The line-5 block gets a literal type per emitting function (the constructor +// and f), sharing the member list; the line-6 block is inside the lambda. +// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "__block_literal_{{[0-9]+}}", {{.*}} line: 5, size: 320, elements: ![[ELEMS5:[0-9]+]]) +// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "__block_literal_{{[0-9]+}}", {{.*}} line: 5, size: 320, elements: ![[ELEMS5]]) +// CHECK-DAG: ![[ELEMS5]] = !{{{.*}}, ![[THIS5:[0-9]+]]} +// CHECK-DAG: ![[THIS5]] = !DIDerivedType(tag: DW_TAG_member, name: "this", {{.*}} line: 5, baseType: ![[THISPTR]], size: 64, offset: 256, flags: DIFlagPublic) +// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "__block_literal_{{[0-9]+}}", {{.*}} line: 6, size: 320, elements: ![[ELEMS6:[0-9]+]]) +// CHECK-DAG: ![[ELEMS6]] = !{{{.*}}, ![[THIS6:[0-9]+]]} +// CHECK-DAG: ![[THIS6]] = !DIDerivedType(tag: DW_TAG_member, name: "this", {{.*}} line: 6, baseType: ![[THISPTR]], size: 64, offset: 256, flags: DIFlagPublic) diff --git a/clang/test/PCH/block-helpers.cpp b/clang/test/PCH/block-helpers.cpp index 89d3967566168f..ba9fd665ed5d0f 100644 --- a/clang/test/PCH/block-helpers.cpp +++ b/clang/test/PCH/block-helpers.cpp @@ -26,7 +26,14 @@ // CHECK: call void @_Block_object_dispose( // CHECK-LABEL: define linkonce_odr hidden void @__destroy_helper_block_e8_32r40r( + +// The block captures 'this'; its type comes from the PCH. +// CHECK-LABEL: define internal noundef i32 @___ZN1T1nEv_block_invoke( +// CHECK: %[[THIS:.*]] = load ptr, ptr %block.captured-this +// CHECK: getelementptr inbounds nuw %struct.T, ptr %[[THIS]], i32 0, i32 0 void test() { S s; s.m(); + T t; + t.n(); } diff --git a/clang/test/PCH/block-helpers.h b/clang/test/PCH/block-helpers.h index 3614cc7be93a06..e9c56c9b9982cd 100644 --- a/clang/test/PCH/block-helpers.h +++ b/clang/test/PCH/block-helpers.h @@ -10,3 +10,8 @@ struct S { ^{ (void)x; (void)y; }; } }; + +struct T { + int x; + int n() { return ^{ return x; }(); } +}; _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
