Skip to content

Commit a7ccecf

Browse files
AaronBallmanIanWood1
authored andcommitted
[C] Warn on uninitialized const objects (llvm#137166)
Unlike C++, C allows the definition of an uninitialized `const` object. If the object has static or thread storage duration, it is still zero-initialized, otherwise, the object is left uninitialized. In either case, the code is not compatible with C++. This adds a new diagnostic group, `-Wdefault-const-init-unsafe`, which is on by default and diagnoses any definition of a `const` object which remains uninitialized. It also adds another new diagnostic group, `-Wdefault-const-init` (which also enabled the `unsafe` variant) that diagnoses any definition of a `const` object (including ones which are zero-initialized). This diagnostic is off by default. Finally, it adds `-Wdefault-const-init` to `-Wc++-compat`. GCC diagnoses these situations under this flag. Fixes llvm#19297
1 parent 2df2105 commit a7ccecf

28 files changed

+179
-44
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,13 @@ C Language Changes
140140
- Clang now allows an ``inline`` specifier on a typedef declaration of a
141141
function type in Microsoft compatibility mode. #GH124869
142142
- Clang now allows ``restrict`` qualifier for array types with pointer elements (#GH92847).
143+
- Clang now diagnoses ``const``-qualified object definitions without an
144+
initializer. If the object is zero-initialized, it will be diagnosed under
145+
the new warning ``-Wdefault-const-init`` (which is grouped under
146+
``-Wc++-compat`` because this construct is not compatible with C++). If the
147+
object is left uninitialized, it will be diagnosed unsed the new warning
148+
``-Wdefault-const-init-unsafe`` (which is grouped under
149+
``-Wdefault-const-init``). #GH19297
143150
- Added ``-Wimplicit-void-ptr-cast``, grouped under ``-Wc++-compat``, which
144151
diagnoses implicit conversion from ``void *`` to another pointer type as
145152
being incompatible with C++. (#GH17792)

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,9 +154,11 @@ def BuiltinRequiresHeader : DiagGroup<"builtin-requires-header">;
154154
def C99Compat : DiagGroup<"c99-compat">;
155155
def C23Compat : DiagGroup<"c23-compat">;
156156
def : DiagGroup<"c2x-compat", [C23Compat]>;
157-
157+
def DefaultConstInitUnsafe : DiagGroup<"default-const-init-unsafe">;
158+
def DefaultConstInit : DiagGroup<"default-const-init", [DefaultConstInitUnsafe]>;
158159
def ImplicitVoidPtrCast : DiagGroup<"implicit-void-ptr-cast">;
159-
def CXXCompat: DiagGroup<"c++-compat", [ImplicitVoidPtrCast]>;
160+
def CXXCompat: DiagGroup<"c++-compat", [ImplicitVoidPtrCast, DefaultConstInit]>;
161+
160162
def ExternCCompat : DiagGroup<"extern-c-compat">;
161163
def KeywordCompat : DiagGroup<"keyword-compat">;
162164
def GNUCaseRange : DiagGroup<"gnu-case-range">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8197,6 +8197,16 @@ def err_address_space_qualified_new : Error<
81978197
def err_address_space_qualified_delete : Error<
81988198
"'delete' cannot delete objects of type %0 in address space '%1'">;
81998199

8200+
def note_default_init_const_member : Note<
8201+
"member %0 declared 'const' here">;
8202+
def warn_default_init_const : Warning<
8203+
"default initialization of an object of type %0%select{| with const member}1 "
8204+
"is incompatible with C++">,
8205+
InGroup<DefaultConstInit>, DefaultIgnore;
8206+
def warn_default_init_const_unsafe : Warning<
8207+
"default initialization of an object of type %0%select{| with const member}1 "
8208+
"leaves the object uninitialized and is incompatible with C++">,
8209+
InGroup<DefaultConstInitUnsafe>;
82008210
def err_default_init_const : Error<
82018211
"default initialization of an object of const type %0"
82028212
"%select{| without a user-provided default constructor}1">;

clang/lib/Parse/ParseStmt.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2154,7 +2154,7 @@ StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
21542154
FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
21552155
} else {
21562156
// In C++0x, "for (T NS:a" might not be a typo for ::
2157-
bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
2157+
bool MightBeForRangeStmt = getLangOpts().CPlusPlus || getLangOpts().ObjC;
21582158
ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
21592159
ParsedAttributes DeclSpecAttrs(AttrFactory);
21602160
DG = ParseSimpleDeclaration(

clang/lib/Sema/Sema.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1448,6 +1448,18 @@ void Sema::ActOnEndOfTranslationUnit() {
14481448
// No initialization is performed for a tentative definition.
14491449
CheckCompleteVariableDeclaration(VD);
14501450

1451+
// In C, if the definition is const-qualified and has no initializer, it
1452+
// is left uninitialized unless it has static or thread storage duration.
1453+
QualType Type = VD->getType();
1454+
if (!VD->isInvalidDecl() && !getLangOpts().CPlusPlus &&
1455+
Type.isConstQualified() && !VD->getAnyInitializer()) {
1456+
unsigned DiagID = diag::warn_default_init_const_unsafe;
1457+
if (VD->getStorageDuration() == SD_Static ||
1458+
VD->getStorageDuration() == SD_Thread)
1459+
DiagID = diag::warn_default_init_const;
1460+
Diag(VD->getLocation(), DiagID) << Type << /*not a field*/ 0;
1461+
}
1462+
14511463
// Notify the consumer that we've completed a tentative definition.
14521464
if (!VD->isInvalidDecl())
14531465
Consumer.CompleteTentativeDefinition(VD);

clang/lib/Sema/SemaDecl.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14339,6 +14339,16 @@ void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
1433914339
return;
1434014340
}
1434114341

14342+
// In C, if the definition is const-qualified and has no initializer, it
14343+
// is left uninitialized unless it has static or thread storage duration.
14344+
if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14345+
unsigned DiagID = diag::warn_default_init_const_unsafe;
14346+
if (Var->getStorageDuration() == SD_Static ||
14347+
Var->getStorageDuration() == SD_Thread)
14348+
DiagID = diag::warn_default_init_const;
14349+
Diag(Var->getLocation(), DiagID) << Type << /*not a field*/ 0;
14350+
}
14351+
1434214352
// Check for jumps past the implicit initializer. C++0x
1434314353
// clarifies that this applies to a "variable with automatic
1434414354
// storage duration", not a "local variable".

clang/lib/Sema/SemaInit.cpp

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6495,6 +6495,20 @@ static bool canPerformArrayCopy(const InitializedEntity &Entity) {
64956495
return false;
64966496
}
64976497

6498+
static const FieldDecl *getConstField(const RecordDecl *RD) {
6499+
assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6500+
for (const FieldDecl *FD : RD->fields()) {
6501+
QualType QT = FD->getType();
6502+
if (QT.isConstQualified())
6503+
return FD;
6504+
if (const auto *RD = QT->getAsRecordDecl()) {
6505+
if (const FieldDecl *FD = getConstField(RD))
6506+
return FD;
6507+
}
6508+
}
6509+
return nullptr;
6510+
}
6511+
64986512
void InitializationSequence::InitializeFrom(Sema &S,
64996513
const InitializedEntity &Entity,
65006514
const InitializationKind &Kind,
@@ -6562,13 +6576,28 @@ void InitializationSequence::InitializeFrom(Sema &S,
65626576

65636577
if (!S.getLangOpts().CPlusPlus &&
65646578
Kind.getKind() == InitializationKind::IK_Default) {
6565-
RecordDecl *Rec = DestType->getAsRecordDecl();
6566-
if (Rec && Rec->hasUninitializedExplicitInitFields()) {
6579+
if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
65676580
VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
6568-
if (Var && !Initializer) {
6569-
S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6570-
<< /* Var-in-Record */ 1 << Rec;
6571-
emitUninitializedExplicitInitFields(S, Rec);
6581+
if (Rec->hasUninitializedExplicitInitFields()) {
6582+
if (Var && !Initializer) {
6583+
S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
6584+
<< /* Var-in-Record */ 1 << Rec;
6585+
emitUninitializedExplicitInitFields(S, Rec);
6586+
}
6587+
}
6588+
// If the record has any members which are const (recursively checked),
6589+
// then we want to diagnose those as being uninitialized if there is no
6590+
// initializer present.
6591+
if (!Initializer) {
6592+
if (const FieldDecl *FD = getConstField(Rec)) {
6593+
unsigned DiagID = diag::warn_default_init_const_unsafe;
6594+
if (Var->getStorageDuration() == SD_Static ||
6595+
Var->getStorageDuration() == SD_Thread)
6596+
DiagID = diag::warn_default_init_const;
6597+
6598+
S.Diag(Var->getLocation(), DiagID) << Var->getType() << /*member*/ 1;
6599+
S.Diag(FD->getLocation(), diag::note_default_init_const_member) << FD;
6600+
}
65726601
}
65736602
}
65746603
}

clang/test/C/C23/n2607.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ void test1(void) {
2424
void test2(void) {
2525
typedef int array[1];
2626
array reg_array;
27-
const array const_array;
27+
const array const_array = { 0 };
2828

2929
// An array and its elements are identically qualified. We have to test this
3030
// using pointers to the array and element, because the controlling
@@ -50,7 +50,7 @@ void test2(void) {
5050
void test3(void) {
5151
// Validate that we pick the correct composite type for a conditional
5252
// operator in the presence of qualifiers.
53-
const int const_array[1];
53+
const int const_array[1] = { 0 };
5454
int array[1];
5555

5656
// FIXME: the type here should be `const int (*)[1]`, but for some reason,

clang/test/C/drs/dr1xx.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ void dr124(void) {
289289
*/
290290
void dr126(void) {
291291
typedef int *IP;
292-
const IP object; /* expected-note {{variable 'object' declared const here}} */
292+
const IP object = 0; /* expected-note {{variable 'object' declared const here}} */
293293

294294
/* The root of the DR is whether 'object' is a pointer to a const int, or a
295295
* const pointer to int.
@@ -329,7 +329,7 @@ void dr129(void) {
329329
void dr131(void) {
330330
struct S {
331331
const int i; /* expected-note {{data member 'i' declared const here}} */
332-
} s1, s2;
332+
} s1 = { 0 }, s2 = { 0 };
333333
s1 = s2; /* expected-error {{cannot assign to variable 's1' with const-qualified data member 'i'}} */
334334
}
335335

clang/test/Parser/typeof.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ static void test(void) {
1212
short TInt eee; // expected-error{{expected ';' at end of declaration}}
1313
void ary[7] fff; // expected-error{{array has incomplete element type 'void'}} expected-error{{expected ';' at end of declaration}}
1414
typeof(void ary[7]) anIntError; // expected-error{{expected ')'}} expected-note {{to match this '('}} expected-error {{variable has incomplete type 'typeof(void)' (aka 'void')}}
15-
typeof(const int) aci;
16-
const typeof (*pi) aConstInt;
15+
typeof(const int) aci = 0;
16+
const typeof (*pi) aConstInt = 0;
1717
int xx;
1818
int *i;
1919
}

0 commit comments

Comments
 (0)