clang 20.0.0git
SemaInit.cpp
Go to the documentation of this file.
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/Lookup.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/FoldingSet.h"
35#include "llvm/ADT/PointerIntPair.h"
36#include "llvm/ADT/STLForwardCompat.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// Sema Initialization Checking
47//===----------------------------------------------------------------------===//
48
49/// Check whether T is compatible with a wide character type (wchar_t,
50/// char16_t or char32_t).
51static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
52 if (Context.typesAreCompatible(Context.getWideCharType(), T))
53 return true;
54 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
55 return Context.typesAreCompatible(Context.Char16Ty, T) ||
56 Context.typesAreCompatible(Context.Char32Ty, T);
57 }
58 return false;
59}
60
69};
70
71/// Check whether the array of type AT can be initialized by the Init
72/// expression by means of string initialization. Returns SIF_None if so,
73/// otherwise returns a StringInitFailureKind that describes why the
74/// initialization would not work.
76 ASTContext &Context) {
77 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
78 return SIF_Other;
79
80 // See if this is a string literal or @encode.
81 Init = Init->IgnoreParens();
82
83 // Handle @encode, which is a narrow string.
84 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
85 return SIF_None;
86
87 // Otherwise we can only handle string literals.
88 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
89 if (!SL)
90 return SIF_Other;
91
92 const QualType ElemTy =
94
95 auto IsCharOrUnsignedChar = [](const QualType &T) {
96 const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
97 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
98 };
99
100 switch (SL->getKind()) {
101 case StringLiteralKind::UTF8:
102 // char8_t array can be initialized with a UTF-8 string.
103 // - C++20 [dcl.init.string] (DR)
104 // Additionally, an array of char or unsigned char may be initialized
105 // by a UTF-8 string literal.
106 if (ElemTy->isChar8Type() ||
107 (Context.getLangOpts().Char8 &&
108 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
109 return SIF_None;
110 [[fallthrough]];
111 case StringLiteralKind::Ordinary:
112 // char array can be initialized with a narrow string.
113 // Only allow char x[] = "foo"; not char x[] = L"foo";
114 if (ElemTy->isCharType())
115 return (SL->getKind() == StringLiteralKind::UTF8 &&
116 Context.getLangOpts().Char8)
118 : SIF_None;
119 if (ElemTy->isChar8Type())
121 if (IsWideCharCompatible(ElemTy, Context))
123 return SIF_Other;
124 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
125 // "An array with element type compatible with a qualified or unqualified
126 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
127 // string literal with the corresponding encoding prefix (L, u, or U,
128 // respectively), optionally enclosed in braces.
129 case StringLiteralKind::UTF16:
130 if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
131 return SIF_None;
132 if (ElemTy->isCharType() || ElemTy->isChar8Type())
134 if (IsWideCharCompatible(ElemTy, Context))
136 return SIF_Other;
137 case StringLiteralKind::UTF32:
138 if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
139 return SIF_None;
140 if (ElemTy->isCharType() || ElemTy->isChar8Type())
142 if (IsWideCharCompatible(ElemTy, Context))
144 return SIF_Other;
145 case StringLiteralKind::Wide:
146 if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
147 return SIF_None;
148 if (ElemTy->isCharType() || ElemTy->isChar8Type())
150 if (IsWideCharCompatible(ElemTy, Context))
152 return SIF_Other;
153 case StringLiteralKind::Unevaluated:
154 assert(false && "Unevaluated string literal in initialization");
155 break;
156 }
157
158 llvm_unreachable("missed a StringLiteral kind?");
159}
160
162 ASTContext &Context) {
163 const ArrayType *arrayType = Context.getAsArrayType(declType);
164 if (!arrayType)
165 return SIF_Other;
166 return IsStringInit(init, arrayType, Context);
167}
168
170 return ::IsStringInit(Init, AT, Context) == SIF_None;
171}
172
173/// Update the type of a string literal, including any surrounding parentheses,
174/// to match the type of the object which it is initializing.
176 while (true) {
177 E->setType(Ty);
179 if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
180 break;
182 }
183}
184
185/// Fix a compound literal initializing an array so it's correctly marked
186/// as an rvalue.
188 while (true) {
190 if (isa<CompoundLiteralExpr>(E))
191 break;
193 }
194}
195
197 Decl *D = Entity.getDecl();
198 const InitializedEntity *Parent = &Entity;
199
200 while (Parent) {
201 D = Parent->getDecl();
202 Parent = Parent->getParent();
203 }
204
205 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
206 return true;
207
208 return false;
209}
210
212 Sema &SemaRef, QualType &TT);
213
214static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
215 Sema &S, bool CheckC23ConstexprInit = false) {
216 // Get the length of the string as parsed.
217 auto *ConstantArrayTy =
218 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
219 uint64_t StrLength = ConstantArrayTy->getZExtSize();
220
221 if (CheckC23ConstexprInit)
222 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens()))
224
225 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
226 // C99 6.7.8p14. We have an array of character type with unknown size
227 // being initialized to a string literal.
228 llvm::APInt ConstVal(32, StrLength);
229 // Return a new array type (C99 6.7.8p22).
231 IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
232 updateStringLiteralType(Str, DeclT);
233 return;
234 }
235
236 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
237
238 // We have an array of character type with known size. However,
239 // the size may be smaller or larger than the string we are initializing.
240 // FIXME: Avoid truncation for 64-bit length strings.
241 if (S.getLangOpts().CPlusPlus) {
242 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
243 // For Pascal strings it's OK to strip off the terminating null character,
244 // so the example below is valid:
245 //
246 // unsigned char a[2] = "\pa";
247 if (SL->isPascal())
248 StrLength--;
249 }
250
251 // [dcl.init.string]p2
252 if (StrLength > CAT->getZExtSize())
253 S.Diag(Str->getBeginLoc(),
254 diag::err_initializer_string_for_char_array_too_long)
255 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
256 } else {
257 // C99 6.7.8p14.
258 if (StrLength - 1 > CAT->getZExtSize())
259 S.Diag(Str->getBeginLoc(),
260 diag::ext_initializer_string_for_char_array_too_long)
261 << Str->getSourceRange();
262 }
263
264 // Set the type to the actual size that we are initializing. If we have
265 // something like:
266 // char x[1] = "foo";
267 // then this will set the string literal's type to char[1].
268 updateStringLiteralType(Str, DeclT);
269}
270
271//===----------------------------------------------------------------------===//
272// Semantic checking for initializer lists.
273//===----------------------------------------------------------------------===//
274
275namespace {
276
277/// Semantic checking for initializer lists.
278///
279/// The InitListChecker class contains a set of routines that each
280/// handle the initialization of a certain kind of entity, e.g.,
281/// arrays, vectors, struct/union types, scalars, etc. The
282/// InitListChecker itself performs a recursive walk of the subobject
283/// structure of the type to be initialized, while stepping through
284/// the initializer list one element at a time. The IList and Index
285/// parameters to each of the Check* routines contain the active
286/// (syntactic) initializer list and the index into that initializer
287/// list that represents the current initializer. Each routine is
288/// responsible for moving that Index forward as it consumes elements.
289///
290/// Each Check* routine also has a StructuredList/StructuredIndex
291/// arguments, which contains the current "structured" (semantic)
292/// initializer list and the index into that initializer list where we
293/// are copying initializers as we map them over to the semantic
294/// list. Once we have completed our recursive walk of the subobject
295/// structure, we will have constructed a full semantic initializer
296/// list.
297///
298/// C99 designators cause changes in the initializer list traversal,
299/// because they make the initialization "jump" into a specific
300/// subobject and then continue the initialization from that
301/// point. CheckDesignatedInitializer() recursively steps into the
302/// designated subobject and manages backing out the recursion to
303/// initialize the subobjects after the one designated.
304///
305/// If an initializer list contains any designators, we build a placeholder
306/// structured list even in 'verify only' mode, so that we can track which
307/// elements need 'empty' initializtion.
308class InitListChecker {
309 Sema &SemaRef;
310 bool hadError = false;
311 bool VerifyOnly; // No diagnostics.
312 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
313 bool InOverloadResolution;
314 InitListExpr *FullyStructuredList = nullptr;
315 NoInitExpr *DummyExpr = nullptr;
316 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
317 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
318 unsigned CurEmbedIndex = 0;
319
320 NoInitExpr *getDummyInit() {
321 if (!DummyExpr)
322 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
323 return DummyExpr;
324 }
325
326 void CheckImplicitInitList(const InitializedEntity &Entity,
327 InitListExpr *ParentIList, QualType T,
328 unsigned &Index, InitListExpr *StructuredList,
329 unsigned &StructuredIndex);
330 void CheckExplicitInitList(const InitializedEntity &Entity,
331 InitListExpr *IList, QualType &T,
332 InitListExpr *StructuredList,
333 bool TopLevelObject = false);
334 void CheckListElementTypes(const InitializedEntity &Entity,
335 InitListExpr *IList, QualType &DeclType,
336 bool SubobjectIsDesignatorContext,
337 unsigned &Index,
338 InitListExpr *StructuredList,
339 unsigned &StructuredIndex,
340 bool TopLevelObject = false);
341 void CheckSubElementType(const InitializedEntity &Entity,
342 InitListExpr *IList, QualType ElemType,
343 unsigned &Index,
344 InitListExpr *StructuredList,
345 unsigned &StructuredIndex,
346 bool DirectlyDesignated = false);
347 void CheckComplexType(const InitializedEntity &Entity,
348 InitListExpr *IList, QualType DeclType,
349 unsigned &Index,
350 InitListExpr *StructuredList,
351 unsigned &StructuredIndex);
352 void CheckScalarType(const InitializedEntity &Entity,
353 InitListExpr *IList, QualType DeclType,
354 unsigned &Index,
355 InitListExpr *StructuredList,
356 unsigned &StructuredIndex);
357 void CheckReferenceType(const InitializedEntity &Entity,
358 InitListExpr *IList, QualType DeclType,
359 unsigned &Index,
360 InitListExpr *StructuredList,
361 unsigned &StructuredIndex);
362 void CheckVectorType(const InitializedEntity &Entity,
363 InitListExpr *IList, QualType DeclType, unsigned &Index,
364 InitListExpr *StructuredList,
365 unsigned &StructuredIndex);
366 void CheckStructUnionTypes(const InitializedEntity &Entity,
367 InitListExpr *IList, QualType DeclType,
370 bool SubobjectIsDesignatorContext, unsigned &Index,
371 InitListExpr *StructuredList,
372 unsigned &StructuredIndex,
373 bool TopLevelObject = false);
374 void CheckArrayType(const InitializedEntity &Entity,
375 InitListExpr *IList, QualType &DeclType,
376 llvm::APSInt elementIndex,
377 bool SubobjectIsDesignatorContext, unsigned &Index,
378 InitListExpr *StructuredList,
379 unsigned &StructuredIndex);
380 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
381 InitListExpr *IList, DesignatedInitExpr *DIE,
382 unsigned DesigIdx,
383 QualType &CurrentObjectType,
385 llvm::APSInt *NextElementIndex,
386 unsigned &Index,
387 InitListExpr *StructuredList,
388 unsigned &StructuredIndex,
389 bool FinishSubobjectInit,
390 bool TopLevelObject);
391 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
392 QualType CurrentObjectType,
393 InitListExpr *StructuredList,
394 unsigned StructuredIndex,
395 SourceRange InitRange,
396 bool IsFullyOverwritten = false);
397 void UpdateStructuredListElement(InitListExpr *StructuredList,
398 unsigned &StructuredIndex,
399 Expr *expr);
400 InitListExpr *createInitListExpr(QualType CurrentObjectType,
401 SourceRange InitRange,
402 unsigned ExpectedNumInits);
403 int numArrayElements(QualType DeclType);
404 int numStructUnionElements(QualType DeclType);
405 static RecordDecl *getRecordDecl(QualType DeclType);
406
407 ExprResult PerformEmptyInit(SourceLocation Loc,
408 const InitializedEntity &Entity);
409
410 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
411 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
412 bool UnionOverride = false,
413 bool FullyOverwritten = true) {
414 // Overriding an initializer via a designator is valid with C99 designated
415 // initializers, but ill-formed with C++20 designated initializers.
416 unsigned DiagID =
417 SemaRef.getLangOpts().CPlusPlus
418 ? (UnionOverride ? diag::ext_initializer_union_overrides
419 : diag::ext_initializer_overrides)
420 : diag::warn_initializer_overrides;
421
422 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
423 // In overload resolution, we have to strictly enforce the rules, and so
424 // don't allow any overriding of prior initializers. This matters for a
425 // case such as:
426 //
427 // union U { int a, b; };
428 // struct S { int a, b; };
429 // void f(U), f(S);
430 //
431 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
432 // consistency, we disallow all overriding of prior initializers in
433 // overload resolution, not only overriding of union members.
434 hadError = true;
435 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
436 // If we'll be keeping around the old initializer but overwriting part of
437 // the object it initialized, and that object is not trivially
438 // destructible, this can leak. Don't allow that, not even as an
439 // extension.
440 //
441 // FIXME: It might be reasonable to allow this in cases where the part of
442 // the initializer that we're overriding has trivial destruction.
443 DiagID = diag::err_initializer_overrides_destructed;
444 } else if (!OldInit->getSourceRange().isValid()) {
445 // We need to check on source range validity because the previous
446 // initializer does not have to be an explicit initializer. e.g.,
447 //
448 // struct P { int a, b; };
449 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
450 //
451 // There is an overwrite taking place because the first braced initializer
452 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
453 //
454 // Such overwrites are harmless, so we don't diagnose them. (Note that in
455 // C++, this cannot be reached unless we've already seen and diagnosed a
456 // different conformance issue, such as a mixture of designated and
457 // non-designated initializers or a multi-level designator.)
458 return;
459 }
460
461 if (!VerifyOnly) {
462 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
463 << NewInitRange << FullyOverwritten << OldInit->getType();
464 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
465 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
466 << OldInit->getSourceRange();
467 }
468 }
469
470 // Explanation on the "FillWithNoInit" mode:
471 //
472 // Assume we have the following definitions (Case#1):
473 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
474 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
475 //
476 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
477 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
478 //
479 // But if we have (Case#2):
480 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
481 //
482 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
483 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
484 //
485 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
486 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
487 // initializers but with special "NoInitExpr" place holders, which tells the
488 // CodeGen not to generate any initializers for these parts.
489 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
490 const InitializedEntity &ParentEntity,
491 InitListExpr *ILE, bool &RequiresSecondPass,
492 bool FillWithNoInit);
493 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
494 const InitializedEntity &ParentEntity,
495 InitListExpr *ILE, bool &RequiresSecondPass,
496 bool FillWithNoInit = false);
497 void FillInEmptyInitializations(const InitializedEntity &Entity,
498 InitListExpr *ILE, bool &RequiresSecondPass,
499 InitListExpr *OuterILE, unsigned OuterIndex,
500 bool FillWithNoInit = false);
501 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
502 Expr *InitExpr, FieldDecl *Field,
503 bool TopLevelObject);
504 void CheckEmptyInitializable(const InitializedEntity &Entity,
506
507 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
508 Expr *Result = nullptr;
509 // Undrestand which part of embed we'd like to reference.
510 if (!CurEmbed) {
511 CurEmbed = Embed;
512 CurEmbedIndex = 0;
513 }
514 // Reference just one if we're initializing a single scalar.
515 uint64_t ElsCount = 1;
516 // Otherwise try to fill whole array with embed data.
518 auto *AType =
519 SemaRef.Context.getAsArrayType(Entity.getParent()->getType());
520 assert(AType && "expected array type when initializing array");
521 ElsCount = Embed->getDataElementCount();
522 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
523 ElsCount = std::min(CAType->getSize().getZExtValue(),
524 ElsCount - CurEmbedIndex);
525 if (ElsCount == Embed->getDataElementCount()) {
526 CurEmbed = nullptr;
527 CurEmbedIndex = 0;
528 return Embed;
529 }
530 }
531
532 Result = new (SemaRef.Context)
533 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
534 CurEmbedIndex, ElsCount);
535 CurEmbedIndex += ElsCount;
536 if (CurEmbedIndex >= Embed->getDataElementCount()) {
537 CurEmbed = nullptr;
538 CurEmbedIndex = 0;
539 }
540 return Result;
541 }
542
543public:
544 InitListChecker(
545 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
546 bool VerifyOnly, bool TreatUnavailableAsInvalid,
547 bool InOverloadResolution = false,
548 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
549 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
550 QualType &T,
551 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
552 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
553 /*TreatUnavailableAsInvalid=*/false,
554 /*InOverloadResolution=*/false,
555 &AggrDeductionCandidateParamTypes) {}
556
557 bool HadError() { return hadError; }
558
559 // Retrieves the fully-structured initializer list used for
560 // semantic analysis and code generation.
561 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
562};
563
564} // end anonymous namespace
565
566ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
567 const InitializedEntity &Entity) {
569 true);
570 MultiExprArg SubInit;
571 Expr *InitExpr;
572 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
573
574 // C++ [dcl.init.aggr]p7:
575 // If there are fewer initializer-clauses in the list than there are
576 // members in the aggregate, then each member not explicitly initialized
577 // ...
578 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
580 if (EmptyInitList) {
581 // C++1y / DR1070:
582 // shall be initialized [...] from an empty initializer list.
583 //
584 // We apply the resolution of this DR to C++11 but not C++98, since C++98
585 // does not have useful semantics for initialization from an init list.
586 // We treat this as copy-initialization, because aggregate initialization
587 // always performs copy-initialization on its elements.
588 //
589 // Only do this if we're initializing a class type, to avoid filling in
590 // the initializer list where possible.
591 InitExpr = VerifyOnly
592 ? &DummyInitList
593 : new (SemaRef.Context)
594 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
595 InitExpr->setType(SemaRef.Context.VoidTy);
596 SubInit = InitExpr;
598 } else {
599 // C++03:
600 // shall be value-initialized.
601 }
602
603 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
604 // libstdc++4.6 marks the vector default constructor as explicit in
605 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
606 // stlport does so too. Look for std::__debug for libstdc++, and for
607 // std:: for stlport. This is effectively a compiler-side implementation of
608 // LWG2193.
609 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
613 InitSeq.getFailedCandidateSet()
614 .BestViableFunction(SemaRef, Kind.getLocation(), Best);
615 (void)O;
616 assert(O == OR_Success && "Inconsistent overload resolution");
617 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
618 CXXRecordDecl *R = CtorDecl->getParent();
619
620 if (CtorDecl->getMinRequiredArguments() == 0 &&
621 CtorDecl->isExplicit() && R->getDeclName() &&
622 SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
623 bool IsInStd = false;
624 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
625 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
627 IsInStd = true;
628 }
629
630 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
631 .Cases("basic_string", "deque", "forward_list", true)
632 .Cases("list", "map", "multimap", "multiset", true)
633 .Cases("priority_queue", "queue", "set", "stack", true)
634 .Cases("unordered_map", "unordered_set", "vector", true)
635 .Default(false)) {
636 InitSeq.InitializeFrom(
637 SemaRef, Entity,
639 MultiExprArg(), /*TopLevelOfInitList=*/false,
640 TreatUnavailableAsInvalid);
641 // Emit a warning for this. System header warnings aren't shown
642 // by default, but people working on system headers should see it.
643 if (!VerifyOnly) {
644 SemaRef.Diag(CtorDecl->getLocation(),
645 diag::warn_invalid_initializer_from_system_header);
647 SemaRef.Diag(Entity.getDecl()->getLocation(),
648 diag::note_used_in_initialization_here);
649 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
650 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
651 }
652 }
653 }
654 }
655 if (!InitSeq) {
656 if (!VerifyOnly) {
657 InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
659 SemaRef.Diag(Entity.getDecl()->getLocation(),
660 diag::note_in_omitted_aggregate_initializer)
661 << /*field*/1 << Entity.getDecl();
662 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
663 bool IsTrailingArrayNewMember =
664 Entity.getParent() &&
666 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
667 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
668 << Entity.getElementIndex();
669 }
670 }
671 hadError = true;
672 return ExprError();
673 }
674
675 return VerifyOnly ? ExprResult()
676 : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
677}
678
679void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
681 // If we're building a fully-structured list, we'll check this at the end
682 // once we know which elements are actually initialized. Otherwise, we know
683 // that there are no designators so we can just check now.
684 if (FullyStructuredList)
685 return;
686 PerformEmptyInit(Loc, Entity);
687}
688
689void InitListChecker::FillInEmptyInitForBase(
690 unsigned Init, const CXXBaseSpecifier &Base,
691 const InitializedEntity &ParentEntity, InitListExpr *ILE,
692 bool &RequiresSecondPass, bool FillWithNoInit) {
694 SemaRef.Context, &Base, false, &ParentEntity);
695
696 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
697 ExprResult BaseInit = FillWithNoInit
698 ? new (SemaRef.Context) NoInitExpr(Base.getType())
699 : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
700 if (BaseInit.isInvalid()) {
701 hadError = true;
702 return;
703 }
704
705 if (!VerifyOnly) {
706 assert(Init < ILE->getNumInits() && "should have been expanded");
707 ILE->setInit(Init, BaseInit.getAs<Expr>());
708 }
709 } else if (InitListExpr *InnerILE =
710 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
711 FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
712 ILE, Init, FillWithNoInit);
713 } else if (DesignatedInitUpdateExpr *InnerDIUE =
714 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
715 FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
716 RequiresSecondPass, ILE, Init,
717 /*FillWithNoInit =*/true);
718 }
719}
720
721void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
722 const InitializedEntity &ParentEntity,
723 InitListExpr *ILE,
724 bool &RequiresSecondPass,
725 bool FillWithNoInit) {
727 unsigned NumInits = ILE->getNumInits();
728 InitializedEntity MemberEntity
729 = InitializedEntity::InitializeMember(Field, &ParentEntity);
730
731 if (Init >= NumInits || !ILE->getInit(Init)) {
732 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
733 if (!RType->getDecl()->isUnion())
734 assert((Init < NumInits || VerifyOnly) &&
735 "This ILE should have been expanded");
736
737 if (FillWithNoInit) {
738 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
739 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
740 if (Init < NumInits)
741 ILE->setInit(Init, Filler);
742 else
743 ILE->updateInit(SemaRef.Context, Init, Filler);
744 return;
745 }
746 // C++1y [dcl.init.aggr]p7:
747 // If there are fewer initializer-clauses in the list than there are
748 // members in the aggregate, then each member not explicitly initialized
749 // shall be initialized from its brace-or-equal-initializer [...]
750 if (Field->hasInClassInitializer()) {
751 if (VerifyOnly)
752 return;
753
754 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
755 if (DIE.isInvalid()) {
756 hadError = true;
757 return;
758 }
759 SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
760 if (Init < NumInits)
761 ILE->setInit(Init, DIE.get());
762 else {
763 ILE->updateInit(SemaRef.Context, Init, DIE.get());
764 RequiresSecondPass = true;
765 }
766 return;
767 }
768
769 if (Field->getType()->isReferenceType()) {
770 if (!VerifyOnly) {
771 // C++ [dcl.init.aggr]p9:
772 // If an incomplete or empty initializer-list leaves a
773 // member of reference type uninitialized, the program is
774 // ill-formed.
775 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
776 << Field->getType()
777 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
778 ->getSourceRange();
779 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
780 }
781 hadError = true;
782 return;
783 }
784
785 ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
786 if (MemberInit.isInvalid()) {
787 hadError = true;
788 return;
789 }
790
791 if (hadError || VerifyOnly) {
792 // Do nothing
793 } else if (Init < NumInits) {
794 ILE->setInit(Init, MemberInit.getAs<Expr>());
795 } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
796 // Empty initialization requires a constructor call, so
797 // extend the initializer list to include the constructor
798 // call and make a note that we'll need to take another pass
799 // through the initializer list.
800 ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
801 RequiresSecondPass = true;
802 }
803 } else if (InitListExpr *InnerILE
804 = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
805 FillInEmptyInitializations(MemberEntity, InnerILE,
806 RequiresSecondPass, ILE, Init, FillWithNoInit);
807 } else if (DesignatedInitUpdateExpr *InnerDIUE =
808 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
809 FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
810 RequiresSecondPass, ILE, Init,
811 /*FillWithNoInit =*/true);
812 }
813}
814
815/// Recursively replaces NULL values within the given initializer list
816/// with expressions that perform value-initialization of the
817/// appropriate type, and finish off the InitListExpr formation.
818void
819InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
820 InitListExpr *ILE,
821 bool &RequiresSecondPass,
822 InitListExpr *OuterILE,
823 unsigned OuterIndex,
824 bool FillWithNoInit) {
825 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
826 "Should not have void type");
827
828 // We don't need to do any checks when just filling NoInitExprs; that can't
829 // fail.
830 if (FillWithNoInit && VerifyOnly)
831 return;
832
833 // If this is a nested initializer list, we might have changed its contents
834 // (and therefore some of its properties, such as instantiation-dependence)
835 // while filling it in. Inform the outer initializer list so that its state
836 // can be updated to match.
837 // FIXME: We should fully build the inner initializers before constructing
838 // the outer InitListExpr instead of mutating AST nodes after they have
839 // been used as subexpressions of other nodes.
840 struct UpdateOuterILEWithUpdatedInit {
841 InitListExpr *Outer;
842 unsigned OuterIndex;
843 ~UpdateOuterILEWithUpdatedInit() {
844 if (Outer)
845 Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
846 }
847 } UpdateOuterRAII = {OuterILE, OuterIndex};
848
849 // A transparent ILE is not performing aggregate initialization and should
850 // not be filled in.
851 if (ILE->isTransparent())
852 return;
853
854 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
855 const RecordDecl *RDecl = RType->getDecl();
856 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
857 FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(), Entity, ILE,
858 RequiresSecondPass, FillWithNoInit);
859 } else {
860 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
861 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
862 "We should have computed initialized fields already");
863 // The fields beyond ILE->getNumInits() are default initialized, so in
864 // order to leave them uninitialized, the ILE is expanded and the extra
865 // fields are then filled with NoInitExpr.
866 unsigned NumElems = numStructUnionElements(ILE->getType());
867 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
868 ++NumElems;
869 if (!VerifyOnly && ILE->getNumInits() < NumElems)
870 ILE->resizeInits(SemaRef.Context, NumElems);
871
872 unsigned Init = 0;
873
874 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
875 for (auto &Base : CXXRD->bases()) {
876 if (hadError)
877 return;
878
879 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
880 FillWithNoInit);
881 ++Init;
882 }
883 }
884
885 for (auto *Field : RDecl->fields()) {
886 if (Field->isUnnamedBitField())
887 continue;
888
889 if (hadError)
890 return;
891
892 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
893 FillWithNoInit);
894 if (hadError)
895 return;
896
897 ++Init;
898
899 // Only look at the first initialization of a union.
900 if (RDecl->isUnion())
901 break;
902 }
903 }
904
905 return;
906 }
907
908 QualType ElementType;
909
910 InitializedEntity ElementEntity = Entity;
911 unsigned NumInits = ILE->getNumInits();
912 uint64_t NumElements = NumInits;
913 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
914 ElementType = AType->getElementType();
915 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
916 NumElements = CAType->getZExtSize();
917 // For an array new with an unknown bound, ask for one additional element
918 // in order to populate the array filler.
919 if (Entity.isVariableLengthArrayNew())
920 ++NumElements;
921 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
922 0, Entity);
923 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
924 ElementType = VType->getElementType();
925 NumElements = VType->getNumElements();
926 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
927 0, Entity);
928 } else
929 ElementType = ILE->getType();
930
931 bool SkipEmptyInitChecks = false;
932 for (uint64_t Init = 0; Init != NumElements; ++Init) {
933 if (hadError)
934 return;
935
936 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
938 ElementEntity.setElementIndex(Init);
939
940 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
941 return;
942
943 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
944 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
945 ILE->setInit(Init, ILE->getArrayFiller());
946 else if (!InitExpr && !ILE->hasArrayFiller()) {
947 // In VerifyOnly mode, there's no point performing empty initialization
948 // more than once.
949 if (SkipEmptyInitChecks)
950 continue;
951
952 Expr *Filler = nullptr;
953
954 if (FillWithNoInit)
955 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
956 else {
957 ExprResult ElementInit =
958 PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
959 if (ElementInit.isInvalid()) {
960 hadError = true;
961 return;
962 }
963
964 Filler = ElementInit.getAs<Expr>();
965 }
966
967 if (hadError) {
968 // Do nothing
969 } else if (VerifyOnly) {
970 SkipEmptyInitChecks = true;
971 } else if (Init < NumInits) {
972 // For arrays, just set the expression used for value-initialization
973 // of the "holes" in the array.
974 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
975 ILE->setArrayFiller(Filler);
976 else
977 ILE->setInit(Init, Filler);
978 } else {
979 // For arrays, just set the expression used for value-initialization
980 // of the rest of elements and exit.
981 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
982 ILE->setArrayFiller(Filler);
983 return;
984 }
985
986 if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
987 // Empty initialization requires a constructor call, so
988 // extend the initializer list to include the constructor
989 // call and make a note that we'll need to take another pass
990 // through the initializer list.
991 ILE->updateInit(SemaRef.Context, Init, Filler);
992 RequiresSecondPass = true;
993 }
994 }
995 } else if (InitListExpr *InnerILE
996 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
997 FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
998 ILE, Init, FillWithNoInit);
999 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1000 dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
1001 FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
1002 RequiresSecondPass, ILE, Init,
1003 /*FillWithNoInit =*/true);
1004 }
1005 }
1006}
1007
1008static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1009 for (const Stmt *Init : *IL)
1010 if (isa_and_nonnull<DesignatedInitExpr>(Init))
1011 return true;
1012 return false;
1013}
1014
1015InitListChecker::InitListChecker(
1016 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1017 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1018 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1019 : SemaRef(S), VerifyOnly(VerifyOnly),
1020 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1021 InOverloadResolution(InOverloadResolution),
1022 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1023 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1024 FullyStructuredList =
1025 createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
1026
1027 // FIXME: Check that IL isn't already the semantic form of some other
1028 // InitListExpr. If it is, we'd create a broken AST.
1029 if (!VerifyOnly)
1030 FullyStructuredList->setSyntacticForm(IL);
1031 }
1032
1033 CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
1034 /*TopLevelObject=*/true);
1035
1036 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1037 bool RequiresSecondPass = false;
1038 FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
1039 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1040 if (RequiresSecondPass && !hadError)
1041 FillInEmptyInitializations(Entity, FullyStructuredList,
1042 RequiresSecondPass, nullptr, 0);
1043 }
1044 if (hadError && FullyStructuredList)
1045 FullyStructuredList->markError();
1046}
1047
1048int InitListChecker::numArrayElements(QualType DeclType) {
1049 // FIXME: use a proper constant
1050 int maxElements = 0x7FFFFFFF;
1051 if (const ConstantArrayType *CAT =
1052 SemaRef.Context.getAsConstantArrayType(DeclType)) {
1053 maxElements = static_cast<int>(CAT->getZExtSize());
1054 }
1055 return maxElements;
1056}
1057
1058int InitListChecker::numStructUnionElements(QualType DeclType) {
1059 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1060 int InitializableMembers = 0;
1061 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1062 InitializableMembers += CXXRD->getNumBases();
1063 for (const auto *Field : structDecl->fields())
1064 if (!Field->isUnnamedBitField())
1065 ++InitializableMembers;
1066
1067 if (structDecl->isUnion())
1068 return std::min(InitializableMembers, 1);
1069 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1070}
1071
1072RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1073 if (const auto *RT = DeclType->getAs<RecordType>())
1074 return RT->getDecl();
1075 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1076 return Inject->getDecl();
1077 return nullptr;
1078}
1079
1080/// Determine whether Entity is an entity for which it is idiomatic to elide
1081/// the braces in aggregate initialization.
1083 // Recursive initialization of the one and only field within an aggregate
1084 // class is considered idiomatic. This case arises in particular for
1085 // initialization of std::array, where the C++ standard suggests the idiom of
1086 //
1087 // std::array<T, N> arr = {1, 2, 3};
1088 //
1089 // (where std::array is an aggregate struct containing a single array field.
1090
1091 if (!Entity.getParent())
1092 return false;
1093
1094 // Allows elide brace initialization for aggregates with empty base.
1095 if (Entity.getKind() == InitializedEntity::EK_Base) {
1096 auto *ParentRD =
1097 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1098 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1099 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1100 }
1101
1102 // Allow brace elision if the only subobject is a field.
1103 if (Entity.getKind() == InitializedEntity::EK_Member) {
1104 auto *ParentRD =
1105 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1106 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1107 if (CXXRD->getNumBases()) {
1108 return false;
1109 }
1110 }
1111 auto FieldIt = ParentRD->field_begin();
1112 assert(FieldIt != ParentRD->field_end() &&
1113 "no fields but have initializer for member?");
1114 return ++FieldIt == ParentRD->field_end();
1115 }
1116
1117 return false;
1118}
1119
1120/// Check whether the range of the initializer \p ParentIList from element
1121/// \p Index onwards can be used to initialize an object of type \p T. Update
1122/// \p Index to indicate how many elements of the list were consumed.
1123///
1124/// This also fills in \p StructuredList, from element \p StructuredIndex
1125/// onwards, with the fully-braced, desugared form of the initialization.
1126void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1127 InitListExpr *ParentIList,
1128 QualType T, unsigned &Index,
1129 InitListExpr *StructuredList,
1130 unsigned &StructuredIndex) {
1131 int maxElements = 0;
1132
1133 if (T->isArrayType())
1134 maxElements = numArrayElements(T);
1135 else if (T->isRecordType())
1136 maxElements = numStructUnionElements(T);
1137 else if (T->isVectorType())
1138 maxElements = T->castAs<VectorType>()->getNumElements();
1139 else
1140 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1141
1142 if (maxElements == 0) {
1143 if (!VerifyOnly)
1144 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1145 diag::err_implicit_empty_initializer);
1146 ++Index;
1147 hadError = true;
1148 return;
1149 }
1150
1151 // Build a structured initializer list corresponding to this subobject.
1152 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1153 ParentIList, Index, T, StructuredList, StructuredIndex,
1154 SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1155 ParentIList->getSourceRange().getEnd()));
1156 unsigned StructuredSubobjectInitIndex = 0;
1157
1158 // Check the element types and build the structural subobject.
1159 unsigned StartIndex = Index;
1160 CheckListElementTypes(Entity, ParentIList, T,
1161 /*SubobjectIsDesignatorContext=*/false, Index,
1162 StructuredSubobjectInitList,
1163 StructuredSubobjectInitIndex);
1164
1165 if (StructuredSubobjectInitList) {
1166 StructuredSubobjectInitList->setType(T);
1167
1168 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1169 // Update the structured sub-object initializer so that it's ending
1170 // range corresponds with the end of the last initializer it used.
1171 if (EndIndex < ParentIList->getNumInits() &&
1172 ParentIList->getInit(EndIndex)) {
1173 SourceLocation EndLoc
1174 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1175 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1176 }
1177
1178 // Complain about missing braces.
1179 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1180 !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1182 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1183 diag::warn_missing_braces)
1184 << StructuredSubobjectInitList->getSourceRange()
1186 StructuredSubobjectInitList->getBeginLoc(), "{")
1188 SemaRef.getLocForEndOfToken(
1189 StructuredSubobjectInitList->getEndLoc()),
1190 "}");
1191 }
1192
1193 // Warn if this type won't be an aggregate in future versions of C++.
1194 auto *CXXRD = T->getAsCXXRecordDecl();
1195 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1196 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1197 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1198 << StructuredSubobjectInitList->getSourceRange() << T;
1199 }
1200 }
1201}
1202
1203/// Warn that \p Entity was of scalar type and was initialized by a
1204/// single-element braced initializer list.
1205static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1207 // Don't warn during template instantiation. If the initialization was
1208 // non-dependent, we warned during the initial parse; otherwise, the
1209 // type might not be scalar in some uses of the template.
1211 return;
1212
1213 unsigned DiagID = 0;
1214
1215 switch (Entity.getKind()) {
1224 // Extra braces here are suspicious.
1225 DiagID = diag::warn_braces_around_init;
1226 break;
1227
1229 // Warn on aggregate initialization but not on ctor init list or
1230 // default member initializer.
1231 if (Entity.getParent())
1232 DiagID = diag::warn_braces_around_init;
1233 break;
1234
1237 // No warning, might be direct-list-initialization.
1238 // FIXME: Should we warn for copy-list-initialization in these cases?
1239 break;
1240
1244 // No warning, braces are part of the syntax of the underlying construct.
1245 break;
1246
1248 // No warning, we already warned when initializing the result.
1249 break;
1250
1258 llvm_unreachable("unexpected braced scalar init");
1259 }
1260
1261 if (DiagID) {
1262 S.Diag(Braces.getBegin(), DiagID)
1263 << Entity.getType()->isSizelessBuiltinType() << Braces
1264 << FixItHint::CreateRemoval(Braces.getBegin())
1265 << FixItHint::CreateRemoval(Braces.getEnd());
1266 }
1267}
1268
1269/// Check whether the initializer \p IList (that was written with explicit
1270/// braces) can be used to initialize an object of type \p T.
1271///
1272/// This also fills in \p StructuredList with the fully-braced, desugared
1273/// form of the initialization.
1274void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1275 InitListExpr *IList, QualType &T,
1276 InitListExpr *StructuredList,
1277 bool TopLevelObject) {
1278 unsigned Index = 0, StructuredIndex = 0;
1279 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1280 Index, StructuredList, StructuredIndex, TopLevelObject);
1281 if (StructuredList) {
1282 QualType ExprTy = T;
1283 if (!ExprTy->isArrayType())
1284 ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1285 if (!VerifyOnly)
1286 IList->setType(ExprTy);
1287 StructuredList->setType(ExprTy);
1288 }
1289 if (hadError)
1290 return;
1291
1292 // Don't complain for incomplete types, since we'll get an error elsewhere.
1293 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1294 // We have leftover initializers
1295 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1296 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1297 hadError = ExtraInitsIsError;
1298 if (VerifyOnly) {
1299 return;
1300 } else if (StructuredIndex == 1 &&
1301 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1302 SIF_None) {
1303 unsigned DK =
1304 ExtraInitsIsError
1305 ? diag::err_excess_initializers_in_char_array_initializer
1306 : diag::ext_excess_initializers_in_char_array_initializer;
1307 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1308 << IList->getInit(Index)->getSourceRange();
1309 } else if (T->isSizelessBuiltinType()) {
1310 unsigned DK = ExtraInitsIsError
1311 ? diag::err_excess_initializers_for_sizeless_type
1312 : diag::ext_excess_initializers_for_sizeless_type;
1313 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1314 << T << IList->getInit(Index)->getSourceRange();
1315 } else {
1316 int initKind = T->isArrayType() ? 0 :
1317 T->isVectorType() ? 1 :
1318 T->isScalarType() ? 2 :
1319 T->isUnionType() ? 3 :
1320 4;
1321
1322 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1323 : diag::ext_excess_initializers;
1324 SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1325 << initKind << IList->getInit(Index)->getSourceRange();
1326 }
1327 }
1328
1329 if (!VerifyOnly) {
1330 if (T->isScalarType() && IList->getNumInits() == 1 &&
1331 !isa<InitListExpr>(IList->getInit(0)))
1332 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1333
1334 // Warn if this is a class type that won't be an aggregate in future
1335 // versions of C++.
1336 auto *CXXRD = T->getAsCXXRecordDecl();
1337 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1338 // Don't warn if there's an equivalent default constructor that would be
1339 // used instead.
1340 bool HasEquivCtor = false;
1341 if (IList->getNumInits() == 0) {
1342 auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1343 HasEquivCtor = CD && !CD->isDeleted();
1344 }
1345
1346 if (!HasEquivCtor) {
1347 SemaRef.Diag(IList->getBeginLoc(),
1348 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1349 << IList->getSourceRange() << T;
1350 }
1351 }
1352 }
1353}
1354
1355void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1356 InitListExpr *IList,
1357 QualType &DeclType,
1358 bool SubobjectIsDesignatorContext,
1359 unsigned &Index,
1360 InitListExpr *StructuredList,
1361 unsigned &StructuredIndex,
1362 bool TopLevelObject) {
1363 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1364 // Explicitly braced initializer for complex type can be real+imaginary
1365 // parts.
1366 CheckComplexType(Entity, IList, DeclType, Index,
1367 StructuredList, StructuredIndex);
1368 } else if (DeclType->isScalarType()) {
1369 CheckScalarType(Entity, IList, DeclType, Index,
1370 StructuredList, StructuredIndex);
1371 } else if (DeclType->isVectorType()) {
1372 CheckVectorType(Entity, IList, DeclType, Index,
1373 StructuredList, StructuredIndex);
1374 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1375 auto Bases =
1378 if (DeclType->isRecordType()) {
1379 assert(DeclType->isAggregateType() &&
1380 "non-aggregate records should be handed in CheckSubElementType");
1381 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1382 Bases = CXXRD->bases();
1383 } else {
1384 Bases = cast<CXXRecordDecl>(RD)->bases();
1385 }
1386 CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1387 SubobjectIsDesignatorContext, Index, StructuredList,
1388 StructuredIndex, TopLevelObject);
1389 } else if (DeclType->isArrayType()) {
1390 llvm::APSInt Zero(
1391 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1392 false);
1393 CheckArrayType(Entity, IList, DeclType, Zero,
1394 SubobjectIsDesignatorContext, Index,
1395 StructuredList, StructuredIndex);
1396 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1397 // This type is invalid, issue a diagnostic.
1398 ++Index;
1399 if (!VerifyOnly)
1400 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1401 << DeclType;
1402 hadError = true;
1403 } else if (DeclType->isReferenceType()) {
1404 CheckReferenceType(Entity, IList, DeclType, Index,
1405 StructuredList, StructuredIndex);
1406 } else if (DeclType->isObjCObjectType()) {
1407 if (!VerifyOnly)
1408 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1409 hadError = true;
1410 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1411 DeclType->isSizelessBuiltinType()) {
1412 // Checks for scalar type are sufficient for these types too.
1413 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1414 StructuredIndex);
1415 } else if (DeclType->isDependentType()) {
1416 // C++ [over.match.class.deduct]p1.5:
1417 // brace elision is not considered for any aggregate element that has a
1418 // dependent non-array type or an array type with a value-dependent bound
1419 ++Index;
1420 assert(AggrDeductionCandidateParamTypes);
1421 AggrDeductionCandidateParamTypes->push_back(DeclType);
1422 } else {
1423 if (!VerifyOnly)
1424 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1425 << DeclType;
1426 hadError = true;
1427 }
1428}
1429
1430void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1431 InitListExpr *IList,
1432 QualType ElemType,
1433 unsigned &Index,
1434 InitListExpr *StructuredList,
1435 unsigned &StructuredIndex,
1436 bool DirectlyDesignated) {
1437 Expr *expr = IList->getInit(Index);
1438
1439 if (ElemType->isReferenceType())
1440 return CheckReferenceType(Entity, IList, ElemType, Index,
1441 StructuredList, StructuredIndex);
1442
1443 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1444 if (SubInitList->getNumInits() == 1 &&
1445 IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1446 SIF_None) {
1447 // FIXME: It would be more faithful and no less correct to include an
1448 // InitListExpr in the semantic form of the initializer list in this case.
1449 expr = SubInitList->getInit(0);
1450 }
1451 // Nested aggregate initialization and C++ initialization are handled later.
1452 } else if (isa<ImplicitValueInitExpr>(expr)) {
1453 // This happens during template instantiation when we see an InitListExpr
1454 // that we've already checked once.
1455 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1456 "found implicit initialization for the wrong type");
1457 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1458 ++Index;
1459 return;
1460 }
1461
1462 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1463 // C++ [dcl.init.aggr]p2:
1464 // Each member is copy-initialized from the corresponding
1465 // initializer-clause.
1466
1467 // FIXME: Better EqualLoc?
1470
1471 // Vector elements can be initialized from other vectors in which case
1472 // we need initialization entity with a type of a vector (and not a vector
1473 // element!) initializing multiple vector elements.
1474 auto TmpEntity =
1475 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1477 : Entity;
1478
1479 if (TmpEntity.getType()->isDependentType()) {
1480 // C++ [over.match.class.deduct]p1.5:
1481 // brace elision is not considered for any aggregate element that has a
1482 // dependent non-array type or an array type with a value-dependent
1483 // bound
1484 assert(AggrDeductionCandidateParamTypes);
1485
1486 // In the presence of a braced-init-list within the initializer, we should
1487 // not perform brace-elision, even if brace elision would otherwise be
1488 // applicable. For example, given:
1489 //
1490 // template <class T> struct Foo {
1491 // T t[2];
1492 // };
1493 //
1494 // Foo t = {{1, 2}};
1495 //
1496 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1497 // {{1, 2}}.
1498 if (isa<InitListExpr, DesignatedInitExpr>(expr) ||
1499 !isa_and_present<ConstantArrayType>(
1500 SemaRef.Context.getAsArrayType(ElemType))) {
1501 ++Index;
1502 AggrDeductionCandidateParamTypes->push_back(ElemType);
1503 return;
1504 }
1505 } else {
1506 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1507 /*TopLevelOfInitList*/ true);
1508 // C++14 [dcl.init.aggr]p13:
1509 // If the assignment-expression can initialize a member, the member is
1510 // initialized. Otherwise [...] brace elision is assumed
1511 //
1512 // Brace elision is never performed if the element is not an
1513 // assignment-expression.
1514 if (Seq || isa<InitListExpr>(expr)) {
1515 if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1516 expr = HandleEmbed(Embed, Entity);
1517 }
1518 if (!VerifyOnly) {
1519 ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1520 if (Result.isInvalid())
1521 hadError = true;
1522
1523 UpdateStructuredListElement(StructuredList, StructuredIndex,
1524 Result.getAs<Expr>());
1525 } else if (!Seq) {
1526 hadError = true;
1527 } else if (StructuredList) {
1528 UpdateStructuredListElement(StructuredList, StructuredIndex,
1529 getDummyInit());
1530 }
1531 if (!CurEmbed)
1532 ++Index;
1533 if (AggrDeductionCandidateParamTypes)
1534 AggrDeductionCandidateParamTypes->push_back(ElemType);
1535 return;
1536 }
1537 }
1538
1539 // Fall through for subaggregate initialization
1540 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1541 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1542 return CheckScalarType(Entity, IList, ElemType, Index,
1543 StructuredList, StructuredIndex);
1544 } else if (const ArrayType *arrayType =
1545 SemaRef.Context.getAsArrayType(ElemType)) {
1546 // arrayType can be incomplete if we're initializing a flexible
1547 // array member. There's nothing we can do with the completed
1548 // type here, though.
1549
1550 if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1551 // FIXME: Should we do this checking in verify-only mode?
1552 if (!VerifyOnly)
1553 CheckStringInit(expr, ElemType, arrayType, SemaRef,
1554 SemaRef.getLangOpts().C23 &&
1556 if (StructuredList)
1557 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1558 ++Index;
1559 return;
1560 }
1561
1562 // Fall through for subaggregate initialization.
1563
1564 } else {
1565 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1566 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1567
1568 // C99 6.7.8p13:
1569 //
1570 // The initializer for a structure or union object that has
1571 // automatic storage duration shall be either an initializer
1572 // list as described below, or a single expression that has
1573 // compatible structure or union type. In the latter case, the
1574 // initial value of the object, including unnamed members, is
1575 // that of the expression.
1576 ExprResult ExprRes = expr;
1578 ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1579 if (ExprRes.isInvalid())
1580 hadError = true;
1581 else {
1582 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1583 if (ExprRes.isInvalid())
1584 hadError = true;
1585 }
1586 UpdateStructuredListElement(StructuredList, StructuredIndex,
1587 ExprRes.getAs<Expr>());
1588 ++Index;
1589 return;
1590 }
1591 ExprRes.get();
1592 // Fall through for subaggregate initialization
1593 }
1594
1595 // C++ [dcl.init.aggr]p12:
1596 //
1597 // [...] Otherwise, if the member is itself a non-empty
1598 // subaggregate, brace elision is assumed and the initializer is
1599 // considered for the initialization of the first member of
1600 // the subaggregate.
1601 // OpenCL vector initializer is handled elsewhere.
1602 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1603 ElemType->isAggregateType()) {
1604 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1605 StructuredIndex);
1606 ++StructuredIndex;
1607
1608 // In C++20, brace elision is not permitted for a designated initializer.
1609 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1610 if (InOverloadResolution)
1611 hadError = true;
1612 if (!VerifyOnly) {
1613 SemaRef.Diag(expr->getBeginLoc(),
1614 diag::ext_designated_init_brace_elision)
1615 << expr->getSourceRange()
1616 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1618 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1619 }
1620 }
1621 } else {
1622 if (!VerifyOnly) {
1623 // We cannot initialize this element, so let PerformCopyInitialization
1624 // produce the appropriate diagnostic. We already checked that this
1625 // initialization will fail.
1628 /*TopLevelOfInitList=*/true);
1629 (void)Copy;
1630 assert(Copy.isInvalid() &&
1631 "expected non-aggregate initialization to fail");
1632 }
1633 hadError = true;
1634 ++Index;
1635 ++StructuredIndex;
1636 }
1637}
1638
1639void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1640 InitListExpr *IList, QualType DeclType,
1641 unsigned &Index,
1642 InitListExpr *StructuredList,
1643 unsigned &StructuredIndex) {
1644 assert(Index == 0 && "Index in explicit init list must be zero");
1645
1646 // As an extension, clang supports complex initializers, which initialize
1647 // a complex number component-wise. When an explicit initializer list for
1648 // a complex number contains two initializers, this extension kicks in:
1649 // it expects the initializer list to contain two elements convertible to
1650 // the element type of the complex type. The first element initializes
1651 // the real part, and the second element intitializes the imaginary part.
1652
1653 if (IList->getNumInits() < 2)
1654 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1655 StructuredIndex);
1656
1657 // This is an extension in C. (The builtin _Complex type does not exist
1658 // in the C++ standard.)
1659 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1660 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1661 << IList->getSourceRange();
1662
1663 // Initialize the complex number.
1664 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1665 InitializedEntity ElementEntity =
1667
1668 for (unsigned i = 0; i < 2; ++i) {
1669 ElementEntity.setElementIndex(Index);
1670 CheckSubElementType(ElementEntity, IList, elementType, Index,
1671 StructuredList, StructuredIndex);
1672 }
1673}
1674
1675void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1676 InitListExpr *IList, QualType DeclType,
1677 unsigned &Index,
1678 InitListExpr *StructuredList,
1679 unsigned &StructuredIndex) {
1680 if (Index >= IList->getNumInits()) {
1681 if (!VerifyOnly) {
1682 if (SemaRef.getLangOpts().CPlusPlus) {
1683 if (DeclType->isSizelessBuiltinType())
1684 SemaRef.Diag(IList->getBeginLoc(),
1685 SemaRef.getLangOpts().CPlusPlus11
1686 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1687 : diag::err_empty_sizeless_initializer)
1688 << DeclType << IList->getSourceRange();
1689 else
1690 SemaRef.Diag(IList->getBeginLoc(),
1691 SemaRef.getLangOpts().CPlusPlus11
1692 ? diag::warn_cxx98_compat_empty_scalar_initializer
1693 : diag::err_empty_scalar_initializer)
1694 << IList->getSourceRange();
1695 }
1696 }
1697 hadError =
1698 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1699 ++Index;
1700 ++StructuredIndex;
1701 return;
1702 }
1703
1704 Expr *expr = IList->getInit(Index);
1705 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1706 // FIXME: This is invalid, and accepting it causes overload resolution
1707 // to pick the wrong overload in some corner cases.
1708 if (!VerifyOnly)
1709 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1710 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1711
1712 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1713 StructuredIndex);
1714 return;
1715 } else if (isa<DesignatedInitExpr>(expr)) {
1716 if (!VerifyOnly)
1717 SemaRef.Diag(expr->getBeginLoc(),
1718 diag::err_designator_for_scalar_or_sizeless_init)
1719 << DeclType->isSizelessBuiltinType() << DeclType
1720 << expr->getSourceRange();
1721 hadError = true;
1722 ++Index;
1723 ++StructuredIndex;
1724 return;
1725 } else if (auto *Embed = dyn_cast<EmbedExpr>(expr)) {
1726 expr = HandleEmbed(Embed, Entity);
1727 }
1728
1729 ExprResult Result;
1730 if (VerifyOnly) {
1731 if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1732 Result = getDummyInit();
1733 else
1734 Result = ExprError();
1735 } else {
1736 Result =
1737 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1738 /*TopLevelOfInitList=*/true);
1739 }
1740
1741 Expr *ResultExpr = nullptr;
1742
1743 if (Result.isInvalid())
1744 hadError = true; // types weren't compatible.
1745 else {
1746 ResultExpr = Result.getAs<Expr>();
1747
1748 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1749 // The type was promoted, update initializer list.
1750 // FIXME: Why are we updating the syntactic init list?
1751 IList->setInit(Index, ResultExpr);
1752 }
1753 }
1754
1755 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1756 if (!CurEmbed)
1757 ++Index;
1758 if (AggrDeductionCandidateParamTypes)
1759 AggrDeductionCandidateParamTypes->push_back(DeclType);
1760}
1761
1762void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1763 InitListExpr *IList, QualType DeclType,
1764 unsigned &Index,
1765 InitListExpr *StructuredList,
1766 unsigned &StructuredIndex) {
1767 if (Index >= IList->getNumInits()) {
1768 // FIXME: It would be wonderful if we could point at the actual member. In
1769 // general, it would be useful to pass location information down the stack,
1770 // so that we know the location (or decl) of the "current object" being
1771 // initialized.
1772 if (!VerifyOnly)
1773 SemaRef.Diag(IList->getBeginLoc(),
1774 diag::err_init_reference_member_uninitialized)
1775 << DeclType << IList->getSourceRange();
1776 hadError = true;
1777 ++Index;
1778 ++StructuredIndex;
1779 return;
1780 }
1781
1782 Expr *expr = IList->getInit(Index);
1783 if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1784 if (!VerifyOnly)
1785 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1786 << DeclType << IList->getSourceRange();
1787 hadError = true;
1788 ++Index;
1789 ++StructuredIndex;
1790 return;
1791 }
1792
1793 ExprResult Result;
1794 if (VerifyOnly) {
1795 if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1796 Result = getDummyInit();
1797 else
1798 Result = ExprError();
1799 } else {
1800 Result =
1801 SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1802 /*TopLevelOfInitList=*/true);
1803 }
1804
1805 if (Result.isInvalid())
1806 hadError = true;
1807
1808 expr = Result.getAs<Expr>();
1809 // FIXME: Why are we updating the syntactic init list?
1810 if (!VerifyOnly && expr)
1811 IList->setInit(Index, expr);
1812
1813 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1814 ++Index;
1815 if (AggrDeductionCandidateParamTypes)
1816 AggrDeductionCandidateParamTypes->push_back(DeclType);
1817}
1818
1819void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1820 InitListExpr *IList, QualType DeclType,
1821 unsigned &Index,
1822 InitListExpr *StructuredList,
1823 unsigned &StructuredIndex) {
1824 const VectorType *VT = DeclType->castAs<VectorType>();
1825 unsigned maxElements = VT->getNumElements();
1826 unsigned numEltsInit = 0;
1827 QualType elementType = VT->getElementType();
1828
1829 if (Index >= IList->getNumInits()) {
1830 // Make sure the element type can be value-initialized.
1831 CheckEmptyInitializable(
1833 IList->getEndLoc());
1834 return;
1835 }
1836
1837 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1838 // If the initializing element is a vector, try to copy-initialize
1839 // instead of breaking it apart (which is doomed to failure anyway).
1840 Expr *Init = IList->getInit(Index);
1841 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1842 ExprResult Result;
1843 if (VerifyOnly) {
1844 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1845 Result = getDummyInit();
1846 else
1847 Result = ExprError();
1848 } else {
1849 Result =
1850 SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1851 /*TopLevelOfInitList=*/true);
1852 }
1853
1854 Expr *ResultExpr = nullptr;
1855 if (Result.isInvalid())
1856 hadError = true; // types weren't compatible.
1857 else {
1858 ResultExpr = Result.getAs<Expr>();
1859
1860 if (ResultExpr != Init && !VerifyOnly) {
1861 // The type was promoted, update initializer list.
1862 // FIXME: Why are we updating the syntactic init list?
1863 IList->setInit(Index, ResultExpr);
1864 }
1865 }
1866 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1867 ++Index;
1868 if (AggrDeductionCandidateParamTypes)
1869 AggrDeductionCandidateParamTypes->push_back(elementType);
1870 return;
1871 }
1872
1873 InitializedEntity ElementEntity =
1875
1876 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1877 // Don't attempt to go past the end of the init list
1878 if (Index >= IList->getNumInits()) {
1879 CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1880 break;
1881 }
1882
1883 ElementEntity.setElementIndex(Index);
1884 CheckSubElementType(ElementEntity, IList, elementType, Index,
1885 StructuredList, StructuredIndex);
1886 }
1887
1888 if (VerifyOnly)
1889 return;
1890
1891 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1892 const VectorType *T = Entity.getType()->castAs<VectorType>();
1893 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1894 T->getVectorKind() == VectorKind::NeonPoly)) {
1895 // The ability to use vector initializer lists is a GNU vector extension
1896 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1897 // endian machines it works fine, however on big endian machines it
1898 // exhibits surprising behaviour:
1899 //
1900 // uint32x2_t x = {42, 64};
1901 // return vget_lane_u32(x, 0); // Will return 64.
1902 //
1903 // Because of this, explicitly call out that it is non-portable.
1904 //
1905 SemaRef.Diag(IList->getBeginLoc(),
1906 diag::warn_neon_vector_initializer_non_portable);
1907
1908 const char *typeCode;
1909 unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1910
1911 if (elementType->isFloatingType())
1912 typeCode = "f";
1913 else if (elementType->isSignedIntegerType())
1914 typeCode = "s";
1915 else if (elementType->isUnsignedIntegerType())
1916 typeCode = "u";
1917 else
1918 llvm_unreachable("Invalid element type!");
1919
1920 SemaRef.Diag(IList->getBeginLoc(),
1921 SemaRef.Context.getTypeSize(VT) > 64
1922 ? diag::note_neon_vector_initializer_non_portable_q
1923 : diag::note_neon_vector_initializer_non_portable)
1924 << typeCode << typeSize;
1925 }
1926
1927 return;
1928 }
1929
1930 InitializedEntity ElementEntity =
1932
1933 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1934 for (unsigned i = 0; i < maxElements; ++i) {
1935 // Don't attempt to go past the end of the init list
1936 if (Index >= IList->getNumInits())
1937 break;
1938
1939 ElementEntity.setElementIndex(Index);
1940
1941 QualType IType = IList->getInit(Index)->getType();
1942 if (!IType->isVectorType()) {
1943 CheckSubElementType(ElementEntity, IList, elementType, Index,
1944 StructuredList, StructuredIndex);
1945 ++numEltsInit;
1946 } else {
1947 QualType VecType;
1948 const VectorType *IVT = IType->castAs<VectorType>();
1949 unsigned numIElts = IVT->getNumElements();
1950
1951 if (IType->isExtVectorType())
1952 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1953 else
1954 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1955 IVT->getVectorKind());
1956 CheckSubElementType(ElementEntity, IList, VecType, Index,
1957 StructuredList, StructuredIndex);
1958 numEltsInit += numIElts;
1959 }
1960 }
1961
1962 // OpenCL and HLSL require all elements to be initialized.
1963 if (numEltsInit != maxElements) {
1964 if (!VerifyOnly)
1965 SemaRef.Diag(IList->getBeginLoc(),
1966 diag::err_vector_incorrect_num_initializers)
1967 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1968 hadError = true;
1969 }
1970}
1971
1972/// Check if the type of a class element has an accessible destructor, and marks
1973/// it referenced. Returns true if we shouldn't form a reference to the
1974/// destructor.
1975///
1976/// Aggregate initialization requires a class element's destructor be
1977/// accessible per 11.6.1 [dcl.init.aggr]:
1978///
1979/// The destructor for each element of class type is potentially invoked
1980/// (15.4 [class.dtor]) from the context where the aggregate initialization
1981/// occurs.
1983 Sema &SemaRef) {
1984 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1985 if (!CXXRD)
1986 return false;
1987
1989 if (!Destructor)
1990 return false;
1991
1993 SemaRef.PDiag(diag::err_access_dtor_temp)
1994 << ElementType);
1996 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1997}
1998
1999static bool
2001 const InitializedEntity &Entity,
2002 ASTContext &Context) {
2003 QualType InitType = Entity.getType();
2004 const InitializedEntity *Parent = &Entity;
2005
2006 while (Parent) {
2007 InitType = Parent->getType();
2008 Parent = Parent->getParent();
2009 }
2010
2011 // Only one initializer, it's an embed and the types match;
2012 EmbedExpr *EE =
2013 ExprList.size() == 1
2014 ? dyn_cast_if_present<EmbedExpr>(ExprList[0]->IgnoreParens())
2015 : nullptr;
2016 if (!EE)
2017 return false;
2018
2019 if (InitType->isArrayType()) {
2020 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2021 QualType InitElementTy = InitArrayType->getElementType();
2022 QualType EmbedExprElementTy = EE->getDataStringLiteral()->getType();
2023 const bool TypesMatch =
2024 Context.typesAreCompatible(InitElementTy, EmbedExprElementTy) ||
2025 (InitElementTy->isCharType() && EmbedExprElementTy->isCharType());
2026 if (TypesMatch)
2027 return true;
2028 }
2029 return false;
2030}
2031
2032void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2033 InitListExpr *IList, QualType &DeclType,
2034 llvm::APSInt elementIndex,
2035 bool SubobjectIsDesignatorContext,
2036 unsigned &Index,
2037 InitListExpr *StructuredList,
2038 unsigned &StructuredIndex) {
2039 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
2040
2041 if (!VerifyOnly) {
2042 if (checkDestructorReference(arrayType->getElementType(),
2043 IList->getEndLoc(), SemaRef)) {
2044 hadError = true;
2045 return;
2046 }
2047 }
2048
2049 if (canInitializeArrayWithEmbedDataString(IList->inits(), Entity,
2050 SemaRef.Context)) {
2051 EmbedExpr *Embed = cast<EmbedExpr>(IList->inits()[0]);
2052 IList->setInit(0, Embed->getDataStringLiteral());
2053 }
2054
2055 // Check for the special-case of initializing an array with a string.
2056 if (Index < IList->getNumInits()) {
2057 if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
2058 SIF_None) {
2059 // We place the string literal directly into the resulting
2060 // initializer list. This is the only place where the structure
2061 // of the structured initializer list doesn't match exactly,
2062 // because doing so would involve allocating one character
2063 // constant for each string.
2064 // FIXME: Should we do these checks in verify-only mode too?
2065 if (!VerifyOnly)
2066 CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef,
2067 SemaRef.getLangOpts().C23 &&
2069 if (StructuredList) {
2070 UpdateStructuredListElement(StructuredList, StructuredIndex,
2071 IList->getInit(Index));
2072 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
2073 }
2074 ++Index;
2075 if (AggrDeductionCandidateParamTypes)
2076 AggrDeductionCandidateParamTypes->push_back(DeclType);
2077 return;
2078 }
2079 }
2080 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
2081 // Check for VLAs; in standard C it would be possible to check this
2082 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2083 // them in all sorts of strange places).
2084 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2085 if (!VerifyOnly) {
2086 // C23 6.7.10p4: An entity of variable length array type shall not be
2087 // initialized except by an empty initializer.
2088 //
2089 // The C extension warnings are issued from ParseBraceInitializer() and
2090 // do not need to be issued here. However, we continue to issue an error
2091 // in the case there are initializers or we are compiling C++. We allow
2092 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2093 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2094 // FIXME: should we allow this construct in C++ when it makes sense to do
2095 // so?
2096 if (HasErr)
2097 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2098 diag::err_variable_object_no_init)
2099 << VAT->getSizeExpr()->getSourceRange();
2100 }
2101 hadError = HasErr;
2102 ++Index;
2103 ++StructuredIndex;
2104 return;
2105 }
2106
2107 // We might know the maximum number of elements in advance.
2108 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2109 elementIndex.isUnsigned());
2110 bool maxElementsKnown = false;
2111 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
2112 maxElements = CAT->getSize();
2113 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
2114 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2115 maxElementsKnown = true;
2116 }
2117
2118 QualType elementType = arrayType->getElementType();
2119 while (Index < IList->getNumInits()) {
2120 Expr *Init = IList->getInit(Index);
2121 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2122 // If we're not the subobject that matches up with the '{' for
2123 // the designator, we shouldn't be handling the
2124 // designator. Return immediately.
2125 if (!SubobjectIsDesignatorContext)
2126 return;
2127
2128 // Handle this designated initializer. elementIndex will be
2129 // updated to be the next array element we'll initialize.
2130 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2131 DeclType, nullptr, &elementIndex, Index,
2132 StructuredList, StructuredIndex, true,
2133 false)) {
2134 hadError = true;
2135 continue;
2136 }
2137
2138 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2139 maxElements = maxElements.extend(elementIndex.getBitWidth());
2140 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2141 elementIndex = elementIndex.extend(maxElements.getBitWidth());
2142 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2143
2144 // If the array is of incomplete type, keep track of the number of
2145 // elements in the initializer.
2146 if (!maxElementsKnown && elementIndex > maxElements)
2147 maxElements = elementIndex;
2148
2149 continue;
2150 }
2151
2152 // If we know the maximum number of elements, and we've already
2153 // hit it, stop consuming elements in the initializer list.
2154 if (maxElementsKnown && elementIndex == maxElements)
2155 break;
2156
2158 SemaRef.Context, StructuredIndex, Entity);
2159
2160 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2161 // Check this element.
2162 CheckSubElementType(ElementEntity, IList, elementType, Index,
2163 StructuredList, StructuredIndex);
2164 ++elementIndex;
2165 if ((CurEmbed || isa<EmbedExpr>(Init)) && elementType->isScalarType()) {
2166 if (CurEmbed) {
2167 elementIndex =
2168 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2169 } else {
2170 auto Embed = cast<EmbedExpr>(Init);
2171 elementIndex = elementIndex + Embed->getDataElementCount() -
2172 EmbedElementIndexBeforeInit - 1;
2173 }
2174 }
2175
2176 // If the array is of incomplete type, keep track of the number of
2177 // elements in the initializer.
2178 if (!maxElementsKnown && elementIndex > maxElements)
2179 maxElements = elementIndex;
2180 }
2181 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2182 // If this is an incomplete array type, the actual type needs to
2183 // be calculated here.
2184 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2185 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2186 // Sizing an array implicitly to zero is not allowed by ISO C,
2187 // but is supported by GNU.
2188 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2189 }
2190
2191 DeclType = SemaRef.Context.getConstantArrayType(
2192 elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2193 }
2194 if (!hadError) {
2195 // If there are any members of the array that get value-initialized, check
2196 // that is possible. That happens if we know the bound and don't have
2197 // enough elements, or if we're performing an array new with an unknown
2198 // bound.
2199 if ((maxElementsKnown && elementIndex < maxElements) ||
2200 Entity.isVariableLengthArrayNew())
2201 CheckEmptyInitializable(
2203 IList->getEndLoc());
2204 }
2205}
2206
2207bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2208 Expr *InitExpr,
2209 FieldDecl *Field,
2210 bool TopLevelObject) {
2211 // Handle GNU flexible array initializers.
2212 unsigned FlexArrayDiag;
2213 if (isa<InitListExpr>(InitExpr) &&
2214 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2215 // Empty flexible array init always allowed as an extension
2216 FlexArrayDiag = diag::ext_flexible_array_init;
2217 } else if (!TopLevelObject) {
2218 // Disallow flexible array init on non-top-level object
2219 FlexArrayDiag = diag::err_flexible_array_init;
2220 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2221 // Disallow flexible array init on anything which is not a variable.
2222 FlexArrayDiag = diag::err_flexible_array_init;
2223 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2224 // Disallow flexible array init on local variables.
2225 FlexArrayDiag = diag::err_flexible_array_init;
2226 } else {
2227 // Allow other cases.
2228 FlexArrayDiag = diag::ext_flexible_array_init;
2229 }
2230
2231 if (!VerifyOnly) {
2232 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2233 << InitExpr->getBeginLoc();
2234 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2235 << Field;
2236 }
2237
2238 return FlexArrayDiag != diag::ext_flexible_array_init;
2239}
2240
2241void InitListChecker::CheckStructUnionTypes(
2242 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2244 bool SubobjectIsDesignatorContext, unsigned &Index,
2245 InitListExpr *StructuredList, unsigned &StructuredIndex,
2246 bool TopLevelObject) {
2247 const RecordDecl *RD = getRecordDecl(DeclType);
2248
2249 // If the record is invalid, some of it's members are invalid. To avoid
2250 // confusion, we forgo checking the initializer for the entire record.
2251 if (RD->isInvalidDecl()) {
2252 // Assume it was supposed to consume a single initializer.
2253 ++Index;
2254 hadError = true;
2255 return;
2256 }
2257
2258 if (RD->isUnion() && IList->getNumInits() == 0) {
2259 if (!VerifyOnly)
2260 for (FieldDecl *FD : RD->fields()) {
2261 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2262 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2263 hadError = true;
2264 return;
2265 }
2266 }
2267
2268 // If there's a default initializer, use it.
2269 if (isa<CXXRecordDecl>(RD) &&
2270 cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2271 if (!StructuredList)
2272 return;
2273 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2274 Field != FieldEnd; ++Field) {
2275 if (Field->hasInClassInitializer() ||
2276 (Field->isAnonymousStructOrUnion() &&
2277 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
2278 StructuredList->setInitializedFieldInUnion(*Field);
2279 // FIXME: Actually build a CXXDefaultInitExpr?
2280 return;
2281 }
2282 }
2283 llvm_unreachable("Couldn't find in-class initializer");
2284 }
2285
2286 // Value-initialize the first member of the union that isn't an unnamed
2287 // bitfield.
2288 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2289 Field != FieldEnd; ++Field) {
2290 if (!Field->isUnnamedBitField()) {
2291 CheckEmptyInitializable(
2292 InitializedEntity::InitializeMember(*Field, &Entity),
2293 IList->getEndLoc());
2294 if (StructuredList)
2295 StructuredList->setInitializedFieldInUnion(*Field);
2296 break;
2297 }
2298 }
2299 return;
2300 }
2301
2302 bool InitializedSomething = false;
2303
2304 // If we have any base classes, they are initialized prior to the fields.
2305 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2306 auto &Base = *I;
2307 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2308
2309 // Designated inits always initialize fields, so if we see one, all
2310 // remaining base classes have no explicit initializer.
2311 if (isa_and_nonnull<DesignatedInitExpr>(Init))
2312 Init = nullptr;
2313
2314 // C++ [over.match.class.deduct]p1.6:
2315 // each non-trailing aggregate element that is a pack expansion is assumed
2316 // to correspond to no elements of the initializer list, and (1.7) a
2317 // trailing aggregate element that is a pack expansion is assumed to
2318 // correspond to all remaining elements of the initializer list (if any).
2319
2320 // C++ [over.match.class.deduct]p1.9:
2321 // ... except that additional parameter packs of the form P_j... are
2322 // inserted into the parameter list in their original aggregate element
2323 // position corresponding to each non-trailing aggregate element of
2324 // type P_j that was skipped because it was a parameter pack, and the
2325 // trailing sequence of parameters corresponding to a trailing
2326 // aggregate element that is a pack expansion (if any) is replaced
2327 // by a single parameter of the form T_n....
2328 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2329 AggrDeductionCandidateParamTypes->push_back(
2330 SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2331
2332 // Trailing pack expansion
2333 if (I + 1 == E && RD->field_empty()) {
2334 if (Index < IList->getNumInits())
2335 Index = IList->getNumInits();
2336 return;
2337 }
2338
2339 continue;
2340 }
2341
2342 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2344 SemaRef.Context, &Base, false, &Entity);
2345 if (Init) {
2346 CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2347 StructuredList, StructuredIndex);
2348 InitializedSomething = true;
2349 } else {
2350 CheckEmptyInitializable(BaseEntity, InitLoc);
2351 }
2352
2353 if (!VerifyOnly)
2354 if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2355 hadError = true;
2356 return;
2357 }
2358 }
2359
2360 // If structDecl is a forward declaration, this loop won't do
2361 // anything except look at designated initializers; That's okay,
2362 // because an error should get printed out elsewhere. It might be
2363 // worthwhile to skip over the rest of the initializer, though.
2364 RecordDecl::field_iterator FieldEnd = RD->field_end();
2365 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2366 return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2367 });
2368 bool HasDesignatedInit = false;
2369
2370 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2371
2372 while (Index < IList->getNumInits()) {
2373 Expr *Init = IList->getInit(Index);
2374 SourceLocation InitLoc = Init->getBeginLoc();
2375
2376 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2377 // If we're not the subobject that matches up with the '{' for
2378 // the designator, we shouldn't be handling the
2379 // designator. Return immediately.
2380 if (!SubobjectIsDesignatorContext)
2381 return;
2382
2383 HasDesignatedInit = true;
2384
2385 // Handle this designated initializer. Field will be updated to
2386 // the next field that we'll be initializing.
2387 bool DesignatedInitFailed = CheckDesignatedInitializer(
2388 Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2389 StructuredList, StructuredIndex, true, TopLevelObject);
2390 if (DesignatedInitFailed)
2391 hadError = true;
2392
2393 // Find the field named by the designated initializer.
2394 DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2395 if (!VerifyOnly && D->isFieldDesignator()) {
2396 FieldDecl *F = D->getFieldDecl();
2397 InitializedFields.insert(F);
2398 if (!DesignatedInitFailed) {
2399 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2400 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2401 hadError = true;
2402 return;
2403 }
2404 }
2405 }
2406
2407 InitializedSomething = true;
2408 continue;
2409 }
2410
2411 // Check if this is an initializer of forms:
2412 //
2413 // struct foo f = {};
2414 // struct foo g = {0};
2415 //
2416 // These are okay for randomized structures. [C99 6.7.8p19]
2417 //
2418 // Also, if there is only one element in the structure, we allow something
2419 // like this, because it's really not randomized in the traditional sense.
2420 //
2421 // struct foo h = {bar};
2422 auto IsZeroInitializer = [&](const Expr *I) {
2423 if (IList->getNumInits() == 1) {
2424 if (NumRecordDecls == 1)
2425 return true;
2426 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2427 return IL->getValue().isZero();
2428 }
2429 return false;
2430 };
2431
2432 // Don't allow non-designated initializers on randomized structures.
2433 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2434 if (!VerifyOnly)
2435 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2436 hadError = true;
2437 break;
2438 }
2439
2440 if (Field == FieldEnd) {
2441 // We've run out of fields. We're done.
2442 break;
2443 }
2444
2445 // We've already initialized a member of a union. We can stop entirely.
2446 if (InitializedSomething && RD->isUnion())
2447 return;
2448
2449 // Stop if we've hit a flexible array member.
2450 if (Field->getType()->isIncompleteArrayType())
2451 break;
2452
2453 if (Field->isUnnamedBitField()) {
2454 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2455 ++Field;
2456 continue;
2457 }
2458
2459 // Make sure we can use this declaration.
2460 bool InvalidUse;
2461 if (VerifyOnly)
2462 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2463 else
2464 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2465 *Field, IList->getInit(Index)->getBeginLoc());
2466 if (InvalidUse) {
2467 ++Index;
2468 ++Field;
2469 hadError = true;
2470 continue;
2471 }
2472
2473 if (!VerifyOnly) {
2474 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2475 if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2476 hadError = true;
2477 return;
2478 }
2479 }
2480
2481 InitializedEntity MemberEntity =
2482 InitializedEntity::InitializeMember(*Field, &Entity);
2483 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2484 StructuredList, StructuredIndex);
2485 InitializedSomething = true;
2486 InitializedFields.insert(*Field);
2487
2488 if (RD->isUnion() && StructuredList) {
2489 // Initialize the first field within the union.
2490 StructuredList->setInitializedFieldInUnion(*Field);
2491 }
2492
2493 ++Field;
2494 }
2495
2496 // Emit warnings for missing struct field initializers.
2497 // This check is disabled for designated initializers in C.
2498 // This matches gcc behaviour.
2499 bool IsCDesignatedInitializer =
2500 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2501 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2502 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
2503 !IsCDesignatedInitializer) {
2504 // It is possible we have one or more unnamed bitfields remaining.
2505 // Find first (if any) named field and emit warning.
2506 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2507 : Field,
2508 end = RD->field_end();
2509 it != end; ++it) {
2510 if (HasDesignatedInit && InitializedFields.count(*it))
2511 continue;
2512
2513 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2514 !it->getType()->isIncompleteArrayType()) {
2515 auto Diag = HasDesignatedInit
2516 ? diag::warn_missing_designated_field_initializers
2517 : diag::warn_missing_field_initializers;
2518 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2519 break;
2520 }
2521 }
2522 }
2523
2524 // Check that any remaining fields can be value-initialized if we're not
2525 // building a structured list. (If we are, we'll check this later.)
2526 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2527 !Field->getType()->isIncompleteArrayType()) {
2528 for (; Field != FieldEnd && !hadError; ++Field) {
2529 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2530 CheckEmptyInitializable(
2531 InitializedEntity::InitializeMember(*Field, &Entity),
2532 IList->getEndLoc());
2533 }
2534 }
2535
2536 // Check that the types of the remaining fields have accessible destructors.
2537 if (!VerifyOnly) {
2538 // If the initializer expression has a designated initializer, check the
2539 // elements for which a designated initializer is not provided too.
2540 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2541 : Field;
2542 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2543 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2544 if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2545 hadError = true;
2546 return;
2547 }
2548 }
2549 }
2550
2551 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2552 Index >= IList->getNumInits())
2553 return;
2554
2555 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2556 TopLevelObject)) {
2557 hadError = true;
2558 ++Index;
2559 return;
2560 }
2561
2562 InitializedEntity MemberEntity =
2563 InitializedEntity::InitializeMember(*Field, &Entity);
2564
2565 if (isa<InitListExpr>(IList->getInit(Index)) ||
2566 AggrDeductionCandidateParamTypes)
2567 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2568 StructuredList, StructuredIndex);
2569 else
2570 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2571 StructuredList, StructuredIndex);
2572
2573 if (RD->isUnion() && StructuredList) {
2574 // Initialize the first field within the union.
2575 StructuredList->setInitializedFieldInUnion(*Field);
2576 }
2577}
2578
2579/// Expand a field designator that refers to a member of an
2580/// anonymous struct or union into a series of field designators that
2581/// refers to the field within the appropriate subobject.
2582///
2584 DesignatedInitExpr *DIE,
2585 unsigned DesigIdx,
2586 IndirectFieldDecl *IndirectField) {
2588
2589 // Build the replacement designators.
2590 SmallVector<Designator, 4> Replacements;
2591 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2592 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2593 if (PI + 1 == PE)
2594 Replacements.push_back(Designator::CreateFieldDesignator(
2595 (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2596 DIE->getDesignator(DesigIdx)->getFieldLoc()));
2597 else
2598 Replacements.push_back(Designator::CreateFieldDesignator(
2599 (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2600 assert(isa<FieldDecl>(*PI));
2601 Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2602 }
2603
2604 // Expand the current designator into the set of replacement
2605 // designators, so we have a full subobject path down to where the
2606 // member of the anonymous struct/union is actually stored.
2607 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2608 &Replacements[0] + Replacements.size());
2609}
2610
2612 DesignatedInitExpr *DIE) {
2613 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2614 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2615 for (unsigned I = 0; I < NumIndexExprs; ++I)
2616 IndexExprs[I] = DIE->getSubExpr(I + 1);
2617 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2618 IndexExprs,
2619 DIE->getEqualOrColonLoc(),
2620 DIE->usesGNUSyntax(), DIE->getInit());
2621}
2622
2623namespace {
2624
2625// Callback to only accept typo corrections that are for field members of
2626// the given struct or union.
2627class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2628 public:
2629 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2630 : Record(RD) {}
2631
2632 bool ValidateCandidate(const TypoCorrection &candidate) override {
2633 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2634 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2635 }
2636
2637 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2638 return std::make_unique<FieldInitializerValidatorCCC>(*this);
2639 }
2640
2641 private:
2642 const RecordDecl *Record;
2643};
2644
2645} // end anonymous namespace
2646
2647/// Check the well-formedness of a C99 designated initializer.
2648///
2649/// Determines whether the designated initializer @p DIE, which
2650/// resides at the given @p Index within the initializer list @p
2651/// IList, is well-formed for a current object of type @p DeclType
2652/// (C99 6.7.8). The actual subobject that this designator refers to
2653/// within the current subobject is returned in either
2654/// @p NextField or @p NextElementIndex (whichever is appropriate).
2655///
2656/// @param IList The initializer list in which this designated
2657/// initializer occurs.
2658///
2659/// @param DIE The designated initializer expression.
2660///
2661/// @param DesigIdx The index of the current designator.
2662///
2663/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2664/// into which the designation in @p DIE should refer.
2665///
2666/// @param NextField If non-NULL and the first designator in @p DIE is
2667/// a field, this will be set to the field declaration corresponding
2668/// to the field named by the designator. On input, this is expected to be
2669/// the next field that would be initialized in the absence of designation,
2670/// if the complete object being initialized is a struct.
2671///
2672/// @param NextElementIndex If non-NULL and the first designator in @p
2673/// DIE is an array designator or GNU array-range designator, this
2674/// will be set to the last index initialized by this designator.
2675///
2676/// @param Index Index into @p IList where the designated initializer
2677/// @p DIE occurs.
2678///
2679/// @param StructuredList The initializer list expression that
2680/// describes all of the subobject initializers in the order they'll
2681/// actually be initialized.
2682///
2683/// @returns true if there was an error, false otherwise.
2684bool
2685InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2686 InitListExpr *IList,
2687 DesignatedInitExpr *DIE,
2688 unsigned DesigIdx,
2689 QualType &CurrentObjectType,
2690 RecordDecl::field_iterator *NextField,
2691 llvm::APSInt *NextElementIndex,
2692 unsigned &Index,
2693 InitListExpr *StructuredList,
2694 unsigned &StructuredIndex,
2695 bool FinishSubobjectInit,
2696 bool TopLevelObject) {
2697 if (DesigIdx == DIE->size()) {
2698 // C++20 designated initialization can result in direct-list-initialization
2699 // of the designated subobject. This is the only way that we can end up
2700 // performing direct initialization as part of aggregate initialization, so
2701 // it needs special handling.
2702 if (DIE->isDirectInit()) {
2703 Expr *Init = DIE->getInit();
2704 assert(isa<InitListExpr>(Init) &&
2705 "designator result in direct non-list initialization?");
2707 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2708 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2709 /*TopLevelOfInitList*/ true);
2710 if (StructuredList) {
2711 ExprResult Result = VerifyOnly
2712 ? getDummyInit()
2713 : Seq.Perform(SemaRef, Entity, Kind, Init);
2714 UpdateStructuredListElement(StructuredList, StructuredIndex,
2715 Result.get());
2716 }
2717 ++Index;
2718 if (AggrDeductionCandidateParamTypes)
2719 AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2720 return !Seq;
2721 }
2722
2723 // Check the actual initialization for the designated object type.
2724 bool prevHadError = hadError;
2725
2726 // Temporarily remove the designator expression from the
2727 // initializer list that the child calls see, so that we don't try
2728 // to re-process the designator.
2729 unsigned OldIndex = Index;
2730 IList->setInit(OldIndex, DIE->getInit());
2731
2732 CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2733 StructuredIndex, /*DirectlyDesignated=*/true);
2734
2735 // Restore the designated initializer expression in the syntactic
2736 // form of the initializer list.
2737 if (IList->getInit(OldIndex) != DIE->getInit())
2738 DIE->setInit(IList->getInit(OldIndex));
2739 IList->setInit(OldIndex, DIE);
2740
2741 return hadError && !prevHadError;
2742 }
2743
2745 bool IsFirstDesignator = (DesigIdx == 0);
2746 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2747 // Determine the structural initializer list that corresponds to the
2748 // current subobject.
2749 if (IsFirstDesignator)
2750 StructuredList = FullyStructuredList;
2751 else {
2752 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2753 StructuredList->getInit(StructuredIndex) : nullptr;
2754 if (!ExistingInit && StructuredList->hasArrayFiller())
2755 ExistingInit = StructuredList->getArrayFiller();
2756
2757 if (!ExistingInit)
2758 StructuredList = getStructuredSubobjectInit(
2759 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2760 SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2761 else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2762 StructuredList = Result;
2763 else {
2764 // We are creating an initializer list that initializes the
2765 // subobjects of the current object, but there was already an
2766 // initialization that completely initialized the current
2767 // subobject, e.g., by a compound literal:
2768 //
2769 // struct X { int a, b; };
2770 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2771 //
2772 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2773 // designated initializer re-initializes only its current object
2774 // subobject [0].b.
2775 diagnoseInitOverride(ExistingInit,
2776 SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2777 /*UnionOverride=*/false,
2778 /*FullyOverwritten=*/false);
2779
2780 if (!VerifyOnly) {
2782 dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2783 StructuredList = E->getUpdater();
2784 else {
2785 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2787 ExistingInit, DIE->getEndLoc());
2788 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2789 StructuredList = DIUE->getUpdater();
2790 }
2791 } else {
2792 // We don't need to track the structured representation of a
2793 // designated init update of an already-fully-initialized object in
2794 // verify-only mode. The only reason we would need the structure is
2795 // to determine where the uninitialized "holes" are, and in this
2796 // case, we know there aren't any and we can't introduce any.
2797 StructuredList = nullptr;
2798 }
2799 }
2800 }
2801 }
2802
2803 if (D->isFieldDesignator()) {
2804 // C99 6.7.8p7:
2805 //
2806 // If a designator has the form
2807 //
2808 // . identifier
2809 //
2810 // then the current object (defined below) shall have
2811 // structure or union type and the identifier shall be the
2812 // name of a member of that type.
2813 RecordDecl *RD = getRecordDecl(CurrentObjectType);
2814 if (!RD) {
2815 SourceLocation Loc = D->getDotLoc();
2816 if (Loc.isInvalid())
2817 Loc = D->getFieldLoc();
2818 if (!VerifyOnly)
2819 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2820 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2821 ++Index;
2822 return true;
2823 }
2824
2825 FieldDecl *KnownField = D->getFieldDecl();
2826 if (!KnownField) {
2827 const IdentifierInfo *FieldName = D->getFieldName();
2828 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2829 if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2830 KnownField = FD;
2831 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2832 // In verify mode, don't modify the original.
2833 if (VerifyOnly)
2834 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2835 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2836 D = DIE->getDesignator(DesigIdx);
2837 KnownField = cast<FieldDecl>(*IFD->chain_begin());
2838 }
2839 if (!KnownField) {
2840 if (VerifyOnly) {
2841 ++Index;
2842 return true; // No typo correction when just trying this out.
2843 }
2844
2845 // We found a placeholder variable
2846 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2847 FieldName)) {
2848 ++Index;
2849 return true;
2850 }
2851 // Name lookup found something, but it wasn't a field.
2852 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2853 !Lookup.empty()) {
2854 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2855 << FieldName;
2856 SemaRef.Diag(Lookup.front()->getLocation(),
2857 diag::note_field_designator_found);
2858 ++Index;
2859 return true;
2860 }
2861
2862 // Name lookup didn't find anything.
2863 // Determine whether this was a typo for another field name.
2864 FieldInitializerValidatorCCC CCC(RD);
2865 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2866 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2867 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2869 SemaRef.diagnoseTypo(
2870 Corrected,
2871 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2872 << FieldName << CurrentObjectType);
2873 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2874 hadError = true;
2875 } else {
2876 // Typo correction didn't find anything.
2877 SourceLocation Loc = D->getFieldLoc();
2878
2879 // The loc can be invalid with a "null" designator (i.e. an anonymous
2880 // union/struct). Do our best to approximate the location.
2881 if (Loc.isInvalid())
2882 Loc = IList->getBeginLoc();
2883
2884 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2885 << FieldName << CurrentObjectType << DIE->getSourceRange();
2886 ++Index;
2887 return true;
2888 }
2889 }
2890 }
2891
2892 unsigned NumBases = 0;
2893 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2894 NumBases = CXXRD->getNumBases();
2895
2896 unsigned FieldIndex = NumBases;
2897
2898 for (auto *FI : RD->fields()) {
2899 if (FI->isUnnamedBitField())
2900 continue;
2901 if (declaresSameEntity(KnownField, FI)) {
2902 KnownField = FI;
2903 break;
2904 }
2905 ++FieldIndex;
2906 }
2907
2910
2911 // All of the fields of a union are located at the same place in
2912 // the initializer list.
2913 if (RD->isUnion()) {
2914 FieldIndex = 0;
2915 if (StructuredList) {
2916 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2917 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2918 assert(StructuredList->getNumInits() == 1
2919 && "A union should never have more than one initializer!");
2920
2921 Expr *ExistingInit = StructuredList->getInit(0);
2922 if (ExistingInit) {
2923 // We're about to throw away an initializer, emit warning.
2924 diagnoseInitOverride(
2925 ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2926 /*UnionOverride=*/true,
2927 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2928 : true);
2929 }
2930
2931 // remove existing initializer
2932 StructuredList->resizeInits(SemaRef.Context, 0);
2933 StructuredList->setInitializedFieldInUnion(nullptr);
2934 }
2935
2936 StructuredList->setInitializedFieldInUnion(*Field);
2937 }
2938 }
2939
2940 // Make sure we can use this declaration.
2941 bool InvalidUse;
2942 if (VerifyOnly)
2943 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2944 else
2945 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2946 if (InvalidUse) {
2947 ++Index;
2948 return true;
2949 }
2950
2951 // C++20 [dcl.init.list]p3:
2952 // The ordered identifiers in the designators of the designated-
2953 // initializer-list shall form a subsequence of the ordered identifiers
2954 // in the direct non-static data members of T.
2955 //
2956 // Note that this is not a condition on forming the aggregate
2957 // initialization, only on actually performing initialization,
2958 // so it is not checked in VerifyOnly mode.
2959 //
2960 // FIXME: This is the only reordering diagnostic we produce, and it only
2961 // catches cases where we have a top-level field designator that jumps
2962 // backwards. This is the only such case that is reachable in an
2963 // otherwise-valid C++20 program, so is the only case that's required for
2964 // conformance, but for consistency, we should diagnose all the other
2965 // cases where a designator takes us backwards too.
2966 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2967 NextField &&
2968 (*NextField == RD->field_end() ||
2969 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2970 // Find the field that we just initialized.
2971 FieldDecl *PrevField = nullptr;
2972 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2973 if (FI->isUnnamedBitField())
2974 continue;
2975 if (*NextField != RD->field_end() &&
2976 declaresSameEntity(*FI, **NextField))
2977 break;
2978 PrevField = *FI;
2979 }
2980
2981 if (PrevField &&
2982 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2983 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2984 diag::ext_designated_init_reordered)
2985 << KnownField << PrevField << DIE->getSourceRange();
2986
2987 unsigned OldIndex = StructuredIndex - 1;
2988 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2989 if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2990 SemaRef.Diag(PrevInit->getBeginLoc(),
2991 diag::note_previous_field_init)
2992 << PrevField << PrevInit->getSourceRange();
2993 }
2994 }
2995 }
2996 }
2997
2998
2999 // Update the designator with the field declaration.
3000 if (!VerifyOnly)
3001 D->setFieldDecl(*Field);
3002
3003 // Make sure that our non-designated initializer list has space
3004 // for a subobject corresponding to this field.
3005 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3006 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
3007
3008 // This designator names a flexible array member.
3009 if (Field->getType()->isIncompleteArrayType()) {
3010 bool Invalid = false;
3011 if ((DesigIdx + 1) != DIE->size()) {
3012 // We can't designate an object within the flexible array
3013 // member (because GCC doesn't allow it).
3014 if (!VerifyOnly) {
3016 = DIE->getDesignator(DesigIdx + 1);
3017 SemaRef.Diag(NextD->getBeginLoc(),
3018 diag::err_designator_into_flexible_array_member)
3019 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3020 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3021 << *Field;
3022 }
3023 Invalid = true;
3024 }
3025
3026 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
3027 !isa<StringLiteral>(DIE->getInit())) {
3028 // The initializer is not an initializer list.
3029 if (!VerifyOnly) {
3030 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
3031 diag::err_flexible_array_init_needs_braces)
3032 << DIE->getInit()->getSourceRange();
3033 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
3034 << *Field;
3035 }
3036 Invalid = true;
3037 }
3038
3039 // Check GNU flexible array initializer.
3040 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
3041 TopLevelObject))
3042 Invalid = true;
3043
3044 if (Invalid) {
3045 ++Index;
3046 return true;
3047 }
3048
3049 // Initialize the array.
3050 bool prevHadError = hadError;
3051 unsigned newStructuredIndex = FieldIndex;
3052 unsigned OldIndex = Index;
3053 IList->setInit(Index, DIE->getInit());
3054
3055 InitializedEntity MemberEntity =
3056 InitializedEntity::InitializeMember(*Field, &Entity);
3057 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
3058 StructuredList, newStructuredIndex);
3059
3060 IList->setInit(OldIndex, DIE);
3061 if (hadError && !prevHadError) {
3062 ++Field;
3063 ++FieldIndex;
3064 if (NextField)
3065 *NextField = Field;
3066 StructuredIndex = FieldIndex;
3067 return true;
3068 }
3069 } else {
3070 // Recurse to check later designated subobjects.
3071 QualType FieldType = Field->getType();
3072 unsigned newStructuredIndex = FieldIndex;
3073
3074 InitializedEntity MemberEntity =
3075 InitializedEntity::InitializeMember(*Field, &Entity);
3076 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
3077 FieldType, nullptr, nullptr, Index,
3078 StructuredList, newStructuredIndex,
3079 FinishSubobjectInit, false))
3080 return true;
3081 }
3082
3083 // Find the position of the next field to be initialized in this
3084 // subobject.
3085 ++Field;
3086 ++FieldIndex;
3087
3088 // If this the first designator, our caller will continue checking
3089 // the rest of this struct/class/union subobject.
3090 if (IsFirstDesignator) {
3091 if (Field != RD->field_end() && Field->isUnnamedBitField())
3092 ++Field;
3093
3094 if (NextField)
3095 *NextField = Field;
3096
3097 StructuredIndex = FieldIndex;
3098 return false;
3099 }
3100
3101 if (!FinishSubobjectInit)
3102 return false;
3103
3104 // We've already initialized something in the union; we're done.
3105 if (RD->isUnion())
3106 return hadError;
3107
3108 // Check the remaining fields within this class/struct/union subobject.
3109 bool prevHadError = hadError;
3110
3111 auto NoBases =
3114 CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
3115 false, Index, StructuredList, FieldIndex);
3116 return hadError && !prevHadError;
3117 }
3118
3119 // C99 6.7.8p6:
3120 //
3121 // If a designator has the form
3122 //
3123 // [ constant-expression ]
3124 //
3125 // then the current object (defined below) shall have array
3126 // type and the expression shall be an integer constant
3127 // expression. If the array is of unknown size, any
3128 // nonnegative value is valid.
3129 //
3130 // Additionally, cope with the GNU extension that permits
3131 // designators of the form
3132 //
3133 // [ constant-expression ... constant-expression ]
3134 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
3135 if (!AT) {
3136 if (!VerifyOnly)
3137 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3138 << CurrentObjectType;
3139 ++Index;
3140 return true;
3141 }
3142
3143 Expr *IndexExpr = nullptr;
3144 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3145 if (D->isArrayDesignator()) {
3146 IndexExpr = DIE->getArrayIndex(*D);
3147 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3148 DesignatedEndIndex = DesignatedStartIndex;
3149 } else {
3150 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3151
3152 DesignatedStartIndex =
3154 DesignatedEndIndex =
3156 IndexExpr = DIE->getArrayRangeEnd(*D);
3157
3158 // Codegen can't handle evaluating array range designators that have side
3159 // effects, because we replicate the AST value for each initialized element.
3160 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3161 // elements with something that has a side effect, so codegen can emit an
3162 // "error unsupported" error instead of miscompiling the app.
3163 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3164 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3165 FullyStructuredList->sawArrayRangeDesignator();
3166 }
3167
3168 if (isa<ConstantArrayType>(AT)) {
3169 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3170 DesignatedStartIndex
3171 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3172 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3173 DesignatedEndIndex
3174 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3175 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3176 if (DesignatedEndIndex >= MaxElements) {
3177 if (!VerifyOnly)
3178 SemaRef.Diag(IndexExpr->getBeginLoc(),
3179 diag::err_array_designator_too_large)
3180 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3181 << IndexExpr->getSourceRange();
3182 ++Index;
3183 return true;
3184 }
3185 } else {
3186 unsigned DesignatedIndexBitWidth =
3188 DesignatedStartIndex =
3189 DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3190 DesignatedEndIndex =
3191 DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3192 DesignatedStartIndex.setIsUnsigned(true);
3193 DesignatedEndIndex.setIsUnsigned(true);
3194 }
3195
3196 bool IsStringLiteralInitUpdate =
3197 StructuredList && StructuredList->isStringLiteralInit();
3198 if (IsStringLiteralInitUpdate && VerifyOnly) {
3199 // We're just verifying an update to a string literal init. We don't need
3200 // to split the string up into individual characters to do that.
3201 StructuredList = nullptr;
3202 } else if (IsStringLiteralInitUpdate) {
3203 // We're modifying a string literal init; we have to decompose the string
3204 // so we can modify the individual characters.
3205 ASTContext &Context = SemaRef.Context;
3206 Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3207
3208 // Compute the character type
3209 QualType CharTy = AT->getElementType();
3210
3211 // Compute the type of the integer literals.
3212 QualType PromotedCharTy = CharTy;
3213 if (Context.isPromotableIntegerType(CharTy))
3214 PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3215 unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3216
3217 if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3218 // Get the length of the string.
3219 uint64_t StrLen = SL->getLength();
3220 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3221 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3222 StructuredList->resizeInits(Context, StrLen);
3223
3224 // Build a literal for each character in the string, and put them into
3225 // the init list.
3226 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3227 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3228 Expr *Init = new (Context) IntegerLiteral(
3229 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3230 if (CharTy != PromotedCharTy)
3231 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3232 Init, nullptr, VK_PRValue,
3234 StructuredList->updateInit(Context, i, Init);
3235 }
3236 } else {
3237 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3238 std::string Str;
3239 Context.getObjCEncodingForType(E->getEncodedType(), Str);
3240
3241 // Get the length of the string.
3242 uint64_t StrLen = Str.size();
3243 if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3244 StrLen = cast<ConstantArrayType>(AT)->getZExtSize();
3245 StructuredList->resizeInits(Context, StrLen);
3246
3247 // Build a literal for each character in the string, and put them into
3248 // the init list.
3249 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3250 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3251 Expr *Init = new (Context) IntegerLiteral(
3252 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3253 if (CharTy != PromotedCharTy)
3254 Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3255 Init, nullptr, VK_PRValue,
3257 StructuredList->updateInit(Context, i, Init);
3258 }
3259 }
3260 }
3261
3262 // Make sure that our non-designated initializer list has space
3263 // for a subobject corresponding to this array element.
3264 if (StructuredList &&
3265 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3266 StructuredList->resizeInits(SemaRef.Context,
3267 DesignatedEndIndex.getZExtValue() + 1);
3268
3269 // Repeatedly perform subobject initializations in the range
3270 // [DesignatedStartIndex, DesignatedEndIndex].
3271
3272 // Move to the next designator
3273 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3274 unsigned OldIndex = Index;
3275
3276 InitializedEntity ElementEntity =
3278
3279 while (DesignatedStartIndex <= DesignatedEndIndex) {
3280 // Recurse to check later designated subobjects.
3281 QualType ElementType = AT->getElementType();
3282 Index = OldIndex;
3283
3284 ElementEntity.setElementIndex(ElementIndex);
3285 if (CheckDesignatedInitializer(
3286 ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3287 nullptr, Index, StructuredList, ElementIndex,
3288 FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3289 false))
3290 return true;
3291
3292 // Move to the next index in the array that we'll be initializing.
3293 ++DesignatedStartIndex;
3294 ElementIndex = DesignatedStartIndex.getZExtValue();
3295 }
3296
3297 // If this the first designator, our caller will continue checking
3298 // the rest of this array subobject.
3299 if (IsFirstDesignator) {
3300 if (NextElementIndex)
3301 *NextElementIndex = DesignatedStartIndex;
3302 StructuredIndex = ElementIndex;
3303 return false;
3304 }
3305
3306 if (!FinishSubobjectInit)
3307 return false;
3308
3309 // Check the remaining elements within this array subobject.
3310 bool prevHadError = hadError;
3311 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3312 /*SubobjectIsDesignatorContext=*/false, Index,
3313 StructuredList, ElementIndex);
3314 return hadError && !prevHadError;
3315}
3316
3317// Get the structured initializer list for a subobject of type
3318// @p CurrentObjectType.
3320InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3321 QualType CurrentObjectType,
3322 InitListExpr *StructuredList,
3323 unsigned StructuredIndex,
3324 SourceRange InitRange,
3325 bool IsFullyOverwritten) {
3326 if (!StructuredList)
3327 return nullptr;
3328
3329 Expr *ExistingInit = nullptr;
3330 if (StructuredIndex < StructuredList->getNumInits())
3331 ExistingInit = StructuredList->getInit(StructuredIndex);
3332
3333 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3334 // There might have already been initializers for subobjects of the current
3335 // object, but a subsequent initializer list will overwrite the entirety
3336 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3337 //
3338 // struct P { char x[6]; };
3339 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3340 //
3341 // The first designated initializer is ignored, and l.x is just "f".
3342 if (!IsFullyOverwritten)
3343 return Result;
3344
3345 if (ExistingInit) {
3346 // We are creating an initializer list that initializes the
3347 // subobjects of the current object, but there was already an
3348 // initialization that completely initialized the current
3349 // subobject:
3350 //
3351 // struct X { int a, b; };
3352 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3353 //
3354 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3355 // designated initializer overwrites the [0].b initializer
3356 // from the prior initialization.
3357 //
3358 // When the existing initializer is an expression rather than an
3359 // initializer list, we cannot decompose and update it in this way.
3360 // For example:
3361 //
3362 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3363 //
3364 // This case is handled by CheckDesignatedInitializer.
3365 diagnoseInitOverride(ExistingInit, InitRange);
3366 }
3367
3368 unsigned ExpectedNumInits = 0;
3369 if (Index < IList->getNumInits()) {
3370 if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3371 ExpectedNumInits = Init->getNumInits();
3372 else
3373 ExpectedNumInits = IList->getNumInits() - Index;
3374 }
3375
3376 InitListExpr *Result =
3377 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3378
3379 // Link this new initializer list into the structured initializer
3380 // lists.
3381 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3382 return Result;
3383}
3384
3386InitListChecker::createInitListExpr(QualType CurrentObjectType,
3387 SourceRange InitRange,
3388 unsigned ExpectedNumInits) {
3389 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3390 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3391
3392 QualType ResultType = CurrentObjectType;
3393 if (!ResultType->isArrayType())
3394 ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3395 Result->setType(ResultType);
3396
3397 // Pre-allocate storage for the structured initializer list.
3398 unsigned NumElements = 0;
3399
3400 if (const ArrayType *AType
3401 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3402 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3403 NumElements = CAType->getZExtSize();
3404 // Simple heuristic so that we don't allocate a very large
3405 // initializer with many empty entries at the end.
3406 if (NumElements > ExpectedNumInits)
3407 NumElements = 0;
3408 }
3409 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3410 NumElements = VType->getNumElements();
3411 } else if (CurrentObjectType->isRecordType()) {
3412 NumElements = numStructUnionElements(CurrentObjectType);
3413 } else if (CurrentObjectType->isDependentType()) {
3414 NumElements = 1;
3415 }
3416
3417 Result->reserveInits(SemaRef.Context, NumElements);
3418
3419 return Result;
3420}
3421
3422/// Update the initializer at index @p StructuredIndex within the
3423/// structured initializer list to the value @p expr.
3424void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3425 unsigned &StructuredIndex,
3426 Expr *expr) {
3427 // No structured initializer list to update
3428 if (!StructuredList)
3429 return;
3430
3431 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3432 StructuredIndex, expr)) {
3433 // This initializer overwrites a previous initializer.
3434 // No need to diagnose when `expr` is nullptr because a more relevant
3435 // diagnostic has already been issued and this diagnostic is potentially
3436 // noise.
3437 if (expr)
3438 diagnoseInitOverride(PrevInit, expr->getSourceRange());
3439 }
3440
3441 ++StructuredIndex;
3442}
3443
3445 const InitializedEntity &Entity, InitListExpr *From) {
3446 QualType Type = Entity.getType();
3447 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3448 /*TreatUnavailableAsInvalid=*/false,
3449 /*InOverloadResolution=*/true);
3450 return !Check.HadError();
3451}
3452
3453/// Check that the given Index expression is a valid array designator
3454/// value. This is essentially just a wrapper around
3455/// VerifyIntegerConstantExpression that also checks for negative values
3456/// and produces a reasonable diagnostic if there is a
3457/// failure. Returns the index expression, possibly with an implicit cast
3458/// added, on success. If everything went okay, Value will receive the
3459/// value of the constant expression.
3460static ExprResult
3461CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3462 SourceLocation Loc = Index->getBeginLoc();
3463
3464 // Make sure this is an integer constant expression.
3467 if (Result.isInvalid())
3468 return Result;
3469
3470 if (Value.isSigned() && Value.isNegative())
3471 return S.Diag(Loc, diag::err_array_designator_negative)
3472 << toString(Value, 10) << Index->getSourceRange();
3473
3474 Value.setIsUnsigned(true);
3475 return Result;
3476}
3477
3479 SourceLocation EqualOrColonLoc,
3480 bool GNUSyntax,
3481 ExprResult Init) {
3482 typedef DesignatedInitExpr::Designator ASTDesignator;
3483
3484 bool Invalid = false;
3486 SmallVector<Expr *, 32> InitExpressions;
3487
3488 // Build designators and check array designator expressions.
3489 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3490 const Designator &D = Desig.getDesignator(Idx);
3491
3492 if (D.isFieldDesignator()) {
3493 Designators.push_back(ASTDesignator::CreateFieldDesignator(
3494 D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3495 } else if (D.isArrayDesignator()) {
3496 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3497 llvm::APSInt IndexValue;
3498 if (!Index->isTypeDependent() && !Index->isValueDependent())
3499 Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3500 if (!Index)
3501 Invalid = true;
3502 else {
3503 Designators.push_back(ASTDesignator::CreateArrayDesignator(
3504 InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3505 InitExpressions.push_back(Index);
3506 }
3507 } else if (D.isArrayRangeDesignator()) {
3508 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3509 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3510 llvm::APSInt StartValue;
3511 llvm::APSInt EndValue;
3512 bool StartDependent = StartIndex->isTypeDependent() ||
3513 StartIndex->isValueDependent();
3514 bool EndDependent = EndIndex->isTypeDependent() ||
3515 EndIndex->isValueDependent();
3516 if (!StartDependent)
3517 StartIndex =
3518 CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3519 if (!EndDependent)
3520 EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3521
3522 if (!StartIndex || !EndIndex)
3523 Invalid = true;
3524 else {
3525 // Make sure we're comparing values with the same bit width.
3526 if (StartDependent || EndDependent) {
3527 // Nothing to compute.
3528 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3529 EndValue = EndValue.extend(StartValue.getBitWidth());
3530 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3531 StartValue = StartValue.extend(EndValue.getBitWidth());
3532
3533 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3534 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3535 << toString(StartValue, 10) << toString(EndValue, 10)
3536 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3537 Invalid = true;
3538 } else {
3539 Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3540 InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3541 D.getRBracketLoc()));
3542 InitExpressions.push_back(StartIndex);
3543 InitExpressions.push_back(EndIndex);
3544 }
3545 }
3546 }
3547 }
3548
3549 if (Invalid || Init.isInvalid())
3550 return ExprError();
3551
3552 return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3553 EqualOrColonLoc, GNUSyntax,
3554 Init.getAs<Expr>());
3555}
3556
3557//===----------------------------------------------------------------------===//
3558// Initialization entity
3559//===----------------------------------------------------------------------===//
3560
3561InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3563 : Parent(&Parent), Index(Index)
3564{
3565 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3566 Kind = EK_ArrayElement;
3567 Type = AT->getElementType();
3568 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3569 Kind = EK_VectorElement;
3570 Type = VT->getElementType();
3571 } else {
3572 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3573 assert(CT && "Unexpected type");
3574 Kind = EK_ComplexElement;
3575 Type = CT->getElementType();
3576 }
3577}
3578
3581 const CXXBaseSpecifier *Base,
3582 bool IsInheritedVirtualBase,
3583 const InitializedEntity *Parent) {
3585 Result.Kind = EK_Base;
3586 Result.Parent = Parent;
3587 Result.Base = {Base, IsInheritedVirtualBase};
3588 Result.Type = Base->getType();
3589 return Result;
3590}
3591
3593 switch (getKind()) {
3594 case EK_Parameter:
3596 ParmVarDecl *D = Parameter.getPointer();
3597 return (D ? D->getDeclName() : DeclarationName());
3598 }
3599
3600 case EK_Variable:
3601 case EK_Member:
3603 case EK_Binding:
3605 return Variable.VariableOrMember->getDeclName();
3606
3607 case EK_LambdaCapture:
3608 return DeclarationName(Capture.VarID);
3609
3610 case EK_Result:
3611 case EK_StmtExprResult:
3612 case EK_Exception:
3613 case EK_New:
3614 case EK_Temporary:
3615 case EK_Base:
3616 case EK_Delegating:
3617 case EK_ArrayElement:
3618 case EK_VectorElement:
3619 case EK_ComplexElement:
3620 case EK_BlockElement:
3623 case EK_RelatedResult:
3624 return DeclarationName();
3625 }
3626
3627 llvm_unreachable("Invalid EntityKind!");
3628}
3629
3631 switch (getKind()) {
3632 case EK_Variable:
3633 case EK_Member:
3635 case EK_Binding:
3637 return Variable.VariableOrMember;
3638
3639 case EK_Parameter:
3641 return Parameter.getPointer();
3642
3643 case EK_Result:
3644 case EK_StmtExprResult:
3645 case EK_Exception:
3646 case EK_New:
3647 case EK_Temporary:
3648 case EK_Base:
3649 case EK_Delegating:
3650 case EK_ArrayElement:
3651 case EK_VectorElement:
3652 case EK_ComplexElement:
3653 case EK_BlockElement:
3655 case EK_LambdaCapture:
3657 case EK_RelatedResult:
3658 return nullptr;
3659 }
3660
3661 llvm_unreachable("Invalid EntityKind!");
3662}
3663
3665 switch (getKind()) {
3666 case EK_Result:
3667 case EK_Exception:
3668 return LocAndNRVO.NRVO;
3669
3670 case EK_StmtExprResult:
3671 case EK_Variable:
3672 case EK_Parameter:
3675 case EK_Member:
3677 case EK_Binding:
3678 case EK_New:
3679 case EK_Temporary:
3681 case EK_Base:
3682 case EK_Delegating:
3683 case EK_ArrayElement:
3684 case EK_VectorElement:
3685 case EK_ComplexElement:
3686 case EK_BlockElement:
3688 case EK_LambdaCapture:
3689 case EK_RelatedResult:
3690 break;
3691 }
3692
3693 return false;
3694}
3695
3696unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3697 assert(getParent() != this);
3698 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3699 for (unsigned I = 0; I != Depth; ++I)
3700 OS << "`-";
3701
3702 switch (getKind()) {
3703 case EK_Variable: OS << "Variable"; break;
3704 case EK_Parameter: OS << "Parameter"; break;
3705 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3706 break;
3707 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3708 case EK_Result: OS << "Result"; break;
3709 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3710 case EK_Exception: OS << "Exception"; break;
3711 case EK_Member:
3713 OS << "Member";
3714 break;
3715 case EK_Binding: OS << "Binding"; break;
3716 case EK_New: OS << "New"; break;
3717 case EK_Temporary: OS << "Temporary"; break;
3718 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3719 case EK_RelatedResult: OS << "RelatedResult"; break;
3720 case EK_Base: OS << "Base"; break;
3721 case EK_Delegating: OS << "Delegating"; break;
3722 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3723 case EK_VectorElement: OS << "VectorElement " << Index; break;
3724 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3725 case EK_BlockElement: OS << "Block"; break;
3727 OS << "Block (lambda)";
3728 break;
3729 case EK_LambdaCapture:
3730 OS << "LambdaCapture ";
3731 OS << DeclarationName(Capture.VarID);
3732 break;
3733 }
3734
3735 if (auto *D = getDecl()) {
3736 OS << " ";
3737 D->printQualifiedName(OS);
3738 }
3739
3740 OS << " '" << getType() << "'\n";
3741
3742 return Depth + 1;
3743}
3744
3745LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3746 dumpImpl(llvm::errs());
3747}
3748
3749//===----------------------------------------------------------------------===//
3750// Initialization sequence
3751//===----------------------------------------------------------------------===//
3752
3754 switch (Kind) {
3759 case SK_BindReference:
3761 case SK_FinalCopy:
3763 case SK_UserConversion:
3770 case SK_UnwrapInitList:
3771 case SK_RewrapInitList:
3775 case SK_CAssignment:
3776 case SK_StringInit:
3778 case SK_ArrayLoopIndex:
3779 case SK_ArrayLoopInit:
3780 case SK_ArrayInit:
3781 case SK_GNUArrayInit:
3788 case SK_OCLSamplerInit:
3791 break;
3792
3795 delete ICS;
3796 }
3797}
3798
3800 // There can be some lvalue adjustments after the SK_BindReference step.
3801 for (const Step &S : llvm::reverse(Steps)) {
3802 if (S.Kind == SK_BindReference)
3803 return true;
3804 if (S.Kind == SK_BindReferenceToTemporary)
3805 return false;
3806 }
3807 return false;
3808}
3809
3811 if (!Failed())
3812 return false;
3813
3814 switch (getFailureKind()) {
3825 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3842 case FK_Incomplete:
3847 case FK_PlaceholderType:
3852 return false;
3853
3858 return FailedOverloadResult == OR_Ambiguous;
3859 }
3860
3861 llvm_unreachable("Invalid EntityKind!");
3862}
3863
3865 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3866}
3867
3868void
3869InitializationSequence
3870::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3872 bool HadMultipleCandidates) {
3873 Step S;
3875 S.Type = Function->getType();
3876 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3877 S.Function.Function = Function;
3878 S.Function.FoundDecl = Found;
3879 Steps.push_back(S);
3880}
3881
3883 ExprValueKind VK) {
3884 Step S;
3885 switch (VK) {
3886 case VK_PRValue:
3888 break;
3889 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3890 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3891 }
3892 S.Type = BaseType;
3893 Steps.push_back(S);
3894}
3895
3897 bool BindingTemporary) {
3898 Step S;
3899 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3900 S.Type = T;
3901 Steps.push_back(S);
3902}
3903
3905 Step S;
3906 S.Kind = SK_FinalCopy;
3907 S.Type = T;
3908 Steps.push_back(S);
3909}
3910
3912 Step S;
3914 S.Type = T;
3915 Steps.push_back(S);
3916}
3917
3918void
3920 DeclAccessPair FoundDecl,
3921 QualType T,
3922 bool HadMultipleCandidates) {
3923 Step S;
3924 S.Kind = SK_UserConversion;
3925 S.Type = T;
3926 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3927 S.Function.Function = Function;
3928 S.Function.FoundDecl = FoundDecl;
3929 Steps.push_back(S);
3930}
3931
3933 ExprValueKind VK) {
3934 Step S;
3935 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3936 switch (VK) {
3937 case VK_PRValue:
3939 break;
3940 case VK_XValue:
3942 break;
3943 case VK_LValue:
3945 break;
3946 }
3947 S.Type = Ty;
3948 Steps.push_back(S);
3949}
3950
3952 Step S;
3954 S.Type = Ty;
3955 Steps.push_back(S);
3956}
3957
3959 Step S;
3960 S.Kind = SK_AtomicConversion;
3961 S.Type = Ty;
3962 Steps.push_back(S);
3963}
3964
3967 bool TopLevelOfInitList) {
3968 Step S;
3969 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3971 S.Type = T;
3972 S.ICS = new ImplicitConversionSequence(ICS);
3973 Steps.push_back(S);
3974}
3975
3977 Step S;
3978 S.Kind = SK_ListInitialization;
3979 S.Type = T;
3980 Steps.push_back(S);
3981}
3982
3984 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3985 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3986 Step S;
3987 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3990 S.Type = T;
3991 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3992 S.Function.Function = Constructor;
3993 S.Function.FoundDecl = FoundDecl;
3994 Steps.push_back(S);
3995}
3996
3998 Step S;
3999 S.Kind = SK_ZeroInitialization;
4000 S.Type = T;
4001 Steps.push_back(S);
4002}
4003
4005 Step S;
4006 S.Kind = SK_CAssignment;
4007 S.Type = T;
4008 Steps.push_back(S);
4009}
4010
4012 Step S;
4013 S.Kind = SK_StringInit;
4014 S.Type = T;
4015 Steps.push_back(S);
4016}
4017
4019 Step S;
4020 S.Kind = SK_ObjCObjectConversion;
4021 S.Type = T;
4022 Steps.push_back(S);
4023}
4024
4026 Step S;
4027 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4028 S.Type = T;
4029 Steps.push_back(S);
4030}
4031
4033 Step S;
4034 S.Kind = SK_ArrayLoopIndex;
4035 S.Type = EltT;
4036 Steps.insert(Steps.begin(), S);
4037
4038 S.Kind = SK_ArrayLoopInit;
4039 S.Type = T;
4040 Steps.push_back(S);
4041}
4042
4044 Step S;
4046 S.Type = T;
4047 Steps.push_back(S);
4048}
4049
4051 bool shouldCopy) {
4052 Step s;
4053 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4055 s.Type = type;
4056 Steps.push_back(s);
4057}
4058
4060 Step S;
4061 S.Kind = SK_ProduceObjCObject;
4062 S.Type = T;
4063 Steps.push_back(S);
4064}
4065
4067 Step S;
4068 S.Kind = SK_StdInitializerList;
4069 S.Type = T;
4070 Steps.push_back(S);
4071}
4072
4074 Step S;
4075 S.Kind = SK_OCLSamplerInit;
4076 S.Type = T;
4077 Steps.push_back(S);
4078}
4079
4081 Step S;
4082 S.Kind = SK_OCLZeroOpaqueType;
4083 S.Type = T;
4084 Steps.push_back(S);
4085}
4086
4088 Step S;
4089 S.Kind = SK_ParenthesizedListInit;
4090 S.Type = T;
4091 Steps.push_back(S);
4092}
4093
4095 InitListExpr *Syntactic) {
4096 assert(Syntactic->getNumInits() == 1 &&
4097 "Can only rewrap trivial init lists.");
4098 Step S;
4099 S.Kind = SK_UnwrapInitList;
4100 S.Type = Syntactic->getInit(0)->getType();
4101 Steps.insert(Steps.begin(), S);
4102
4103 S.Kind = SK_RewrapInitList;
4104 S.Type = T;
4105 S.WrappingSyntacticList = Syntactic;
4106 Steps.push_back(S);
4107}
4108
4112 this->Failure = Failure;
4113 this->FailedOverloadResult = Result;
4114}
4115
4116//===----------------------------------------------------------------------===//
4117// Attempt initialization
4118//===----------------------------------------------------------------------===//
4119
4120/// Tries to add a zero initializer. Returns true if that worked.
4121static bool
4123 const InitializedEntity &Entity) {
4125 return false;
4126
4127 VarDecl *VD = cast<VarDecl>(Entity.getDecl());
4128 if (VD->getInit() || VD->getEndLoc().isMacroID())
4129 return false;
4130
4131 QualType VariableTy = VD->getType().getCanonicalType();
4133 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
4134 if (!Init.empty()) {
4135 Sequence.AddZeroInitializationStep(Entity.getType());
4137 return true;
4138 }
4139 return false;
4140}
4141
4143 InitializationSequence &Sequence,
4144 const InitializedEntity &Entity) {
4145 if (!S.getLangOpts().ObjCAutoRefCount) return;
4146
4147 /// When initializing a parameter, produce the value if it's marked
4148 /// __attribute__((ns_consumed)).
4149 if (Entity.isParameterKind()) {
4150 if (!Entity.isParameterConsumed())
4151 return;
4152
4153 assert(Entity.getType()->isObjCRetainableType() &&
4154 "consuming an object of unretainable type?");
4155 Sequence.AddProduceObjCObjectStep(Entity.getType());
4156
4157 /// When initializing a return value, if the return type is a
4158 /// retainable type, then returns need to immediately retain the
4159 /// object. If an autorelease is required, it will be done at the
4160 /// last instant.
4161 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4163 if (!Entity.getType()->isObjCRetainableType())
4164 return;
4165
4166 Sequence.AddProduceObjCObjectStep(Entity.getType());
4167 }
4168}
4169
4170static void TryListInitialization(Sema &S,
4171 const InitializedEntity &Entity,
4172 const InitializationKind &Kind,
4173 InitListExpr *InitList,
4174 InitializationSequence &Sequence,
4175 bool TreatUnavailableAsInvalid);
4176
4177/// When initializing from init list via constructor, handle
4178/// initialization of an object of type std::initializer_list<T>.
4179///
4180/// \return true if we have handled initialization of an object of type
4181/// std::initializer_list<T>, false otherwise.
4183 InitListExpr *List,
4184 QualType DestType,
4185 InitializationSequence &Sequence,
4186 bool TreatUnavailableAsInvalid) {
4187 QualType E;
4188 if (!S.isStdInitializerList(DestType, &E))
4189 return false;
4190
4191 if (!S.isCompleteType(List->getExprLoc(), E)) {
4192 Sequence.setIncompleteTypeFailure(E);
4193 return true;
4194 }
4195
4196 // Try initializing a temporary array from the init list.
4198 E.withConst(),
4199 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4200 List->getNumInits()),
4202 InitializedEntity HiddenArray =
4205 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4206 TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4207 TreatUnavailableAsInvalid);
4208 if (Sequence)
4209 Sequence.AddStdInitializerListConstructionStep(DestType);
4210 return true;
4211}
4212
4213/// Determine if the constructor has the signature of a copy or move
4214/// constructor for the type T of the class in which it was found. That is,
4215/// determine if its first parameter is of type T or reference to (possibly
4216/// cv-qualified) T.
4218 const ConstructorInfo &Info) {
4219 if (Info.Constructor->getNumParams() == 0)
4220 return false;
4221
4222 QualType ParmT =
4224 QualType ClassT =
4225 Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4226
4227 return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4228}
4229
4231 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4232 OverloadCandidateSet &CandidateSet, QualType DestType,
4234 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4235 bool IsListInit, bool RequireActualConstructor,
4236 bool SecondStepOfCopyInit = false) {
4238 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4239
4240 for (NamedDecl *D : Ctors) {
4241 auto Info = getConstructorInfo(D);
4242 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4243 continue;
4244
4245 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4246 continue;
4247
4248 // C++11 [over.best.ics]p4:
4249 // ... and the constructor or user-defined conversion function is a
4250 // candidate by
4251 // - 13.3.1.3, when the argument is the temporary in the second step
4252 // of a class copy-initialization, or
4253 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4254 // - the second phase of 13.3.1.7 when the initializer list has exactly
4255 // one element that is itself an initializer list, and the target is
4256 // the first parameter of a constructor of class X, and the conversion
4257 // is to X or reference to (possibly cv-qualified X),
4258 // user-defined conversion sequences are not considered.
4259 bool SuppressUserConversions =
4260 SecondStepOfCopyInit ||
4261 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4263
4264 if (Info.ConstructorTmpl)
4266 Info.ConstructorTmpl, Info.FoundDecl,
4267 /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4268 /*PartialOverloading=*/false, AllowExplicit);
4269 else {
4270 // C++ [over.match.copy]p1:
4271 // - When initializing a temporary to be bound to the first parameter
4272 // of a constructor [for type T] that takes a reference to possibly
4273 // cv-qualified T as its first argument, called with a single
4274 // argument in the context of direct-initialization, explicit
4275 // conversion functions are also considered.
4276 // FIXME: What if a constructor template instantiates to such a signature?
4277 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4278 Args.size() == 1 &&
4280 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4281 CandidateSet, SuppressUserConversions,
4282 /*PartialOverloading=*/false, AllowExplicit,
4283 AllowExplicitConv);
4284 }
4285 }
4286
4287 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4288 //
4289 // When initializing an object of class type T by constructor
4290 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4291 // from a single expression of class type U, conversion functions of
4292 // U that convert to the non-reference type cv T are candidates.
4293 // Explicit conversion functions are only candidates during
4294 // direct-initialization.
4295 //
4296 // Note: SecondStepOfCopyInit is only ever true in this case when
4297 // evaluating whether to produce a C++98 compatibility warning.
4298 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4299 !RequireActualConstructor && !SecondStepOfCopyInit) {
4300 Expr *Initializer = Args[0];
4301 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4302 if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4303 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4304 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4305 NamedDecl *D = *I;
4306 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4307 D = D->getUnderlyingDecl();
4308
4309 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4310 CXXConversionDecl *Conv;
4311 if (ConvTemplate)
4312 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4313 else
4314 Conv = cast<CXXConversionDecl>(D);
4315
4316 if (ConvTemplate)
4318 ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4319 CandidateSet, AllowExplicit, AllowExplicit,
4320 /*AllowResultConversion*/ false);
4321 else
4322 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4323 DestType, CandidateSet, AllowExplicit,
4324 AllowExplicit,
4325 /*AllowResultConversion*/ false);
4326 }
4327 }
4328 }
4329
4330 // Perform overload resolution and return the result.
4331 return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4332}
4333
4334/// Attempt initialization by constructor (C++ [dcl.init]), which
4335/// enumerates the constructors of the initialized entity and performs overload
4336/// resolution to select the best.
4337/// \param DestType The destination class type.
4338/// \param DestArrayType The destination type, which is either DestType or
4339/// a (possibly multidimensional) array of DestType.
4340/// \param IsListInit Is this list-initialization?
4341/// \param IsInitListCopy Is this non-list-initialization resulting from a
4342/// list-initialization from {x} where x is the same
4343/// aggregate type as the entity?
4345 const InitializedEntity &Entity,
4346 const InitializationKind &Kind,
4347 MultiExprArg Args, QualType DestType,
4348 QualType DestArrayType,
4349 InitializationSequence &Sequence,
4350 bool IsListInit = false,
4351 bool IsInitListCopy = false) {
4352 assert(((!IsListInit && !IsInitListCopy) ||
4353 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4354 "IsListInit/IsInitListCopy must come with a single initializer list "
4355 "argument.");
4356 InitListExpr *ILE =
4357 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4358 MultiExprArg UnwrappedArgs =
4359 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4360
4361 // The type we're constructing needs to be complete.
4362 if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4363 Sequence.setIncompleteTypeFailure(DestType);
4364 return;
4365 }
4366
4367 bool RequireActualConstructor =
4368 !(Entity.getKind() != InitializedEntity::EK_Base &&
4370 Entity.getKind() !=
4372
4373 bool CopyElisionPossible = false;
4374 auto ElideConstructor = [&] {
4375 // Convert qualifications if necessary.
4376 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4377 if (ILE)
4378 Sequence.RewrapReferenceInitList(DestType, ILE);
4379 };
4380
4381 // C++17 [dcl.init]p17:
4382 // - If the initializer expression is a prvalue and the cv-unqualified
4383 // version of the source type is the same class as the class of the
4384 // destination, the initializer expression is used to initialize the
4385 // destination object.
4386 // Per DR (no number yet), this does not apply when initializing a base
4387 // class or delegating to another constructor from a mem-initializer.
4388 // ObjC++: Lambda captured by the block in the lambda to block conversion
4389 // should avoid copy elision.
4390 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4391 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4392 S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4393 if (ILE && !DestType->isAggregateType()) {
4394 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4395 // Make this an elision if this won't call an initializer-list
4396 // constructor. (Always on an aggregate type or check constructors first.)
4397
4398 // This effectively makes our resolution as follows. The parts in angle
4399 // brackets are additions.
4400 // C++17 [over.match.list]p(1.2):
4401 // - If no viable initializer-list constructor is found <and the
4402 // initializer list does not consist of exactly a single element with
4403 // the same cv-unqualified class type as T>, [...]
4404 // C++17 [dcl.init.list]p(3.6):
4405 // - Otherwise, if T is a class type, constructors are considered. The
4406 // applicable constructors are enumerated and the best one is chosen
4407 // through overload resolution. <If no constructor is found and the
4408 // initializer list consists of exactly a single element with the same
4409 // cv-unqualified class type as T, the object is initialized from that
4410 // element (by copy-initialization for copy-list-initialization, or by
4411 // direct-initialization for direct-list-initialization). Otherwise, >
4412 // if a narrowing conversion [...]
4413 assert(!IsInitListCopy &&
4414 "IsInitListCopy only possible with aggregate types");
4415 CopyElisionPossible = true;
4416 } else {
4417 ElideConstructor();
4418 return;
4419 }
4420 }
4421
4422 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4423 assert(DestRecordType && "Constructor initialization requires record type");
4424 CXXRecordDecl *DestRecordDecl
4425 = cast<CXXRecordDecl>(DestRecordType->getDecl());
4426
4427 // Build the candidate set directly in the initialization sequence
4428 // structure, so that it will persist if we fail.
4429 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4430
4431 // Determine whether we are allowed to call explicit constructors or
4432 // explicit conversion operators.
4433 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4434 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4435
4436 // - Otherwise, if T is a class type, constructors are considered. The
4437 // applicable constructors are enumerated, and the best one is chosen
4438 // through overload resolution.
4439 DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4440
4443 bool AsInitializerList = false;
4444
4445 // C++11 [over.match.list]p1, per DR1467:
4446 // When objects of non-aggregate type T are list-initialized, such that
4447 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4448 // according to the rules in this section, overload resolution selects
4449 // the constructor in two phases:
4450 //
4451 // - Initially, the candidate functions are the initializer-list
4452 // constructors of the class T and the argument list consists of the
4453 // initializer list as a single argument.
4454 if (IsListInit) {
4455 AsInitializerList = true;
4456
4457 // If the initializer list has no elements and T has a default constructor,
4458 // the first phase is omitted.
4459 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4461 S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4462 CopyInitialization, AllowExplicit,
4463 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4464
4465 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4466 // No initializer list candidate
4467 ElideConstructor();
4468 return;
4469 }
4470 }
4471
4472 // C++11 [over.match.list]p1:
4473 // - If no viable initializer-list constructor is found, overload resolution
4474 // is performed again, where the candidate functions are all the
4475 // constructors of the class T and the argument list consists of the
4476 // elements of the initializer list.
4478 AsInitializerList = false;
4480 S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4481 Best, CopyInitialization, AllowExplicit,
4482 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4483 }
4484 if (Result) {
4485 Sequence.SetOverloadFailure(
4488 Result);
4489
4490 if (Result != OR_Deleted)
4491 return;
4492 }
4493
4494 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4495
4496 // In C++17, ResolveConstructorOverload can select a conversion function
4497 // instead of a constructor.
4498 if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4499 // Add the user-defined conversion step that calls the conversion function.
4500 QualType ConvType = CD->getConversionType();
4501 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4502 "should not have selected this conversion function");
4503 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4504 HadMultipleCandidates);
4505 if (!S.Context.hasSameType(ConvType, DestType))
4506 Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4507 if (IsListInit)
4508 Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4509 return;
4510 }
4511
4512 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4513 if (Result != OR_Deleted) {
4514 // C++11 [dcl.init]p6:
4515 // If a program calls for the default initialization of an object
4516 // of a const-qualified type T, T shall be a class type with a
4517 // user-provided default constructor.
4518 // C++ core issue 253 proposal:
4519 // If the implicit default constructor initializes all subobjects, no
4520 // initializer should be required.
4521 // The 253 proposal is for example needed to process libstdc++ headers
4522 // in 5.x.
4523 if (Kind.getKind() == InitializationKind::IK_Default &&
4524 Entity.getType().isConstQualified()) {
4525 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4526 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4528 return;
4529 }
4530 }
4531
4532 // C++11 [over.match.list]p1:
4533 // In copy-list-initialization, if an explicit constructor is chosen, the
4534 // initializer is ill-formed.
4535 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4537 return;
4538 }
4539 }
4540
4541 // [class.copy.elision]p3:
4542 // In some copy-initialization contexts, a two-stage overload resolution
4543 // is performed.
4544 // If the first overload resolution selects a deleted function, we also
4545 // need the initialization sequence to decide whether to perform the second
4546 // overload resolution.
4547 // For deleted functions in other contexts, there is no need to get the
4548 // initialization sequence.
4549 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4550 return;
4551
4552 // Add the constructor initialization step. Any cv-qualification conversion is
4553 // subsumed by the initialization.
4555 Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4556 IsListInit | IsInitListCopy, AsInitializerList);
4557}
4558
4559static bool
4562 QualType &SourceType,
4563 QualType &UnqualifiedSourceType,
4564 QualType UnqualifiedTargetType,
4565 InitializationSequence &Sequence) {
4566 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4567 S.Context.OverloadTy) {
4569 bool HadMultipleCandidates = false;
4570 if (FunctionDecl *Fn
4572 UnqualifiedTargetType,
4573 false, Found,
4574 &HadMultipleCandidates)) {
4576 HadMultipleCandidates);
4577 SourceType = Fn->getType();
4578 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4579 } else if (!UnqualifiedTargetType->isRecordType()) {
4581 return true;
4582 }
4583 }
4584 return false;
4585}
4586
4588 const InitializedEntity &Entity,
4589 const InitializationKind &Kind,
4591 QualType cv1T1, QualType T1,
4592 Qualifiers T1Quals,
4593 QualType cv2T2, QualType T2,
4594 Qualifiers T2Quals,
4595 InitializationSequence &Sequence,
4596 bool TopLevelOfInitList);
4597
4598static void TryValueInitialization(Sema &S,
4599 const InitializedEntity &Entity,
4600 const InitializationKind &Kind,
4601 InitializationSequence &Sequence,
4602 InitListExpr *InitList = nullptr);
4603
4604/// Attempt list initialization of a reference.
4606 const InitializedEntity &Entity,
4607 const InitializationKind &Kind,
4608 InitListExpr *InitList,
4609 InitializationSequence &Sequence,
4610 bool TreatUnavailableAsInvalid) {
4611 // First, catch C++03 where this isn't possible.
4612 if (!S.getLangOpts().CPlusPlus11) {
4614 return;
4615 }
4616 // Can't reference initialize a compound literal.
4619 return;
4620 }
4621
4622 QualType DestType = Entity.getType();
4623 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4624 Qualifiers T1Quals;
4625 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4626
4627 // Reference initialization via an initializer list works thus:
4628 // If the initializer list consists of a single element that is
4629 // reference-related to the referenced type, bind directly to that element
4630 // (possibly creating temporaries).
4631 // Otherwise, initialize a temporary with the initializer list and
4632 // bind to that.
4633 if (InitList->getNumInits() == 1) {
4634 Expr *Initializer = InitList->getInit(0);
4636 Qualifiers T2Quals;
4637 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4638
4639 // If this fails, creating a temporary wouldn't work either.
4641 T1, Sequence))
4642 return;
4643
4644 SourceLocation DeclLoc = Initializer->getBeginLoc();
4645 Sema::ReferenceCompareResult RefRelationship
4646 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4647 if (RefRelationship >= Sema::Ref_Related) {
4648 // Try to bind the reference here.
4649 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4650 T1Quals, cv2T2, T2, T2Quals, Sequence,
4651 /*TopLevelOfInitList=*/true);
4652 if (Sequence)
4653 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4654 return;
4655 }
4656
4657 // Update the initializer if we've resolved an overloaded function.
4658 if (Sequence.step_begin() != Sequence.step_end())
4659 Sequence.RewrapReferenceInitList(cv1T1, InitList);
4660 }
4661 // Perform address space compatibility check.
4662 QualType cv1T1IgnoreAS = cv1T1;
4663 if (T1Quals.hasAddressSpace()) {
4664 Qualifiers T2Quals;
4665 (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4666 if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4667 Sequence.SetFailed(
4669 return;
4670 }
4671 // Ignore address space of reference type at this point and perform address
4672 // space conversion after the reference binding step.
4673 cv1T1IgnoreAS =
4675 }
4676 // Not reference-related. Create a temporary and bind to that.
4677 InitializedEntity TempEntity =
4679
4680 TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4681 TreatUnavailableAsInvalid);
4682 if (Sequence) {
4683 if (DestType->isRValueReferenceType() ||
4684 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4685 if (S.getLangOpts().CPlusPlus20 &&
4686 isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4687 DestType->isRValueReferenceType()) {
4688 // C++20 [dcl.init.list]p3.10:
4689 // List-initialization of an object or reference of type T is defined as
4690 // follows:
4691 // ..., unless T is “reference to array of unknown bound of U”, in which
4692 // case the type of the prvalue is the type of x in the declaration U
4693 // x[] H, where H is the initializer list.
4695 }
4696 Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4697 /*BindingTemporary=*/true);
4698 if (T1Quals.hasAddressSpace())
4700 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4701 } else
4702 Sequence.SetFailed(
4704 }
4705}
4706
4707/// Attempt list initialization (C++0x [dcl.init.list])
4709 const InitializedEntity &Entity,
4710 const InitializationKind &Kind,
4711 InitListExpr *InitList,
4712 InitializationSequence &Sequence,
4713 bool TreatUnavailableAsInvalid) {
4714 QualType DestType = Entity.getType();
4715
4716 // C++ doesn't allow scalar initialization with more than one argument.
4717 // But C99 complex numbers are scalars and it makes sense there.
4718 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4719 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4721 return;
4722 }
4723 if (DestType->isReferenceType()) {
4724 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4725 TreatUnavailableAsInvalid);
4726 return;
4727 }
4728
4729 if (DestType->isRecordType() &&
4730 !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4731 Sequence.setIncompleteTypeFailure(DestType);
4732 return;
4733 }
4734
4735 // C++20 [dcl.init.list]p3:
4736 // - If the braced-init-list contains a designated-initializer-list, T shall
4737 // be an aggregate class. [...] Aggregate initialization is performed.
4738 //
4739 // We allow arrays here too in order to support array designators.
4740 //
4741 // FIXME: This check should precede the handling of reference initialization.
4742 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4743 // as a tentative DR resolution.
4744 bool IsDesignatedInit = InitList->hasDesignatedInit();
4745 if (!DestType->isAggregateType() && IsDesignatedInit) {
4746 Sequence.SetFailed(
4748 return;
4749 }
4750
4751 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4752 // - If T is an aggregate class and the initializer list has a single element
4753 // of type cv U, where U is T or a class derived from T, the object is
4754 // initialized from that element (by copy-initialization for
4755 // copy-list-initialization, or by direct-initialization for
4756 // direct-list-initialization).
4757 // - Otherwise, if T is a character array and the initializer list has a
4758 // single element that is an appropriately-typed string literal
4759 // (8.5.2 [dcl.init.string]), initialization is performed as described
4760 // in that section.
4761 // - Otherwise, if T is an aggregate, [...] (continue below).
4762 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4763 !IsDesignatedInit) {
4764 if (DestType->isRecordType() && DestType->isAggregateType()) {
4765 QualType InitType = InitList->getInit(0)->getType();
4766 if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4767 S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4768 Expr *InitListAsExpr = InitList;
4769 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4770 DestType, Sequence,
4771 /*InitListSyntax*/false,
4772 /*IsInitListCopy*/true);
4773 return;
4774 }
4775 }
4776 if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4777 Expr *SubInit[1] = {InitList->getInit(0)};
4778 if (!isa<VariableArrayType>(DestAT) &&
4779 IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4780 InitializationKind SubKind =
4781 Kind.getKind() == InitializationKind::IK_DirectList
4782 ? InitializationKind::CreateDirect(Kind.getLocation(),
4783 InitList->getLBraceLoc(),
4784 InitList->getRBraceLoc())
4785 : Kind;
4786 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4787 /*TopLevelOfInitList*/ true,
4788 TreatUnavailableAsInvalid);
4789
4790 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4791 // the element is not an appropriately-typed string literal, in which
4792 // case we should proceed as in C++11 (below).
4793 if (Sequence) {
4794 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4795 return;
4796 }
4797 }
4798 }
4799 }
4800
4801 // C++11 [dcl.init.list]p3:
4802 // - If T is an aggregate, aggregate initialization is performed.
4803 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4804 (S.getLangOpts().CPlusPlus11 &&
4805 S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4806 if (S.getLangOpts().CPlusPlus11) {
4807 // - Otherwise, if the initializer list has no elements and T is a
4808 // class type with a default constructor, the object is
4809 // value-initialized.
4810 if (InitList->getNumInits() == 0) {
4811 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4812 if (S.LookupDefaultConstructor(RD)) {
4813 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4814 return;
4815 }
4816 }
4817
4818 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4819 // an initializer_list object constructed [...]
4820 if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4821 TreatUnavailableAsInvalid))
4822 return;
4823
4824 // - Otherwise, if T is a class type, constructors are considered.
4825 Expr *InitListAsExpr = InitList;
4826 TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4827 DestType, Sequence, /*InitListSyntax*/true);
4828 } else
4830 return;
4831 }
4832
4833 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4834 InitList->getNumInits() == 1) {
4835 Expr *E = InitList->getInit(0);
4836
4837 // - Otherwise, if T is an enumeration with a fixed underlying type,
4838 // the initializer-list has a single element v, and the initialization
4839 // is direct-list-initialization, the object is initialized with the
4840 // value T(v); if a narrowing conversion is required to convert v to
4841 // the underlying type of T, the program is ill-formed.
4842 auto *ET = DestType->getAs<EnumType>();
4843 if (S.getLangOpts().CPlusPlus17 &&
4844 Kind.getKind() == InitializationKind::IK_DirectList &&
4845 ET && ET->getDecl()->isFixed() &&
4846 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4848 E->getType()->isFloatingType())) {
4849 // There are two ways that T(v) can work when T is an enumeration type.
4850 // If there is either an implicit conversion sequence from v to T or
4851 // a conversion function that can convert from v to T, then we use that.
4852 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4853 // type, it is converted to the enumeration type via its underlying type.
4854 // There is no overlap possible between these two cases (except when the
4855 // source value is already of the destination type), and the first
4856 // case is handled by the general case for single-element lists below.
4858 ICS.setStandard();
4860 if (!E->isPRValue())
4862 // If E is of a floating-point type, then the conversion is ill-formed
4863 // due to narrowing, but go through the motions in order to produce the
4864 // right diagnostic.
4868 ICS.Standard.setFromType(E->getType());
4869 ICS.Standard.setToType(0, E->getType());
4870 ICS.Standard.setToType(1, DestType);
4871 ICS.Standard.setToType(2, DestType);
4872 Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4873 /*TopLevelOfInitList*/true);
4874 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4875 return;
4876 }
4877
4878 // - Otherwise, if the initializer list has a single element of type E
4879 // [...references are handled above...], the object or reference is
4880 // initialized from that element (by copy-initialization for
4881 // copy-list-initialization, or by direct-initialization for
4882 // direct-list-initialization); if a narrowing conversion is required
4883 // to convert the element to T, the program is ill-formed.
4884 //
4885 // Per core-24034, this is direct-initialization if we were performing
4886 // direct-list-initialization and copy-initialization otherwise.
4887 // We can't use InitListChecker for this, because it always performs
4888 // copy-initialization. This only matters if we might use an 'explicit'
4889 // conversion operator, or for the special case conversion of nullptr_t to
4890 // bool, so we only need to handle those cases.
4891 //
4892 // FIXME: Why not do this in all cases?
4893 Expr *Init = InitList->getInit(0);
4894 if (Init->getType()->isRecordType() ||
4895 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4896 InitializationKind SubKind =
4897 Kind.getKind() == InitializationKind::IK_DirectList
4898 ? InitializationKind::CreateDirect(Kind.getLocation(),
4899 InitList->getLBraceLoc(),
4900 InitList->getRBraceLoc())
4901 : Kind;
4902 Expr *SubInit[1] = { Init };
4903 Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4904 /*TopLevelOfInitList*/true,
4905 TreatUnavailableAsInvalid);
4906 if (Sequence)
4907 Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4908 return;
4909 }
4910 }
4911
4912 InitListChecker CheckInitList(S, Entity, InitList,
4913 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4914 if (CheckInitList.HadError()) {
4916 return;
4917 }
4918
4919 // Add the list initialization step with the built init list.
4920 Sequence.AddListInitializationStep(DestType);
4921}
4922
4923/// Try a reference initialization that involves calling a conversion
4924/// function.
4926 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4927 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4928 InitializationSequence &Sequence) {
4929 QualType DestType = Entity.getType();
4930 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4931 QualType T1 = cv1T1.getUnqualifiedType();
4932 QualType cv2T2 = Initializer->getType();
4933 QualType T2 = cv2T2.getUnqualifiedType();
4934
4935 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4936 "Must have incompatible references when binding via conversion");
4937
4938 // Build the candidate set directly in the initialization sequence
4939 // structure, so that it will persist if we fail.
4940 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4942
4943 // Determine whether we are allowed to call explicit conversion operators.
4944 // Note that none of [over.match.copy], [over.match.conv], nor
4945 // [over.match.ref] permit an explicit constructor to be chosen when
4946 // initializing a reference, not even for direct-initialization.
4947 bool AllowExplicitCtors = false;
4948 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4949
4950 const RecordType *T1RecordType = nullptr;
4951 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4952 S.isCompleteType(Kind.getLocation(), T1)) {
4953 // The type we're converting to is a class type. Enumerate its constructors
4954 // to see if there is a suitable conversion.
4955 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4956
4957 for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4958 auto Info = getConstructorInfo(D);
4959 if (!Info.Constructor)
4960 continue;
4961
4962 if (!Info.Constructor->isInvalidDecl() &&
4963 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4964 if (Info.ConstructorTmpl)
4966 Info.ConstructorTmpl, Info.FoundDecl,
4967 /*ExplicitArgs*/ nullptr,