Skip to content

Commit 2ee7179

Browse files
committed
[Clang] Make '-Wglobal-constructors` work on the GNU attributes
Summary: The `-Wglobal-constructors` option is useful for restricting the usage of global constructors / destructors. However, it currently ignores the attributes that introduce global constructors, meaning that the module can still have ctors if `-Werror` is set. If this is intentional by the user, I believe it would be more correct to push the diagnostic.
1 parent 089f988 commit 2ee7179

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7596,6 +7596,17 @@ void Sema::ProcessDeclAttributeList(
75967596
D->setInvalidDecl();
75977597
}
75987598

7599+
// Warn on global constructors and destructors created by attributes.
7600+
if (D->hasAttr<ConstructorAttr>() &&
7601+
!getDiagnostics().isIgnored(diag::warn_global_constructor,
7602+
D->getLocation()))
7603+
Diag(D->getLocation(), diag::warn_global_constructor)
7604+
<< D->getSourceRange();
7605+
if (D->hasAttr<DestructorAttr>() &&
7606+
!getDiagnostics().isIgnored(diag::warn_global_destructor,
7607+
D->getLocation()))
7608+
Diag(D->getLocation(), diag::warn_global_destructor) << D->getSourceRange();
7609+
75997610
// Do this check after processing D's attributes because the attribute
76007611
// objc_method_family can change whether the given method is in the init
76017612
// family, and it can be applied after objc_designated_initializer. This is a

clang/test/SemaCXX/attr-require-constant-initialization.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,11 @@ constexpr TestCtor<NotC> inval_constexpr(42); // expected-error {{must be initia
337337
ATTR constexpr TestCtor<NotC> inval_constexpr2(42); // expected-error {{must be initialized by a constant expression}}
338338
// expected-note@-1 {{in call to 'TestCtor(42)'}}
339339

340+
[[gnu::constructor]] void ctor() {}
341+
// expected-warning@-1 {{declaration requires a global constructor}}
342+
[[gnu::destructor]] void dtor() {}
343+
// expected-warning@-1 {{declaration requires a global destructor}}
344+
340345
#elif defined(TEST_THREE)
341346
#if defined(__cplusplus)
342347
#error This test requires C

0 commit comments

Comments
 (0)