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