1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for initializers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/IgnoreExpr.h"
20#include "clang/AST/TypeBase.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Specifiers.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Designator.h"
27#include "clang/Sema/EnterExpressionEvaluationContext.h"
28#include "clang/Sema/Initialization.h"
29#include "clang/Sema/Lookup.h"
30#include "clang/Sema/Ownership.h"
31#include "clang/Sema/SemaHLSL.h"
32#include "clang/Sema/SemaObjC.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/PointerIntPair.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/raw_ostream.h"
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// Sema Initialization Checking
46//===----------------------------------------------------------------------===//
47
48/// Check whether T is compatible with a wide character type (wchar_t,
49/// char16_t or char32_t).
50static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
51 if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: T))
52 return true;
53 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
54 return Context.typesAreCompatible(T1: Context.Char16Ty, T2: T) ||
55 Context.typesAreCompatible(T1: Context.Char32Ty, T2: T);
56 }
57 return false;
58}
59
60enum StringInitFailureKind {
61 SIF_None,
62 SIF_NarrowStringIntoWideChar,
63 SIF_WideStringIntoChar,
64 SIF_IncompatWideStringIntoWideChar,
65 SIF_UTF8StringIntoPlainChar,
66 SIF_PlainStringIntoUTF8Char,
67 SIF_Other
68};
69
70/// Check whether the array of type AT can be initialized by the Init
71/// expression by means of string initialization. Returns SIF_None if so,
72/// otherwise returns a StringInitFailureKind that describes why the
73/// initialization would not work.
74static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
75 ASTContext &Context) {
76 if (!isa<ConstantArrayType>(Val: AT) && !isa<IncompleteArrayType>(Val: AT))
77 return SIF_Other;
78
79 // See if this is a string literal or @encode.
80 Init = Init->IgnoreParens();
81
82 // Handle @encode, which is a narrow string.
83 if (isa<ObjCEncodeExpr>(Val: Init) && AT->getElementType()->isCharType())
84 return SIF_None;
85
86 // Otherwise we can only handle string literals.
87 StringLiteral *SL = dyn_cast<StringLiteral>(Val: Init);
88 if (!SL)
89 return SIF_Other;
90
91 const QualType ElemTy =
92 Context.getCanonicalType(T: AT->getElementType()).getUnqualifiedType();
93
94 auto IsCharOrUnsignedChar = [](const QualType &T) {
95 const BuiltinType *BT = dyn_cast<BuiltinType>(Val: T.getTypePtr());
96 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
97 };
98
99 switch (SL->getKind()) {
100 case StringLiteralKind::UTF8:
101 // char8_t array can be initialized with a UTF-8 string.
102 // - C++20 [dcl.init.string] (DR)
103 // Additionally, an array of char or unsigned char may be initialized
104 // by a UTF-8 string literal.
105 if (ElemTy->isChar8Type() ||
106 (Context.getLangOpts().Char8 &&
107 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
108 return SIF_None;
109 [[fallthrough]];
110 case StringLiteralKind::Ordinary:
111 case StringLiteralKind::Binary:
112 // char array can be initialized with a narrow string.
113 // Only allow char x[] = "foo"; not char x[] = L"foo";
114 if (ElemTy->isCharType())
115 return (SL->getKind() == StringLiteralKind::UTF8 &&
116 Context.getLangOpts().Char8)
117 ? SIF_UTF8StringIntoPlainChar
118 : SIF_None;
119 if (ElemTy->isChar8Type())
120 return SIF_PlainStringIntoUTF8Char;
121 if (IsWideCharCompatible(T: ElemTy, Context))
122 return SIF_NarrowStringIntoWideChar;
123 return SIF_Other;
124 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
125 // "An array with element type compatible with a qualified or unqualified
126 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
127 // string literal with the corresponding encoding prefix (L, u, or U,
128 // respectively), optionally enclosed in braces.
129 case StringLiteralKind::UTF16:
130 if (Context.typesAreCompatible(T1: Context.Char16Ty, T2: ElemTy))
131 return SIF_None;
132 if (ElemTy->isCharType() || ElemTy->isChar8Type())
133 return SIF_WideStringIntoChar;
134 if (IsWideCharCompatible(T: ElemTy, Context))
135 return SIF_IncompatWideStringIntoWideChar;
136 return SIF_Other;
137 case StringLiteralKind::UTF32:
138 if (Context.typesAreCompatible(T1: Context.Char32Ty, T2: ElemTy))
139 return SIF_None;
140 if (ElemTy->isCharType() || ElemTy->isChar8Type())
141 return SIF_WideStringIntoChar;
142 if (IsWideCharCompatible(T: ElemTy, Context))
143 return SIF_IncompatWideStringIntoWideChar;
144 return SIF_Other;
145 case StringLiteralKind::Wide:
146 if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: ElemTy))
147 return SIF_None;
148 if (ElemTy->isCharType() || ElemTy->isChar8Type())
149 return SIF_WideStringIntoChar;
150 if (IsWideCharCompatible(T: ElemTy, Context))
151 return SIF_IncompatWideStringIntoWideChar;
152 return SIF_Other;
153 case StringLiteralKind::Unevaluated:
154 assert(false && "Unevaluated string literal in initialization");
155 break;
156 }
157
158 llvm_unreachable("missed a StringLiteral kind?");
159}
160
161static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
162 ASTContext &Context) {
163 const ArrayType *arrayType = Context.getAsArrayType(T: declType);
164 if (!arrayType)
165 return SIF_Other;
166 return IsStringInit(Init: init, AT: arrayType, Context);
167}
168
169bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
170 return ::IsStringInit(Init, AT, Context) == SIF_None;
171}
172
173/// Update the type of a string literal, including any surrounding parentheses,
174/// to match the type of the object which it is initializing.
175static void updateStringLiteralType(Expr *E, QualType Ty) {
176 while (true) {
177 E->setType(Ty);
178 E->setValueKind(VK_PRValue);
179 if (isa<StringLiteral>(Val: E) || isa<ObjCEncodeExpr>(Val: E))
180 break;
181 E = IgnoreParensSingleStep(E);
182 }
183}
184
185/// Fix a compound literal initializing an array so it's correctly marked
186/// as an rvalue.
187static void updateGNUCompoundLiteralRValue(Expr *E) {
188 while (true) {
189 E->setValueKind(VK_PRValue);
190 if (isa<CompoundLiteralExpr>(Val: E))
191 break;
192 E = IgnoreParensSingleStep(E);
193 }
194}
195
196static bool initializingConstexprVariable(const InitializedEntity &Entity) {
197 Decl *D = Entity.getDecl();
198 const InitializedEntity *Parent = &Entity;
199
200 while (Parent) {
201 D = Parent->getDecl();
202 Parent = Parent->getParent();
203 }
204
205 if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); VD && VD->isConstexpr())
206 return true;
207
208 return false;
209}
210
211static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
212 Sema &SemaRef, QualType &TT);
213
214static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
215 Sema &S, const InitializedEntity &Entity,
216 bool CheckC23ConstexprInit = false) {
217 // Get the length of the string as parsed.
218 auto *ConstantArrayTy =
219 cast<ConstantArrayType>(Val: Str->getType()->getAsArrayTypeUnsafe());
220 uint64_t StrLength = ConstantArrayTy->getZExtSize();
221
222 if (CheckC23ConstexprInit)
223 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens()))
224 CheckC23ConstexprInitStringLiteral(SE: SL, SemaRef&: S, TT&: DeclT);
225
226 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
227 // C99 6.7.8p14. We have an array of character type with unknown size
228 // being initialized to a string literal.
229 llvm::APInt ConstVal(32, StrLength);
230 // Return a new array type (C99 6.7.8p22).
231 DeclT = S.Context.getConstantArrayType(
232 EltTy: IAT->getElementType(), ArySize: ConstVal, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
233 updateStringLiteralType(E: Str, Ty: DeclT);
234 return;
235 }
236
237 const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: AT);
238 uint64_t ArrayLen = CAT->getZExtSize();
239
240 // We have an array of character type with known size. However,
241 // the size may be smaller or larger than the string we are initializing.
242 // FIXME: Avoid truncation for 64-bit length strings.
243 if (S.getLangOpts().CPlusPlus) {
244 if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) {
245 // For Pascal strings it's OK to strip off the terminating null character,
246 // so the example below is valid:
247 //
248 // unsigned char a[2] = "\pa";
249 if (SL->isPascal())
250 StrLength--;
251 }
252
253 // [dcl.init.string]p2
254 if (StrLength > ArrayLen)
255 S.Diag(Loc: Str->getBeginLoc(),
256 DiagID: diag::err_initializer_string_for_char_array_too_long)
257 << ArrayLen << StrLength << Str->getSourceRange();
258 } else {
259 // C99 6.7.8p14.
260 if (StrLength - 1 > ArrayLen)
261 S.Diag(Loc: Str->getBeginLoc(),
262 DiagID: diag::ext_initializer_string_for_char_array_too_long)
263 << Str->getSourceRange();
264 else if (StrLength - 1 == ArrayLen) {
265 // In C, if the string literal is null-terminated explicitly, e.g., `char
266 // a[4] = "ABC\0"`, there should be no warning:
267 const auto *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens());
268 bool IsSLSafe = SL && SL->getLength() > 0 &&
269 SL->getCodeUnit(I: SL->getLength() - 1) == 0;
270
271 if (!IsSLSafe) {
272 // If the entity being initialized has the nonstring attribute, then
273 // silence the "missing nonstring" diagnostic. If there's no entity,
274 // check whether we're initializing an array of arrays; if so, walk the
275 // parents to find an entity.
276 auto FindCorrectEntity =
277 [](const InitializedEntity *Entity) -> const ValueDecl * {
278 while (Entity) {
279 if (const ValueDecl *VD = Entity->getDecl())
280 return VD;
281 if (!Entity->getType()->isArrayType())
282 return nullptr;
283 Entity = Entity->getParent();
284 }
285
286 return nullptr;
287 };
288 if (const ValueDecl *D = FindCorrectEntity(&Entity);
289 !D || !D->hasAttr<NonStringAttr>())
290 S.Diag(
291 Loc: Str->getBeginLoc(),
292 DiagID: diag::
293 warn_initializer_string_for_char_array_too_long_no_nonstring)
294 << ArrayLen << StrLength << Str->getSourceRange();
295 }
296 // Always emit the C++ compatibility diagnostic.
297 S.Diag(Loc: Str->getBeginLoc(),
298 DiagID: diag::warn_initializer_string_for_char_array_too_long_for_cpp)
299 << ArrayLen << StrLength << Str->getSourceRange();
300 }
301 }
302
303 // Set the type to the actual size that we are initializing. If we have
304 // something like:
305 // char x[1] = "foo";
306 // then this will set the string literal's type to char[1].
307 updateStringLiteralType(E: Str, Ty: DeclT);
308}
309
310void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R) {
311 for (const FieldDecl *Field : R->fields()) {
312 if (Field->hasAttr<ExplicitInitAttr>())
313 S.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at) << Field;
314 }
315}
316
317//===----------------------------------------------------------------------===//
318// Semantic checking for initializer lists.
319//===----------------------------------------------------------------------===//
320
321namespace {
322
323/// Semantic checking for initializer lists.
324///
325/// The InitListChecker class contains a set of routines that each
326/// handle the initialization of a certain kind of entity, e.g.,
327/// arrays, vectors, struct/union types, scalars, etc. The
328/// InitListChecker itself performs a recursive walk of the subobject
329/// structure of the type to be initialized, while stepping through
330/// the initializer list one element at a time. The IList and Index
331/// parameters to each of the Check* routines contain the active
332/// (syntactic) initializer list and the index into that initializer
333/// list that represents the current initializer. Each routine is
334/// responsible for moving that Index forward as it consumes elements.
335///
336/// Each Check* routine also has a StructuredList/StructuredIndex
337/// arguments, which contains the current "structured" (semantic)
338/// initializer list and the index into that initializer list where we
339/// are copying initializers as we map them over to the semantic
340/// list. Once we have completed our recursive walk of the subobject
341/// structure, we will have constructed a full semantic initializer
342/// list.
343///
344/// C99 designators cause changes in the initializer list traversal,
345/// because they make the initialization "jump" into a specific
346/// subobject and then continue the initialization from that
347/// point. CheckDesignatedInitializer() recursively steps into the
348/// designated subobject and manages backing out the recursion to
349/// initialize the subobjects after the one designated.
350///
351/// If an initializer list contains any designators, we build a placeholder
352/// structured list even in 'verify only' mode, so that we can track which
353/// elements need 'empty' initializtion.
354class InitListChecker {
355 Sema &SemaRef;
356 bool hadError = false;
357 bool VerifyOnly; // No diagnostics.
358 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
359 bool InOverloadResolution;
360 InitListExpr *FullyStructuredList = nullptr;
361 NoInitExpr *DummyExpr = nullptr;
362 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
363 EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing.
364 unsigned CurEmbedIndex = 0;
365
366 NoInitExpr *getDummyInit() {
367 if (!DummyExpr)
368 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
369 return DummyExpr;
370 }
371
372 void CheckImplicitInitList(const InitializedEntity &Entity,
373 InitListExpr *ParentIList, QualType T,
374 unsigned &Index, InitListExpr *StructuredList,
375 unsigned &StructuredIndex);
376 void CheckExplicitInitList(const InitializedEntity &Entity,
377 InitListExpr *IList, QualType &T,
378 InitListExpr *StructuredList,
379 bool TopLevelObject = false);
380 void CheckListElementTypes(const InitializedEntity &Entity,
381 InitListExpr *IList, QualType &DeclType,
382 bool SubobjectIsDesignatorContext,
383 unsigned &Index,
384 InitListExpr *StructuredList,
385 unsigned &StructuredIndex,
386 bool TopLevelObject = false);
387 void CheckSubElementType(const InitializedEntity &Entity,
388 InitListExpr *IList, QualType ElemType,
389 unsigned &Index,
390 InitListExpr *StructuredList,
391 unsigned &StructuredIndex,
392 bool DirectlyDesignated = false);
393 void CheckComplexType(const InitializedEntity &Entity,
394 InitListExpr *IList, QualType DeclType,
395 unsigned &Index,
396 InitListExpr *StructuredList,
397 unsigned &StructuredIndex);
398 void CheckScalarType(const InitializedEntity &Entity,
399 InitListExpr *IList, QualType DeclType,
400 unsigned &Index,
401 InitListExpr *StructuredList,
402 unsigned &StructuredIndex);
403 void CheckReferenceType(const InitializedEntity &Entity,
404 InitListExpr *IList, QualType DeclType,
405 unsigned &Index,
406 InitListExpr *StructuredList,
407 unsigned &StructuredIndex);
408 void CheckMatrixType(const InitializedEntity &Entity, InitListExpr *IList,
409 QualType DeclType, unsigned &Index,
410 InitListExpr *StructuredList, unsigned &StructuredIndex);
411 void CheckVectorType(const InitializedEntity &Entity,
412 InitListExpr *IList, QualType DeclType, unsigned &Index,
413 InitListExpr *StructuredList,
414 unsigned &StructuredIndex);
415 void CheckStructUnionTypes(const InitializedEntity &Entity,
416 InitListExpr *IList, QualType DeclType,
417 CXXRecordDecl::base_class_const_range Bases,
418 RecordDecl::field_iterator Field,
419 bool SubobjectIsDesignatorContext, unsigned &Index,
420 InitListExpr *StructuredList,
421 unsigned &StructuredIndex,
422 bool TopLevelObject = false);
423 void CheckArrayType(const InitializedEntity &Entity,
424 InitListExpr *IList, QualType &DeclType,
425 llvm::APSInt elementIndex,
426 bool SubobjectIsDesignatorContext, unsigned &Index,
427 InitListExpr *StructuredList,
428 unsigned &StructuredIndex);
429 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
430 InitListExpr *IList, DesignatedInitExpr *DIE,
431 unsigned DesigIdx,
432 QualType &CurrentObjectType,
433 RecordDecl::field_iterator *NextField,
434 llvm::APSInt *NextElementIndex,
435 unsigned &Index,
436 InitListExpr *StructuredList,
437 unsigned &StructuredIndex,
438 bool FinishSubobjectInit,
439 bool TopLevelObject);
440 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
441 QualType CurrentObjectType,
442 InitListExpr *StructuredList,
443 unsigned StructuredIndex,
444 SourceRange InitRange,
445 bool IsFullyOverwritten = false);
446 void UpdateStructuredListElement(InitListExpr *StructuredList,
447 unsigned &StructuredIndex,
448 Expr *expr);
449 InitListExpr *createInitListExpr(QualType CurrentObjectType,
450 SourceRange InitRange,
451 unsigned ExpectedNumInits, bool IsExplicit);
452 int numArrayElements(QualType DeclType);
453 int numStructUnionElements(QualType DeclType);
454
455 ExprResult PerformEmptyInit(SourceLocation Loc,
456 const InitializedEntity &Entity);
457
458 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
459 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
460 bool UnionOverride = false,
461 bool FullyOverwritten = true) {
462 // Overriding an initializer via a designator is valid with C99 designated
463 // initializers, but ill-formed with C++20 designated initializers.
464 unsigned DiagID =
465 SemaRef.getLangOpts().CPlusPlus
466 ? (UnionOverride ? diag::ext_initializer_union_overrides
467 : diag::ext_initializer_overrides)
468 : diag::warn_initializer_overrides;
469
470 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
471 // In overload resolution, we have to strictly enforce the rules, and so
472 // don't allow any overriding of prior initializers. This matters for a
473 // case such as:
474 //
475 // union U { int a, b; };
476 // struct S { int a, b; };
477 // void f(U), f(S);
478 //
479 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
480 // consistency, we disallow all overriding of prior initializers in
481 // overload resolution, not only overriding of union members.
482 hadError = true;
483 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
484 // If we'll be keeping around the old initializer but overwriting part of
485 // the object it initialized, and that object is not trivially
486 // destructible, this can leak. Don't allow that, not even as an
487 // extension.
488 //
489 // FIXME: It might be reasonable to allow this in cases where the part of
490 // the initializer that we're overriding has trivial destruction.
491 DiagID = diag::err_initializer_overrides_destructed;
492 } else if (!OldInit->getSourceRange().isValid()) {
493 // We need to check on source range validity because the previous
494 // initializer does not have to be an explicit initializer. e.g.,
495 //
496 // struct P { int a, b; };
497 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
498 //
499 // There is an overwrite taking place because the first braced initializer
500 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
501 //
502 // Such overwrites are harmless, so we don't diagnose them. (Note that in
503 // C++, this cannot be reached unless we've already seen and diagnosed a
504 // different conformance issue, such as a mixture of designated and
505 // non-designated initializers or a multi-level designator.)
506 return;
507 }
508
509 if (!VerifyOnly) {
510 SemaRef.Diag(Loc: NewInitRange.getBegin(), DiagID)
511 << NewInitRange << FullyOverwritten << OldInit->getType();
512 SemaRef.Diag(Loc: OldInit->getBeginLoc(), DiagID: diag::note_previous_initializer)
513 << (OldInit->HasSideEffects(Ctx: SemaRef.Context) && FullyOverwritten)
514 << OldInit->getSourceRange();
515 }
516 }
517
518 // Explanation on the "FillWithNoInit" mode:
519 //
520 // Assume we have the following definitions (Case#1):
521 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
522 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
523 //
524 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
525 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
526 //
527 // But if we have (Case#2):
528 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
529 //
530 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
531 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
532 //
533 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
534 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
535 // initializers but with special "NoInitExpr" place holders, which tells the
536 // CodeGen not to generate any initializers for these parts.
537 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
538 const InitializedEntity &ParentEntity,
539 InitListExpr *ILE, bool &RequiresSecondPass,
540 bool FillWithNoInit);
541 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
542 const InitializedEntity &ParentEntity,
543 InitListExpr *ILE, bool &RequiresSecondPass,
544 bool FillWithNoInit = false);
545 void FillInEmptyInitializations(const InitializedEntity &Entity,
546 InitListExpr *ILE, bool &RequiresSecondPass,
547 InitListExpr *OuterILE, unsigned OuterIndex,
548 bool FillWithNoInit = false);
549 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
550 Expr *InitExpr, FieldDecl *Field,
551 bool TopLevelObject);
552 void CheckEmptyInitializable(const InitializedEntity &Entity,
553 SourceLocation Loc);
554
555 Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) {
556 Expr *Result = nullptr;
557 // Undrestand which part of embed we'd like to reference.
558 if (!CurEmbed) {
559 CurEmbed = Embed;
560 CurEmbedIndex = 0;
561 }
562 // Reference just one if we're initializing a single scalar.
563 uint64_t ElsCount = 1;
564 // Otherwise try to fill whole array with embed data.
565 if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
566 unsigned ArrIndex = Entity.getElementIndex();
567 auto *AType =
568 SemaRef.Context.getAsArrayType(T: Entity.getParent()->getType());
569 assert(AType && "expected array type when initializing array");
570 ElsCount = Embed->getDataElementCount();
571 if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType))
572 ElsCount = std::min(a: CAType->getSize().getZExtValue() - ArrIndex,
573 b: ElsCount - CurEmbedIndex);
574 if (ElsCount == Embed->getDataElementCount()) {
575 CurEmbed = nullptr;
576 CurEmbedIndex = 0;
577 return Embed;
578 }
579 }
580
581 Result = new (SemaRef.Context)
582 EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(),
583 CurEmbedIndex, ElsCount);
584 CurEmbedIndex += ElsCount;
585 if (CurEmbedIndex >= Embed->getDataElementCount()) {
586 CurEmbed = nullptr;
587 CurEmbedIndex = 0;
588 }
589 return Result;
590 }
591
592public:
593 InitListChecker(
594 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
595 bool VerifyOnly, bool TreatUnavailableAsInvalid,
596 bool InOverloadResolution = false,
597 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
598 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
599 QualType &T,
600 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
601 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
602 /*TreatUnavailableAsInvalid=*/false,
603 /*InOverloadResolution=*/false,
604 &AggrDeductionCandidateParamTypes) {}
605
606 bool HadError() { return hadError; }
607
608 // Retrieves the fully-structured initializer list used for
609 // semantic analysis and code generation.
610 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
611};
612
613} // end anonymous namespace
614
615ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
616 const InitializedEntity &Entity) {
617 InitializationKind Kind = InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc,
618 isImplicit: true);
619 MultiExprArg SubInit;
620 Expr *InitExpr;
621 InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc,
622 /*isExplicit=*/false);
623
624 // C++ [dcl.init.aggr]p7:
625 // If there are fewer initializer-clauses in the list than there are
626 // members in the aggregate, then each member not explicitly initialized
627 // ...
628 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
629 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
630 if (EmptyInitList) {
631 // C++1y / DR1070:
632 // shall be initialized [...] from an empty initializer list.
633 //
634 // We apply the resolution of this DR to C++11 but not C++98, since C++98
635 // does not have useful semantics for initialization from an init list.
636 // We treat this as copy-initialization, because aggregate initialization
637 // always performs copy-initialization on its elements.
638 //
639 // Only do this if we're initializing a class type, to avoid filling in
640 // the initializer list where possible.
641 InitExpr = VerifyOnly ? &DummyInitList
642 : new (SemaRef.Context)
643 InitListExpr(SemaRef.Context, Loc, {}, Loc,
644 /*isExplicit=*/false);
645 InitExpr->setType(SemaRef.Context.VoidTy);
646 SubInit = InitExpr;
647 Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
648 } else {
649 // C++03:
650 // shall be value-initialized.
651 }
652
653 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
654 // HACK: libstdc++ prior to 4.9 marks the vector default constructor
655 // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic
656 // in that case. stlport does so too.
657 // Look for std::__debug for libstdc++, and for std:: for stlport.
658 // This is effectively a compiler-side implementation of LWG2193.
659 if (!InitSeq && EmptyInitList &&
660 InitSeq.getFailureKind() ==
661 InitializationSequence::FK_ExplicitConstructor &&
662 SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2014'04'22)) {
663 OverloadCandidateSet::iterator Best;
664 OverloadingResult O =
665 InitSeq.getFailedCandidateSet()
666 .BestViableFunction(S&: SemaRef, Loc: Kind.getLocation(), Best);
667 (void)O;
668 assert(O == OR_Success && "Inconsistent overload resolution");
669 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
670 CXXRecordDecl *R = CtorDecl->getParent();
671
672 if (CtorDecl->getMinRequiredArguments() == 0 &&
673 CtorDecl->isExplicit() && R->getDeclName() &&
674 SemaRef.SourceMgr.isInSystemHeader(Loc: CtorDecl->getLocation())) {
675 bool IsInStd = false;
676 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: R->getDeclContext());
677 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(Val: ND->getParent())) {
678 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(NS: ND))
679 IsInStd = true;
680 }
681
682 if (IsInStd &&
683 llvm::StringSwitch<bool>(R->getName())
684 .Cases(CaseStrings: {"basic_string", "deque", "forward_list"}, Value: true)
685 .Cases(CaseStrings: {"list", "map", "multimap", "multiset"}, Value: true)
686 .Cases(CaseStrings: {"priority_queue", "queue", "set", "stack"}, Value: true)
687 .Cases(CaseStrings: {"unordered_map", "unordered_set", "vector"}, Value: true)
688 .Default(Value: false)) {
689 InitSeq.InitializeFrom(
690 S&: SemaRef, Entity,
691 Kind: InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, isImplicit: true),
692 Args: MultiExprArg(), /*TopLevelOfInitList=*/false,
693 TreatUnavailableAsInvalid);
694 // Emit a warning for this. System header warnings aren't shown
695 // by default, but people working on system headers should see it.
696 if (!VerifyOnly) {
697 SemaRef.Diag(Loc: CtorDecl->getLocation(),
698 DiagID: diag::warn_invalid_initializer_from_system_header);
699 if (Entity.getKind() == InitializedEntity::EK_Member)
700 SemaRef.Diag(Loc: Entity.getDecl()->getLocation(),
701 DiagID: diag::note_used_in_initialization_here);
702 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
703 SemaRef.Diag(Loc, DiagID: diag::note_used_in_initialization_here);
704 }
705 }
706 }
707 }
708 if (!InitSeq) {
709 if (!VerifyOnly) {
710 InitSeq.Diagnose(S&: SemaRef, Entity, Kind, Args: SubInit);
711 if (Entity.getKind() == InitializedEntity::EK_Member)
712 SemaRef.Diag(Loc: Entity.getDecl()->getLocation(),
713 DiagID: diag::note_in_omitted_aggregate_initializer)
714 << /*field*/1 << Entity.getDecl();
715 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
716 bool IsTrailingArrayNewMember =
717 Entity.getParent() &&
718 Entity.getParent()->isVariableLengthArrayNew();
719 SemaRef.Diag(Loc, DiagID: diag::note_in_omitted_aggregate_initializer)
720 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
721 << Entity.getElementIndex();
722 }
723 }
724 hadError = true;
725 return ExprError();
726 }
727
728 return VerifyOnly ? ExprResult()
729 : InitSeq.Perform(S&: SemaRef, Entity, Kind, Args: SubInit);
730}
731
732void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
733 SourceLocation Loc) {
734 // If we're building a fully-structured list, we'll check this at the end
735 // once we know which elements are actually initialized. Otherwise, we know
736 // that there are no designators so we can just check now.
737 if (FullyStructuredList)
738 return;
739 PerformEmptyInit(Loc, Entity);
740}
741
742void InitListChecker::FillInEmptyInitForBase(
743 unsigned Init, const CXXBaseSpecifier &Base,
744 const InitializedEntity &ParentEntity, InitListExpr *ILE,
745 bool &RequiresSecondPass, bool FillWithNoInit) {
746 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
747 Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &ParentEntity);
748
749 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
750 ExprResult BaseInit = FillWithNoInit
751 ? new (SemaRef.Context) NoInitExpr(Base.getType())
752 : PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: BaseEntity);
753 if (BaseInit.isInvalid()) {
754 hadError = true;
755 return;
756 }
757
758 if (!VerifyOnly) {
759 assert(Init < ILE->getNumInits() && "should have been expanded");
760 ILE->setInit(Init, expr: BaseInit.getAs<Expr>());
761 }
762 } else if (InitListExpr *InnerILE =
763 dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) {
764 FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerILE, RequiresSecondPass,
765 OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
766 } else if (DesignatedInitUpdateExpr *InnerDIUE =
767 dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) {
768 FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerDIUE->getUpdater(),
769 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
770 /*FillWithNoInit =*/true);
771 }
772}
773
774void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
775 const InitializedEntity &ParentEntity,
776 InitListExpr *ILE,
777 bool &RequiresSecondPass,
778 bool FillWithNoInit) {
779 SourceLocation Loc = ILE->getEndLoc();
780 unsigned NumInits = ILE->getNumInits();
781 InitializedEntity MemberEntity
782 = InitializedEntity::InitializeMember(Member: Field, Parent: &ParentEntity);
783
784 if (Init >= NumInits || !ILE->getInit(Init)) {
785 if (const RecordType *RType = ILE->getType()->getAsCanonical<RecordType>())
786 if (!RType->getDecl()->isUnion())
787 assert((Init < NumInits || VerifyOnly) &&
788 "This ILE should have been expanded");
789
790 if (FillWithNoInit) {
791 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
792 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
793 if (Init < NumInits)
794 ILE->setInit(Init, expr: Filler);
795 else
796 ILE->updateInit(C: SemaRef.Context, Init, expr: Filler);
797 return;
798 }
799
800 if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() &&
801 !SemaRef.isUnevaluatedContext()) {
802 SemaRef.Diag(Loc: ILE->getExprLoc(), DiagID: diag::warn_field_requires_explicit_init)
803 << /* Var-in-Record */ 0 << Field;
804 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at)
805 << Field;
806 }
807
808 // C++1y [dcl.init.aggr]p7:
809 // If there are fewer initializer-clauses in the list than there are
810 // members in the aggregate, then each member not explicitly initialized
811 // shall be initialized from its brace-or-equal-initializer [...]
812 if (Field->hasInClassInitializer()) {
813 if (VerifyOnly)
814 return;
815
816 ExprResult DIE;
817 {
818 // Enter a default initializer rebuild context, then we can support
819 // lifetime extension of temporary created by aggregate initialization
820 // using a default member initializer.
821 // CWG1815 (https://wg21.link/CWG1815).
822 EnterExpressionEvaluationContext RebuildDefaultInit(
823 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
824 SemaRef.currentEvaluationContext().RebuildDefaultArgOrDefaultInit =
825 true;
826 SemaRef.currentEvaluationContext().DelayedDefaultInitializationContext =
827 SemaRef.parentEvaluationContext()
828 .DelayedDefaultInitializationContext;
829 SemaRef.currentEvaluationContext().InLifetimeExtendingContext =
830 SemaRef.parentEvaluationContext().InLifetimeExtendingContext;
831 DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
832 }
833 if (DIE.isInvalid()) {
834 hadError = true;
835 return;
836 }
837 SemaRef.checkInitializerLifetime(Entity: MemberEntity, Init: DIE.get());
838 if (Init < NumInits)
839 ILE->setInit(Init, expr: DIE.get());
840 else {
841 ILE->updateInit(C: SemaRef.Context, Init, expr: DIE.get());
842 RequiresSecondPass = true;
843 }
844 return;
845 }
846
847 if (Field->getType()->isReferenceType()) {
848 if (!VerifyOnly) {
849 // C++ [dcl.init.aggr]p9:
850 // If an incomplete or empty initializer-list leaves a
851 // member of reference type uninitialized, the program is
852 // ill-formed.
853 SemaRef.Diag(Loc, DiagID: diag::err_init_reference_member_uninitialized)
854 << Field->getType()
855 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
856 ->getSourceRange();
857 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_uninit_reference_member);
858 }
859 hadError = true;
860 return;
861 }
862
863 ExprResult MemberInit = PerformEmptyInit(Loc, Entity: MemberEntity);
864 if (MemberInit.isInvalid()) {
865 hadError = true;
866 return;
867 }
868
869 if (hadError || VerifyOnly) {
870 // Do nothing
871 } else if (Init < NumInits) {
872 ILE->setInit(Init, expr: MemberInit.getAs<Expr>());
873 } else if (!isa<ImplicitValueInitExpr>(Val: MemberInit.get())) {
874 // Empty initialization requires a constructor call, so
875 // extend the initializer list to include the constructor
876 // call and make a note that we'll need to take another pass
877 // through the initializer list.
878 ILE->updateInit(C: SemaRef.Context, Init, expr: MemberInit.getAs<Expr>());
879 RequiresSecondPass = true;
880 }
881 } else if (InitListExpr *InnerILE
882 = dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) {
883 FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerILE,
884 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
885 } else if (DesignatedInitUpdateExpr *InnerDIUE =
886 dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) {
887 FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerDIUE->getUpdater(),
888 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
889 /*FillWithNoInit =*/true);
890 }
891}
892
893/// Recursively replaces NULL values within the given initializer list
894/// with expressions that perform value-initialization of the
895/// appropriate type, and finish off the InitListExpr formation.
896void
897InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
898 InitListExpr *ILE,
899 bool &RequiresSecondPass,
900 InitListExpr *OuterILE,
901 unsigned OuterIndex,
902 bool FillWithNoInit) {
903 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
904 "Should not have void type");
905
906 // We don't need to do any checks when just filling NoInitExprs; that can't
907 // fail.
908 if (FillWithNoInit && VerifyOnly)
909 return;
910
911 // If this is a nested initializer list, we might have changed its contents
912 // (and therefore some of its properties, such as instantiation-dependence)
913 // while filling it in. Inform the outer initializer list so that its state
914 // can be updated to match.
915 // FIXME: We should fully build the inner initializers before constructing
916 // the outer InitListExpr instead of mutating AST nodes after they have
917 // been used as subexpressions of other nodes.
918 struct UpdateOuterILEWithUpdatedInit {
919 InitListExpr *Outer;
920 unsigned OuterIndex;
921 ~UpdateOuterILEWithUpdatedInit() {
922 if (Outer)
923 Outer->setInit(Init: OuterIndex, expr: Outer->getInit(Init: OuterIndex));
924 }
925 } UpdateOuterRAII = {.Outer: OuterILE, .OuterIndex: OuterIndex};
926
927 // A transparent ILE is not performing aggregate initialization and should
928 // not be filled in.
929 if (ILE->isTransparent())
930 return;
931
932 if (const auto *RDecl = ILE->getType()->getAsRecordDecl()) {
933 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) {
934 FillInEmptyInitForField(Init: 0, Field: ILE->getInitializedFieldInUnion(), ParentEntity: Entity, ILE,
935 RequiresSecondPass, FillWithNoInit);
936 } else {
937 assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) ||
938 !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) &&
939 "We should have computed initialized fields already");
940 // The fields beyond ILE->getNumInits() are default initialized, so in
941 // order to leave them uninitialized, the ILE is expanded and the extra
942 // fields are then filled with NoInitExpr.
943 unsigned NumElems = numStructUnionElements(DeclType: ILE->getType());
944 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
945 ++NumElems;
946 if (!VerifyOnly && ILE->getNumInits() < NumElems)
947 ILE->resizeInits(Context: SemaRef.Context, NumInits: NumElems);
948
949 unsigned Init = 0;
950
951 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RDecl)) {
952 for (auto &Base : CXXRD->bases()) {
953 if (hadError)
954 return;
955
956 FillInEmptyInitForBase(Init, Base, ParentEntity: Entity, ILE, RequiresSecondPass,
957 FillWithNoInit);
958 ++Init;
959 }
960 }
961
962 for (auto *Field : RDecl->fields()) {
963 if (Field->isUnnamedBitField())
964 continue;
965
966 if (hadError)
967 return;
968
969 FillInEmptyInitForField(Init, Field, ParentEntity: Entity, ILE, RequiresSecondPass,
970 FillWithNoInit);
971 if (hadError)
972 return;
973
974 ++Init;
975
976 // Only look at the first initialization of a union.
977 if (RDecl->isUnion())
978 break;
979 }
980 }
981
982 return;
983 }
984
985 QualType ElementType;
986
987 InitializedEntity ElementEntity = Entity;
988 unsigned NumInits = ILE->getNumInits();
989 uint64_t NumElements = NumInits;
990 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(T: ILE->getType())) {
991 ElementType = AType->getElementType();
992 if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType))
993 NumElements = CAType->getZExtSize();
994 // For an array new with an unknown bound, ask for one additional element
995 // in order to populate the array filler.
996 if (Entity.isVariableLengthArrayNew())
997 ++NumElements;
998 ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context,
999 Index: 0, Parent: Entity);
1000 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
1001 ElementType = VType->getElementType();
1002 NumElements = VType->getNumElements();
1003 ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context,
1004 Index: 0, Parent: Entity);
1005 } else
1006 ElementType = ILE->getType();
1007
1008 bool SkipEmptyInitChecks = false;
1009 for (uint64_t Init = 0; Init != NumElements; ++Init) {
1010 if (hadError)
1011 return;
1012
1013 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
1014 ElementEntity.getKind() == InitializedEntity::EK_VectorElement ||
1015 ElementEntity.getKind() == InitializedEntity::EK_MatrixElement)
1016 ElementEntity.setElementIndex(Init);
1017
1018 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
1019 return;
1020
1021 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
1022 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
1023 ILE->setInit(Init, expr: ILE->getArrayFiller());
1024 else if (!InitExpr && !ILE->hasArrayFiller()) {
1025 // In VerifyOnly mode, there's no point performing empty initialization
1026 // more than once.
1027 if (SkipEmptyInitChecks)
1028 continue;
1029
1030 Expr *Filler = nullptr;
1031
1032 if (FillWithNoInit)
1033 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
1034 else {
1035 ExprResult ElementInit =
1036 PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: ElementEntity);
1037 if (ElementInit.isInvalid()) {
1038 hadError = true;
1039 return;
1040 }
1041
1042 Filler = ElementInit.getAs<Expr>();
1043 }
1044
1045 if (hadError) {
1046 // Do nothing
1047 } else if (VerifyOnly) {
1048 SkipEmptyInitChecks = true;
1049 } else if (Init < NumInits) {
1050 // For arrays, just set the expression used for value-initialization
1051 // of the "holes" in the array.
1052 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
1053 ILE->setArrayFiller(Filler);
1054 else
1055 ILE->setInit(Init, expr: Filler);
1056 } else {
1057 // For arrays, just set the expression used for value-initialization
1058 // of the rest of elements and exit.
1059 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
1060 ILE->setArrayFiller(Filler);
1061 return;
1062 }
1063
1064 if (!isa<ImplicitValueInitExpr>(Val: Filler) && !isa<NoInitExpr>(Val: Filler)) {
1065 // Empty initialization requires a constructor call, so
1066 // extend the initializer list to include the constructor
1067 // call and make a note that we'll need to take another pass
1068 // through the initializer list.
1069 ILE->updateInit(C: SemaRef.Context, Init, expr: Filler);
1070 RequiresSecondPass = true;
1071 }
1072 }
1073 } else if (InitListExpr *InnerILE
1074 = dyn_cast_or_null<InitListExpr>(Val: InitExpr)) {
1075 FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerILE, RequiresSecondPass,
1076 OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
1077 } else if (DesignatedInitUpdateExpr *InnerDIUE =
1078 dyn_cast_or_null<DesignatedInitUpdateExpr>(Val: InitExpr)) {
1079 FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerDIUE->getUpdater(),
1080 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
1081 /*FillWithNoInit =*/true);
1082 }
1083 }
1084}
1085
1086static bool hasAnyDesignatedInits(const InitListExpr *IL) {
1087 for (const Stmt *Init : *IL)
1088 if (isa_and_nonnull<DesignatedInitExpr>(Val: Init))
1089 return true;
1090 return false;
1091}
1092
1093InitListChecker::InitListChecker(
1094 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
1095 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
1096 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
1097 : SemaRef(S), VerifyOnly(VerifyOnly),
1098 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
1099 InOverloadResolution(InOverloadResolution),
1100 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
1101 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
1102 FullyStructuredList = createInitListExpr(
1103 CurrentObjectType: T, InitRange: IL->getSourceRange(), ExpectedNumInits: IL->getNumInits(), IsExplicit: IL->isExplicit());
1104
1105 // FIXME: Check that IL isn't already the semantic form of some other
1106 // InitListExpr. If it is, we'd create a broken AST.
1107 if (!VerifyOnly)
1108 FullyStructuredList->setSyntacticForm(IL);
1109 }
1110
1111 CheckExplicitInitList(Entity, IList: IL, T, StructuredList: FullyStructuredList,
1112 /*TopLevelObject=*/true);
1113
1114 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1115 bool RequiresSecondPass = false;
1116 FillInEmptyInitializations(Entity, ILE: FullyStructuredList, RequiresSecondPass,
1117 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1118 if (RequiresSecondPass && !hadError)
1119 FillInEmptyInitializations(Entity, ILE: FullyStructuredList,
1120 RequiresSecondPass, OuterILE: nullptr, OuterIndex: 0);
1121 }
1122 if (hadError && FullyStructuredList)
1123 FullyStructuredList->markError();
1124}
1125
1126int InitListChecker::numArrayElements(QualType DeclType) {
1127 // FIXME: use a proper constant
1128 int maxElements = 0x7FFFFFFF;
1129 if (const ConstantArrayType *CAT =
1130 SemaRef.Context.getAsConstantArrayType(T: DeclType)) {
1131 maxElements = static_cast<int>(CAT->getZExtSize());
1132 }
1133 return maxElements;
1134}
1135
1136int InitListChecker::numStructUnionElements(QualType DeclType) {
1137 auto *structDecl = DeclType->castAsRecordDecl();
1138 int InitializableMembers = 0;
1139 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: structDecl))
1140 InitializableMembers += CXXRD->getNumBases();
1141 for (const auto *Field : structDecl->fields())
1142 if (!Field->isUnnamedBitField())
1143 ++InitializableMembers;
1144
1145 if (structDecl->isUnion())
1146 return std::min(a: InitializableMembers, b: 1);
1147 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1148}
1149
1150/// Determine whether Entity is an entity for which it is idiomatic to elide
1151/// the braces in aggregate initialization.
1152static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1153 // Recursive initialization of the one and only field within an aggregate
1154 // class is considered idiomatic. This case arises in particular for
1155 // initialization of std::array, where the C++ standard suggests the idiom of
1156 //
1157 // std::array<T, N> arr = {1, 2, 3};
1158 //
1159 // (where std::array is an aggregate struct containing a single array field.
1160
1161 if (!Entity.getParent())
1162 return false;
1163
1164 // Allows elide brace initialization for aggregates with empty base.
1165 if (Entity.getKind() == InitializedEntity::EK_Base) {
1166 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1167 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(Val: ParentRD);
1168 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1169 }
1170
1171 // Allow brace elision if the only subobject is a field.
1172 if (Entity.getKind() == InitializedEntity::EK_Member) {
1173 auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl();
1174 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: ParentRD)) {
1175 if (CXXRD->getNumBases()) {
1176 return false;
1177 }
1178 }
1179 auto FieldIt = ParentRD->field_begin();
1180 assert(FieldIt != ParentRD->field_end() &&
1181 "no fields but have initializer for member?");
1182 return ++FieldIt == ParentRD->field_end();
1183 }
1184
1185 return false;
1186}
1187
1188/// Check whether the range of the initializer \p ParentIList from element
1189/// \p Index onwards can be used to initialize an object of type \p T. Update
1190/// \p Index to indicate how many elements of the list were consumed.
1191///
1192/// This also fills in \p StructuredList, from element \p StructuredIndex
1193/// onwards, with the fully-braced, desugared form of the initialization.
1194void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1195 InitListExpr *ParentIList,
1196 QualType T, unsigned &Index,
1197 InitListExpr *StructuredList,
1198 unsigned &StructuredIndex) {
1199 int maxElements = 0;
1200
1201 if (T->isArrayType())
1202 maxElements = numArrayElements(DeclType: T);
1203 else if (T->isRecordType())
1204 maxElements = numStructUnionElements(DeclType: T);
1205 else if (T->isVectorType())
1206 maxElements = T->castAs<VectorType>()->getNumElements();
1207 else
1208 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1209
1210 if (maxElements == 0) {
1211 if (!VerifyOnly)
1212 SemaRef.Diag(Loc: ParentIList->getInit(Init: Index)->getBeginLoc(),
1213 DiagID: diag::err_implicit_empty_initializer);
1214 ++Index;
1215 hadError = true;
1216 return;
1217 }
1218
1219 // Build a structured initializer list corresponding to this subobject.
1220 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1221 IList: ParentIList, Index, CurrentObjectType: T, StructuredList, StructuredIndex,
1222 InitRange: SourceRange(ParentIList->getInit(Init: Index)->getBeginLoc(),
1223 ParentIList->getSourceRange().getEnd()));
1224 unsigned StructuredSubobjectInitIndex = 0;
1225
1226 // Check the element types and build the structural subobject.
1227 unsigned StartIndex = Index;
1228 CheckListElementTypes(Entity, IList: ParentIList, DeclType&: T,
1229 /*SubobjectIsDesignatorContext=*/false, Index,
1230 StructuredList: StructuredSubobjectInitList,
1231 StructuredIndex&: StructuredSubobjectInitIndex);
1232
1233 if (StructuredSubobjectInitList) {
1234 StructuredSubobjectInitList->setType(T);
1235
1236 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1237 // Update the structured sub-object initializer so that it's ending
1238 // range corresponds with the end of the last initializer it used.
1239 if (EndIndex < ParentIList->getNumInits() &&
1240 ParentIList->getInit(Init: EndIndex)) {
1241 SourceLocation EndLoc
1242 = ParentIList->getInit(Init: EndIndex)->getSourceRange().getEnd();
1243 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1244 }
1245
1246 // Complain about missing braces.
1247 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1248 !ParentIList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) &&
1249 !isIdiomaticBraceElisionEntity(Entity)) {
1250 SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(),
1251 DiagID: diag::warn_missing_braces)
1252 << StructuredSubobjectInitList->getSourceRange()
1253 << FixItHint::CreateInsertion(
1254 InsertionLoc: StructuredSubobjectInitList->getBeginLoc(), Code: "{")
1255 << FixItHint::CreateInsertion(
1256 InsertionLoc: SemaRef.getLocForEndOfToken(
1257 Loc: StructuredSubobjectInitList->getEndLoc()),
1258 Code: "}");
1259 }
1260
1261 // Warn if this type won't be an aggregate in future versions of C++.
1262 auto *CXXRD = T->getAsCXXRecordDecl();
1263 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1264 SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(),
1265 DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors)
1266 << StructuredSubobjectInitList->getSourceRange() << T;
1267 }
1268 }
1269}
1270
1271/// Warn that \p Entity was of scalar type and was initialized by a
1272/// single-element braced initializer list.
1273static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1274 SourceRange Braces) {
1275 // Don't warn during template instantiation. If the initialization was
1276 // non-dependent, we warned during the initial parse; otherwise, the
1277 // type might not be scalar in some uses of the template.
1278 if (S.inTemplateInstantiation())
1279 return;
1280
1281 unsigned DiagID = 0;
1282
1283 switch (Entity.getKind()) {
1284 case InitializedEntity::EK_VectorElement:
1285 case InitializedEntity::EK_MatrixElement:
1286 case InitializedEntity::EK_ComplexElement:
1287 case InitializedEntity::EK_ArrayElement:
1288 case InitializedEntity::EK_Parameter:
1289 case InitializedEntity::EK_Parameter_CF_Audited:
1290 case InitializedEntity::EK_TemplateParameter:
1291 case InitializedEntity::EK_Result:
1292 case InitializedEntity::EK_ParenAggInitMember:
1293 // Extra braces here are suspicious.
1294 DiagID = diag::warn_braces_around_init;
1295 break;
1296
1297 case InitializedEntity::EK_Member:
1298 // Warn on aggregate initialization but not on ctor init list or
1299 // default member initializer.
1300 if (Entity.getParent())
1301 DiagID = diag::warn_braces_around_init;
1302 break;
1303
1304 case InitializedEntity::EK_Variable:
1305 case InitializedEntity::EK_LambdaCapture:
1306 // No warning, might be direct-list-initialization.
1307 // FIXME: Should we warn for copy-list-initialization in these cases?
1308 break;
1309
1310 case InitializedEntity::EK_New:
1311 case InitializedEntity::EK_Temporary:
1312 case InitializedEntity::EK_CompoundLiteralInit:
1313 // No warning, braces are part of the syntax of the underlying construct.
1314 break;
1315
1316 case InitializedEntity::EK_RelatedResult:
1317 // No warning, we already warned when initializing the result.
1318 break;
1319
1320 case InitializedEntity::EK_Exception:
1321 case InitializedEntity::EK_Base:
1322 case InitializedEntity::EK_Delegating:
1323 case InitializedEntity::EK_BlockElement:
1324 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1325 case InitializedEntity::EK_Binding:
1326 case InitializedEntity::EK_StmtExprResult:
1327 llvm_unreachable("unexpected braced scalar init");
1328 }
1329
1330 if (DiagID) {
1331 S.Diag(Loc: Braces.getBegin(), DiagID)
1332 << Entity.getType()->isSizelessBuiltinType() << Braces
1333 << FixItHint::CreateRemoval(RemoveRange: Braces.getBegin())
1334 << FixItHint::CreateRemoval(RemoveRange: Braces.getEnd());
1335 }
1336}
1337
1338/// Check whether the initializer \p IList (that was written with explicit
1339/// braces) can be used to initialize an object of type \p T.
1340///
1341/// This also fills in \p StructuredList with the fully-braced, desugared
1342/// form of the initialization.
1343void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1344 InitListExpr *IList, QualType &T,
1345 InitListExpr *StructuredList,
1346 bool TopLevelObject) {
1347 unsigned Index = 0, StructuredIndex = 0;
1348 CheckListElementTypes(Entity, IList, DeclType&: T, /*SubobjectIsDesignatorContext=*/true,
1349 Index, StructuredList, StructuredIndex, TopLevelObject);
1350 if (StructuredList) {
1351 QualType ExprTy = T;
1352 if (!ExprTy->isArrayType())
1353 ExprTy = ExprTy.getNonLValueExprType(Context: SemaRef.Context);
1354 if (!VerifyOnly)
1355 IList->setType(ExprTy);
1356 StructuredList->setType(ExprTy);
1357 }
1358 if (hadError)
1359 return;
1360
1361 // Don't complain for incomplete types, since we'll get an error elsewhere.
1362 if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) {
1363 // We have leftover initializers
1364 Expr *ExtraInit =
1365 Index < IList->getNumInits() ? IList->getInit(Init: Index) : CurEmbed;
1366 SourceLocation ExtraInitLoc =
1367 ExtraInit ? ExtraInit->getBeginLoc() : IList->getEndLoc();
1368 SourceRange ExtraInitRange =
1369 ExtraInit ? ExtraInit->getSourceRange() : IList->getSourceRange();
1370 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1371 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1372 hadError = ExtraInitsIsError;
1373 if (VerifyOnly) {
1374 return;
1375 } else if (StructuredIndex == 1 && StructuredList->getNumInits() != 0 &&
1376 StructuredList->getInit(Init: 0) &&
1377 IsStringInit(init: StructuredList->getInit(Init: 0), declType: T, Context&: SemaRef.Context) ==
1378 SIF_None) {
1379 unsigned DK =
1380 ExtraInitsIsError
1381 ? diag::err_excess_initializers_in_char_array_initializer
1382 : diag::ext_excess_initializers_in_char_array_initializer;
1383 SemaRef.Diag(Loc: ExtraInitLoc, DiagID: DK) << ExtraInitRange;
1384 } else if (T->isSizelessBuiltinType()) {
1385 unsigned DK = ExtraInitsIsError
1386 ? diag::err_excess_initializers_for_sizeless_type
1387 : diag::ext_excess_initializers_for_sizeless_type;
1388 SemaRef.Diag(Loc: ExtraInitLoc, DiagID: DK) << T << ExtraInitRange;
1389 } else {
1390 int initKind = T->isArrayType() ? 0
1391 : T->isVectorType() ? 1
1392 : T->isMatrixType() ? 2
1393 : T->isScalarType() ? 3
1394 : T->isUnionType() ? 4
1395 : 5;
1396
1397 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1398 : diag::ext_excess_initializers;
1399 SemaRef.Diag(Loc: ExtraInitLoc, DiagID: DK) << initKind << ExtraInitRange;
1400 }
1401 }
1402
1403 if (!VerifyOnly) {
1404 if (T->isScalarType() && IList->getNumInits() == 1 &&
1405 !isa<InitListExpr>(Val: IList->getInit(Init: 0)))
1406 warnBracedScalarInit(S&: SemaRef, Entity, Braces: IList->getSourceRange());
1407
1408 // Warn if this is a class type that won't be an aggregate in future
1409 // versions of C++.
1410 auto *CXXRD = T->getAsCXXRecordDecl();
1411 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1412 // Don't warn if there's an equivalent default constructor that would be
1413 // used instead.
1414 bool HasEquivCtor = false;
1415 if (IList->getNumInits() == 0) {
1416 auto *CD = SemaRef.LookupDefaultConstructor(Class: CXXRD);
1417 HasEquivCtor = CD && !CD->isDeleted();
1418 }
1419
1420 if (!HasEquivCtor) {
1421 SemaRef.Diag(Loc: IList->getBeginLoc(),
1422 DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors)
1423 << IList->getSourceRange() << T;
1424 }
1425 }
1426 }
1427}
1428
1429void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1430 InitListExpr *IList,
1431 QualType &DeclType,
1432 bool SubobjectIsDesignatorContext,
1433 unsigned &Index,
1434 InitListExpr *StructuredList,
1435 unsigned &StructuredIndex,
1436 bool TopLevelObject) {
1437 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1438 // Explicitly braced initializer for complex type can be real+imaginary
1439 // parts.
1440 CheckComplexType(Entity, IList, DeclType, Index,
1441 StructuredList, StructuredIndex);
1442 } else if (DeclType->isScalarType()) {
1443 CheckScalarType(Entity, IList, DeclType, Index,
1444 StructuredList, StructuredIndex);
1445 } else if (DeclType->isVectorType()) {
1446 CheckVectorType(Entity, IList, DeclType, Index,
1447 StructuredList, StructuredIndex);
1448 } else if (DeclType->isMatrixType()) {
1449 CheckMatrixType(Entity, IList, DeclType, Index, StructuredList,
1450 StructuredIndex);
1451 } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) {
1452 auto Bases =
1453 CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1454 CXXRecordDecl::base_class_const_iterator());
1455 if (DeclType->isRecordType()) {
1456 assert(DeclType->isAggregateType() &&
1457 "non-aggregate records should be handed in CheckSubElementType");
1458 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
1459 Bases = CXXRD->bases();
1460 } else {
1461 Bases = cast<CXXRecordDecl>(Val: RD)->bases();
1462 }
1463 CheckStructUnionTypes(Entity, IList, DeclType, Bases, Field: RD->field_begin(),
1464 SubobjectIsDesignatorContext, Index, StructuredList,
1465 StructuredIndex, TopLevelObject);
1466 } else if (DeclType->isArrayType()) {
1467 llvm::APSInt Zero(
1468 SemaRef.Context.getTypeSize(T: SemaRef.Context.getSizeType()),
1469 false);
1470 CheckArrayType(Entity, IList, DeclType, elementIndex: Zero,
1471 SubobjectIsDesignatorContext, Index,
1472 StructuredList, StructuredIndex);
1473 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1474 // This type is invalid, issue a diagnostic.
1475 ++Index;
1476 if (!VerifyOnly)
1477 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type)
1478 << DeclType;
1479 hadError = true;
1480 } else if (DeclType->isReferenceType()) {
1481 CheckReferenceType(Entity, IList, DeclType, Index,
1482 StructuredList, StructuredIndex);
1483 } else if (DeclType->isObjCObjectType()) {
1484 if (!VerifyOnly)
1485 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_objc_class) << DeclType;
1486 hadError = true;
1487 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1488 DeclType->isSizelessBuiltinType()) {
1489 // Checks for scalar type are sufficient for these types too.
1490 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1491 StructuredIndex);
1492 } else if (DeclType->isDependentType()) {
1493 // C++ [over.match.class.deduct]p1.5:
1494 // brace elision is not considered for any aggregate element that has a
1495 // dependent non-array type or an array type with a value-dependent bound
1496 ++Index;
1497 assert(AggrDeductionCandidateParamTypes);
1498 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1499 } else {
1500 if (!VerifyOnly)
1501 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type)
1502 << DeclType;
1503 hadError = true;
1504 }
1505}
1506
1507void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1508 InitListExpr *IList,
1509 QualType ElemType,
1510 unsigned &Index,
1511 InitListExpr *StructuredList,
1512 unsigned &StructuredIndex,
1513 bool DirectlyDesignated) {
1514 Expr *expr = IList->getInit(Init: Index);
1515
1516 if (ElemType->isReferenceType())
1517 return CheckReferenceType(Entity, IList, DeclType: ElemType, Index,
1518 StructuredList, StructuredIndex);
1519
1520 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(Val: expr)) {
1521 if (SubInitList->getNumInits() == 1 &&
1522 IsStringInit(init: SubInitList->getInit(Init: 0), declType: ElemType, Context&: SemaRef.Context) ==
1523 SIF_None) {
1524 // FIXME: It would be more faithful and no less correct to include an
1525 // InitListExpr in the semantic form of the initializer list in this case.
1526 expr = SubInitList->getInit(Init: 0);
1527 }
1528 // Nested aggregate initialization and C++ initialization are handled later.
1529 } else if (isa<ImplicitValueInitExpr>(Val: expr)) {
1530 // This happens during template instantiation when we see an InitListExpr
1531 // that we've already checked once.
1532 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1533 "found implicit initialization for the wrong type");
1534 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1535 ++Index;
1536 return;
1537 }
1538
1539 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(Val: expr)) {
1540 // C++ [dcl.init.aggr]p2:
1541 // Each member is copy-initialized from the corresponding
1542 // initializer-clause.
1543
1544 // FIXME: Better EqualLoc?
1545 InitializationKind Kind =
1546 InitializationKind::CreateCopy(InitLoc: expr->getBeginLoc(), EqualLoc: SourceLocation());
1547
1548 // Vector elements can be initialized from other vectors in which case
1549 // we need initialization entity with a type of a vector (and not a vector
1550 // element!) initializing multiple vector elements.
1551 auto TmpEntity =
1552 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1553 ? InitializedEntity::InitializeTemporary(Type: ElemType)
1554 : Entity;
1555
1556 if (TmpEntity.getType()->isDependentType()) {
1557 // C++ [over.match.class.deduct]p1.5:
1558 // brace elision is not considered for any aggregate element that has a
1559 // dependent non-array type or an array type with a value-dependent
1560 // bound
1561 assert(AggrDeductionCandidateParamTypes);
1562
1563 // In the presence of a braced-init-list within the initializer, we should
1564 // not perform brace-elision, even if brace elision would otherwise be
1565 // applicable. For example, given:
1566 //
1567 // template <class T> struct Foo {
1568 // T t[2];
1569 // };
1570 //
1571 // Foo t = {{1, 2}};
1572 //
1573 // we don't want the (T, T) but rather (T [2]) in terms of the initializer
1574 // {{1, 2}}.
1575 if (isa<InitListExpr, DesignatedInitExpr>(Val: expr) ||
1576 !isa_and_present<ConstantArrayType>(
1577 Val: SemaRef.Context.getAsArrayType(T: ElemType))) {
1578 ++Index;
1579 AggrDeductionCandidateParamTypes->push_back(Elt: ElemType);
1580 return;
1581 }
1582 } else {
1583 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1584 /*TopLevelOfInitList*/ true);
1585 // C++14 [dcl.init.aggr]p13:
1586 // If the assignment-expression can initialize a member, the member is
1587 // initialized. Otherwise [...] brace elision is assumed
1588 //
1589 // Brace elision is never performed if the element is not an
1590 // assignment-expression.
1591 if (Seq || isa<InitListExpr>(Val: expr)) {
1592 if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) {
1593 expr = HandleEmbed(Embed, Entity);
1594 }
1595 if (!VerifyOnly) {
1596 ExprResult Result = Seq.Perform(S&: SemaRef, Entity: TmpEntity, Kind, Args: expr);
1597 if (Result.isInvalid())
1598 hadError = true;
1599
1600 UpdateStructuredListElement(StructuredList, StructuredIndex,
1601 expr: Result.getAs<Expr>());
1602 } else if (!Seq) {
1603 hadError = true;
1604 } else if (StructuredList) {
1605 UpdateStructuredListElement(StructuredList, StructuredIndex,
1606 expr: getDummyInit());
1607 }
1608 if (!CurEmbed)
1609 ++Index;
1610 if (AggrDeductionCandidateParamTypes)
1611 AggrDeductionCandidateParamTypes->push_back(Elt: ElemType);
1612 return;
1613 }
1614 }
1615
1616 // Fall through for subaggregate initialization
1617 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1618 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1619 return CheckScalarType(Entity, IList, DeclType: ElemType, Index,
1620 StructuredList, StructuredIndex);
1621 } else if (const ArrayType *arrayType =
1622 SemaRef.Context.getAsArrayType(T: ElemType)) {
1623 // arrayType can be incomplete if we're initializing a flexible
1624 // array member. There's nothing we can do with the completed
1625 // type here, though.
1626
1627 if (IsStringInit(Init: expr, AT: arrayType, Context&: SemaRef.Context) == SIF_None) {
1628 // FIXME: Should we do this checking in verify-only mode?
1629 if (!VerifyOnly)
1630 CheckStringInit(Str: expr, DeclT&: ElemType, AT: arrayType, S&: SemaRef, Entity,
1631 CheckC23ConstexprInit: SemaRef.getLangOpts().C23 &&
1632 initializingConstexprVariable(Entity));
1633 if (StructuredList)
1634 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1635 ++Index;
1636 return;
1637 }
1638
1639 // Fall through for subaggregate initialization.
1640
1641 } else {
1642 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1643 ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) &&
1644 "Unexpected type");
1645
1646 // C99 6.7.8p13:
1647 //
1648 // The initializer for a structure or union object that has
1649 // automatic storage duration shall be either an initializer
1650 // list as described below, or a single expression that has
1651 // compatible structure or union type. In the latter case, the
1652 // initial value of the object, including unnamed members, is
1653 // that of the expression.
1654 ExprResult ExprRes = expr;
1655 if (SemaRef.CheckSingleAssignmentConstraints(LHSType: ElemType, RHS&: ExprRes,
1656 Diagnose: !VerifyOnly) !=
1657 AssignConvertType::Incompatible) {
1658 if (ExprRes.isInvalid())
1659 hadError = true;
1660 else {
1661 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(E: ExprRes.get());
1662 if (ExprRes.isInvalid())
1663 hadError = true;
1664 }
1665 UpdateStructuredListElement(StructuredList, StructuredIndex,
1666 expr: ExprRes.getAs<Expr>());
1667 ++Index;
1668 return;
1669 }
1670 ExprRes.get();
1671 // Fall through for subaggregate initialization
1672 }
1673
1674 // C++ [dcl.init.aggr]p12:
1675 //
1676 // [...] Otherwise, if the member is itself a non-empty
1677 // subaggregate, brace elision is assumed and the initializer is
1678 // considered for the initialization of the first member of
1679 // the subaggregate.
1680 // OpenCL vector initializer is handled elsewhere.
1681 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1682 ElemType->isAggregateType()) {
1683 CheckImplicitInitList(Entity, ParentIList: IList, T: ElemType, Index, StructuredList,
1684 StructuredIndex);
1685 ++StructuredIndex;
1686
1687 // In C++20, brace elision is not permitted for a designated initializer.
1688 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1689 if (InOverloadResolution)
1690 hadError = true;
1691 if (!VerifyOnly) {
1692 SemaRef.Diag(Loc: expr->getBeginLoc(),
1693 DiagID: diag::ext_designated_init_brace_elision)
1694 << expr->getSourceRange()
1695 << FixItHint::CreateInsertion(InsertionLoc: expr->getBeginLoc(), Code: "{")
1696 << FixItHint::CreateInsertion(
1697 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: expr->getEndLoc()), Code: "}");
1698 }
1699 }
1700 } else {
1701 if (!VerifyOnly) {
1702 // We cannot initialize this element, so let PerformCopyInitialization
1703 // produce the appropriate diagnostic. We already checked that this
1704 // initialization will fail.
1705 ExprResult Copy =
1706 SemaRef.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: expr,
1707 /*TopLevelOfInitList=*/true);
1708 (void)Copy;
1709 assert(Copy.isInvalid() &&
1710 "expected non-aggregate initialization to fail");
1711 }
1712 hadError = true;
1713 ++Index;
1714 ++StructuredIndex;
1715 }
1716}
1717
1718void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1719 InitListExpr *IList, QualType DeclType,
1720 unsigned &Index,
1721 InitListExpr *StructuredList,
1722 unsigned &StructuredIndex) {
1723 assert(Index == 0 && "Index in explicit init list must be zero");
1724
1725 // As an extension, clang supports complex initializers, which initialize
1726 // a complex number component-wise. When an explicit initializer list for
1727 // a complex number contains two initializers, this extension kicks in:
1728 // it expects the initializer list to contain two elements convertible to
1729 // the element type of the complex type. The first element initializes
1730 // the real part, and the second element intitializes the imaginary part.
1731
1732 if (IList->getNumInits() < 2)
1733 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1734 StructuredIndex);
1735
1736 // This is an extension in C. (The builtin _Complex type does not exist
1737 // in the C++ standard.)
1738 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1739 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_complex_component_init)
1740 << IList->getSourceRange();
1741
1742 // Initialize the complex number.
1743 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1744 InitializedEntity ElementEntity =
1745 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1746
1747 for (unsigned i = 0; i < 2; ++i) {
1748 ElementEntity.setElementIndex(Index);
1749 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1750 StructuredList, StructuredIndex);
1751 }
1752}
1753
1754void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1755 InitListExpr *IList, QualType DeclType,
1756 unsigned &Index,
1757 InitListExpr *StructuredList,
1758 unsigned &StructuredIndex) {
1759 if (Index >= IList->getNumInits()) {
1760 if (!VerifyOnly) {
1761 if (SemaRef.getLangOpts().CPlusPlus) {
1762 if (DeclType->isSizelessBuiltinType())
1763 SemaRef.Diag(Loc: IList->getBeginLoc(),
1764 DiagID: SemaRef.getLangOpts().CPlusPlus11
1765 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1766 : diag::err_empty_sizeless_initializer)
1767 << DeclType << IList->getSourceRange();
1768 else
1769 SemaRef.Diag(Loc: IList->getBeginLoc(),
1770 DiagID: SemaRef.getLangOpts().CPlusPlus11
1771 ? diag::warn_cxx98_compat_empty_scalar_initializer
1772 : diag::err_empty_scalar_initializer)
1773 << IList->getSourceRange();
1774 }
1775 }
1776 hadError =
1777 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1778 ++Index;
1779 ++StructuredIndex;
1780 return;
1781 }
1782
1783 Expr *expr = IList->getInit(Init: Index);
1784 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(Val: expr)) {
1785 // FIXME: This is invalid, and accepting it causes overload resolution
1786 // to pick the wrong overload in some corner cases.
1787 if (!VerifyOnly)
1788 SemaRef.Diag(Loc: SubIList->getBeginLoc(), DiagID: diag::ext_many_braces_around_init)
1789 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1790
1791 CheckScalarType(Entity, IList: SubIList, DeclType, Index, StructuredList,
1792 StructuredIndex);
1793 return;
1794 } else if (isa<DesignatedInitExpr>(Val: expr)) {
1795 if (!VerifyOnly)
1796 SemaRef.Diag(Loc: expr->getBeginLoc(),
1797 DiagID: diag::err_designator_for_scalar_or_sizeless_init)
1798 << DeclType->isSizelessBuiltinType() << DeclType
1799 << expr->getSourceRange();
1800 hadError = true;
1801 ++Index;
1802 ++StructuredIndex;
1803 return;
1804 } else if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) {
1805 expr = HandleEmbed(Embed, Entity);
1806 }
1807
1808 ExprResult Result;
1809 if (VerifyOnly) {
1810 if (SemaRef.CanPerformCopyInitialization(Entity, Init: expr))
1811 Result = getDummyInit();
1812 else
1813 Result = ExprError();
1814 } else {
1815 Result =
1816 SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr,
1817 /*TopLevelOfInitList=*/true);
1818 }
1819
1820 Expr *ResultExpr = nullptr;
1821
1822 if (Result.isInvalid())
1823 hadError = true; // types weren't compatible.
1824 else {
1825 ResultExpr = Result.getAs<Expr>();
1826
1827 if (ResultExpr != expr && !VerifyOnly && !CurEmbed) {
1828 // The type was promoted, update initializer list.
1829 // FIXME: Why are we updating the syntactic init list?
1830 IList->setInit(Init: Index, expr: ResultExpr);
1831 }
1832 }
1833
1834 UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr);
1835 if (!CurEmbed)
1836 ++Index;
1837 if (AggrDeductionCandidateParamTypes)
1838 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1839}
1840
1841void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1842 InitListExpr *IList, QualType DeclType,
1843 unsigned &Index,
1844 InitListExpr *StructuredList,
1845 unsigned &StructuredIndex) {
1846 if (Index >= IList->getNumInits()) {
1847 // FIXME: It would be wonderful if we could point at the actual member. In
1848 // general, it would be useful to pass location information down the stack,
1849 // so that we know the location (or decl) of the "current object" being
1850 // initialized.
1851 if (!VerifyOnly)
1852 SemaRef.Diag(Loc: IList->getBeginLoc(),
1853 DiagID: diag::err_init_reference_member_uninitialized)
1854 << DeclType << IList->getSourceRange();
1855 hadError = true;
1856 ++Index;
1857 ++StructuredIndex;
1858 return;
1859 }
1860
1861 Expr *expr = IList->getInit(Init: Index);
1862 if (isa<InitListExpr>(Val: expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1863 if (!VerifyOnly)
1864 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_non_aggr_init_list)
1865 << DeclType << IList->getSourceRange();
1866 hadError = true;
1867 ++Index;
1868 ++StructuredIndex;
1869 return;
1870 }
1871
1872 ExprResult Result;
1873 if (VerifyOnly) {
1874 if (SemaRef.CanPerformCopyInitialization(Entity,Init: expr))
1875 Result = getDummyInit();
1876 else
1877 Result = ExprError();
1878 } else {
1879 Result =
1880 SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr,
1881 /*TopLevelOfInitList=*/true);
1882 }
1883
1884 if (Result.isInvalid())
1885 hadError = true;
1886
1887 expr = Result.getAs<Expr>();
1888 // FIXME: Why are we updating the syntactic init list?
1889 if (!VerifyOnly && expr)
1890 IList->setInit(Init: Index, expr);
1891
1892 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1893 ++Index;
1894 if (AggrDeductionCandidateParamTypes)
1895 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1896}
1897
1898void InitListChecker::CheckMatrixType(const InitializedEntity &Entity,
1899 InitListExpr *IList, QualType DeclType,
1900 unsigned &Index,
1901 InitListExpr *StructuredList,
1902 unsigned &StructuredIndex) {
1903 if (!SemaRef.getLangOpts().HLSL)
1904 return;
1905
1906 const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>();
1907
1908 // For HLSL, the error reporting for this case is handled in SemaHLSL's
1909 // initializer list diagnostics. That means the execution should require
1910 // getNumElementsFlattened to equal getNumInits. In other words the execution
1911 // should never reach this point if this condition is not true".
1912 assert(IList->getNumInits() == MT->getNumElementsFlattened() &&
1913 "Inits must equal Matrix element count");
1914
1915 QualType ElemTy = MT->getElementType();
1916
1917 Index = 0;
1918 InitializedEntity Element =
1919 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1920
1921 while (Index < IList->getNumInits()) {
1922 // Not a sublist: just consume directly.
1923 // Note: In HLSL, elements of the InitListExpr are in row-major order, so no
1924 // change is needed to the Index.
1925 Element.setElementIndex(Index);
1926 CheckSubElementType(Entity: Element, IList, ElemType: ElemTy, Index, StructuredList,
1927 StructuredIndex);
1928 }
1929}
1930
1931void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1932 InitListExpr *IList, QualType DeclType,
1933 unsigned &Index,
1934 InitListExpr *StructuredList,
1935 unsigned &StructuredIndex) {
1936 const VectorType *VT = DeclType->castAs<VectorType>();
1937 unsigned maxElements = VT->getNumElements();
1938 unsigned numEltsInit = 0;
1939 QualType elementType = VT->getElementType();
1940
1941 if (Index >= IList->getNumInits()) {
1942 // Make sure the element type can be value-initialized.
1943 CheckEmptyInitializable(
1944 Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity),
1945 Loc: IList->getEndLoc());
1946 return;
1947 }
1948
1949 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1950 // If the initializing element is a vector, try to copy-initialize
1951 // instead of breaking it apart (which is doomed to failure anyway).
1952 Expr *Init = IList->getInit(Init: Index);
1953 if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVectorType()) {
1954 ExprResult Result;
1955 if (VerifyOnly) {
1956 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1957 Result = getDummyInit();
1958 else
1959 Result = ExprError();
1960 } else {
1961 Result =
1962 SemaRef.PerformCopyInitialization(Entity, EqualLoc: Init->getBeginLoc(), Init,
1963 /*TopLevelOfInitList=*/true);
1964 }
1965
1966 Expr *ResultExpr = nullptr;
1967 if (Result.isInvalid())
1968 hadError = true; // types weren't compatible.
1969 else {
1970 ResultExpr = Result.getAs<Expr>();
1971
1972 if (ResultExpr != Init && !VerifyOnly) {
1973 // The type was promoted, update initializer list.
1974 // FIXME: Why are we updating the syntactic init list?
1975 IList->setInit(Init: Index, expr: ResultExpr);
1976 }
1977 }
1978 UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr);
1979 ++Index;
1980 if (AggrDeductionCandidateParamTypes)
1981 AggrDeductionCandidateParamTypes->push_back(Elt: elementType);
1982 return;
1983 }
1984
1985 InitializedEntity ElementEntity =
1986 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1987
1988 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1989 // Don't attempt to go past the end of the init list
1990 if (Index >= IList->getNumInits()) {
1991 CheckEmptyInitializable(Entity: ElementEntity, Loc: IList->getEndLoc());
1992 break;
1993 }
1994
1995 ElementEntity.setElementIndex(Index);
1996 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1997 StructuredList, StructuredIndex);
1998 }
1999
2000 if (VerifyOnly)
2001 return;
2002
2003 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
2004 const VectorType *T = Entity.getType()->castAs<VectorType>();
2005 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
2006 T->getVectorKind() == VectorKind::NeonPoly)) {
2007 // The ability to use vector initializer lists is a GNU vector extension
2008 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
2009 // endian machines it works fine, however on big endian machines it
2010 // exhibits surprising behaviour:
2011 //
2012 // uint32x2_t x = {42, 64};
2013 // return vget_lane_u32(x, 0); // Will return 64.
2014 //
2015 // Because of this, explicitly call out that it is non-portable.
2016 //
2017 SemaRef.Diag(Loc: IList->getBeginLoc(),
2018 DiagID: diag::warn_neon_vector_initializer_non_portable);
2019
2020 const char *typeCode;
2021 unsigned typeSize = SemaRef.Context.getTypeSize(T: elementType);
2022
2023 if (elementType->isFloatingType())
2024 typeCode = "f";
2025 else if (elementType->isSignedIntegerType())
2026 typeCode = "s";
2027 else if (elementType->isUnsignedIntegerType())
2028 typeCode = "u";
2029 else if (elementType->isMFloat8Type())
2030 typeCode = "mf";
2031 else
2032 llvm_unreachable("Invalid element type!");
2033
2034 SemaRef.Diag(Loc: IList->getBeginLoc(),
2035 DiagID: SemaRef.Context.getTypeSize(T: VT) > 64
2036 ? diag::note_neon_vector_initializer_non_portable_q
2037 : diag::note_neon_vector_initializer_non_portable)
2038 << typeCode << typeSize;
2039 }
2040
2041 return;
2042 }
2043
2044 InitializedEntity ElementEntity =
2045 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
2046
2047 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
2048 for (unsigned i = 0; i < maxElements; ++i) {
2049 // Don't attempt to go past the end of the init list
2050 if (Index >= IList->getNumInits())
2051 break;
2052
2053 ElementEntity.setElementIndex(Index);
2054
2055 QualType IType = IList->getInit(Init: Index)->getType();
2056 if (!IType->isVectorType()) {
2057 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
2058 StructuredList, StructuredIndex);
2059 ++numEltsInit;
2060 } else {
2061 QualType VecType;
2062 const VectorType *IVT = IType->castAs<VectorType>();
2063 unsigned numIElts = IVT->getNumElements();
2064
2065 if (IType->isExtVectorType())
2066 VecType = SemaRef.Context.getExtVectorType(VectorType: elementType, NumElts: numIElts);
2067 else
2068 VecType = SemaRef.Context.getVectorType(VectorType: elementType, NumElts: numIElts,
2069 VecKind: IVT->getVectorKind());
2070 CheckSubElementType(Entity: ElementEntity, IList, ElemType: VecType, Index,
2071 StructuredList, StructuredIndex);
2072 numEltsInit += numIElts;
2073 }
2074 }
2075
2076 // OpenCL and HLSL require all elements to be initialized.
2077 if (numEltsInit != maxElements) {
2078 if (!VerifyOnly)
2079 SemaRef.Diag(Loc: IList->getBeginLoc(),
2080 DiagID: diag::err_vector_incorrect_num_elements)
2081 << (numEltsInit < maxElements) << maxElements << numEltsInit
2082 << /*initialization*/ 0;
2083 hadError = true;
2084 }
2085}
2086
2087/// Check if the type of a class element has an accessible destructor, and marks
2088/// it referenced. Returns true if we shouldn't form a reference to the
2089/// destructor.
2090///
2091/// Aggregate initialization requires a class element's destructor be
2092/// accessible per 11.6.1 [dcl.init.aggr]:
2093///
2094/// The destructor for each element of class type is potentially invoked
2095/// (15.4 [class.dtor]) from the context where the aggregate initialization
2096/// occurs.
2097static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
2098 Sema &SemaRef) {
2099 auto *CXXRD = ElementType->getAsCXXRecordDecl();
2100 // Bail out on incomplete record types: a forward-declared class has no
2101 // destructor to look up, and `LookupDestructor` (via `LookupSpecialMember`)
2102 // asserts that the record is fully defined. Error recovery for init lists
2103 // of incomplete element types reaches this point even after the parser has
2104 // already diagnosed the incompleteness.
2105 if (!CXXRD || !CXXRD->hasDefinition())
2106 return false;
2107
2108 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Class: CXXRD);
2109 if (!Destructor)
2110 return false;
2111
2112 SemaRef.CheckDestructorAccess(Loc, Dtor: Destructor,
2113 PDiag: SemaRef.PDiag(DiagID: diag::err_access_dtor_temp)
2114 << ElementType);
2115 SemaRef.MarkFunctionReferenced(Loc, Func: Destructor);
2116 return SemaRef.DiagnoseUseOfDecl(D: Destructor, Locs: Loc);
2117}
2118
2119static bool
2120canInitializeArrayWithEmbedDataString(ArrayRef<Expr *> ExprList,
2121 const InitializedEntity &Entity,
2122 ASTContext &Context) {
2123 QualType InitType = Entity.getType();
2124 const InitializedEntity *Parent = &Entity;
2125
2126 while (Parent) {
2127 InitType = Parent->getType();
2128 Parent = Parent->getParent();
2129 }
2130
2131 // Only one initializer, it's an embed and the types match;
2132 EmbedExpr *EE =
2133 ExprList.size() == 1
2134 ? dyn_cast_if_present<EmbedExpr>(Val: ExprList[0]->IgnoreParens())
2135 : nullptr;
2136 if (!EE)
2137 return false;
2138
2139 if (InitType->isArrayType()) {
2140 const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe();
2141 StringLiteral *SL = EE->getDataStringLiteral();
2142 return IsStringInit(Init: SL, AT: InitArrayType, Context) == SIF_None;
2143 }
2144 return false;
2145}
2146
2147void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
2148 InitListExpr *IList, QualType &DeclType,
2149 llvm::APSInt elementIndex,
2150 bool SubobjectIsDesignatorContext,
2151 unsigned &Index,
2152 InitListExpr *StructuredList,
2153 unsigned &StructuredIndex) {
2154 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(T: DeclType);
2155
2156 if (!VerifyOnly) {
2157 if (checkDestructorReference(ElementType: arrayType->getElementType(),
2158 Loc: IList->getEndLoc(), SemaRef)) {
2159 hadError = true;
2160 return;
2161 }
2162 }
2163
2164 if (canInitializeArrayWithEmbedDataString(ExprList: IList->inits(), Entity,
2165 Context&: SemaRef.Context)) {
2166 EmbedExpr *Embed = cast<EmbedExpr>(Val: IList->inits()[0]);
2167 IList->setInit(Init: 0, expr: Embed->getDataStringLiteral());
2168 }
2169
2170 // Check for the special-case of initializing an array with a string.
2171 if (Index < IList->getNumInits()) {
2172 if (IsStringInit(Init: IList->getInit(Init: Index), AT: arrayType, Context&: SemaRef.Context) ==
2173 SIF_None) {
2174 // We place the string literal directly into the resulting
2175 // initializer list. This is the only place where the structure
2176 // of the structured initializer list doesn't match exactly,
2177 // because doing so would involve allocating one character
2178 // constant for each string.
2179 // FIXME: Should we do these checks in verify-only mode too?
2180 if (!VerifyOnly)
2181 CheckStringInit(
2182 Str: IList->getInit(Init: Index), DeclT&: DeclType, AT: arrayType, S&: SemaRef, Entity,
2183 CheckC23ConstexprInit: SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
2184 if (StructuredList) {
2185 UpdateStructuredListElement(StructuredList, StructuredIndex,
2186 expr: IList->getInit(Init: Index));
2187 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: StructuredIndex);
2188 }
2189 ++Index;
2190 if (AggrDeductionCandidateParamTypes)
2191 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
2192 return;
2193 }
2194 }
2195 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Val: arrayType)) {
2196 // Check for VLAs; in standard C it would be possible to check this
2197 // earlier, but I don't know where clang accepts VLAs (gcc accepts
2198 // them in all sorts of strange places).
2199 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
2200 if (!VerifyOnly) {
2201 // C23 6.7.10p4: An entity of variable length array type shall not be
2202 // initialized except by an empty initializer.
2203 //
2204 // The C extension warnings are issued from ParseBraceInitializer() and
2205 // do not need to be issued here. However, we continue to issue an error
2206 // in the case there are initializers or we are compiling C++. We allow
2207 // use of VLAs in C++, but it's not clear we want to allow {} to zero
2208 // init a VLA in C++ in all cases (such as with non-trivial constructors).
2209 // FIXME: should we allow this construct in C++ when it makes sense to do
2210 // so?
2211 if (HasErr)
2212 SemaRef.Diag(Loc: VAT->getSizeExpr()->getBeginLoc(),
2213 DiagID: diag::err_variable_object_no_init)
2214 << VAT->getSizeExpr()->getSourceRange();
2215 }
2216 hadError = HasErr;
2217 ++Index;
2218 ++StructuredIndex;
2219 return;
2220 }
2221
2222 // We might know the maximum number of elements in advance.
2223 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2224 elementIndex.isUnsigned());
2225 bool maxElementsKnown = false;
2226 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: arrayType)) {
2227 maxElements = CAT->getSize();
2228 elementIndex = elementIndex.extOrTrunc(width: maxElements.getBitWidth());
2229 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2230 maxElementsKnown = true;
2231 }
2232
2233 QualType elementType = arrayType->getElementType();
2234 while (Index < IList->getNumInits()) {
2235 Expr *Init = IList->getInit(Init: Index);
2236 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) {
2237 // If we're not the subobject that matches up with the '{' for
2238 // the designator, we shouldn't be handling the
2239 // designator. Return immediately.
2240 if (!SubobjectIsDesignatorContext)
2241 return;
2242
2243 // Handle this designated initializer. elementIndex will be
2244 // updated to be the next array element we'll initialize.
2245 if (CheckDesignatedInitializer(Entity, IList, DIE, DesigIdx: 0,
2246 CurrentObjectType&: DeclType, NextField: nullptr, NextElementIndex: &elementIndex, Index,
2247 StructuredList, StructuredIndex, FinishSubobjectInit: true,
2248 TopLevelObject: false)) {
2249 hadError = true;
2250 continue;
2251 }
2252
2253 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2254 maxElements = maxElements.extend(width: elementIndex.getBitWidth());
2255 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2256 elementIndex = elementIndex.extend(width: maxElements.getBitWidth());
2257 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2258
2259 // If the array is of incomplete type, keep track of the number of
2260 // elements in the initializer.
2261 if (!maxElementsKnown && elementIndex > maxElements)
2262 maxElements = elementIndex;
2263
2264 continue;
2265 }
2266
2267 // If we know the maximum number of elements, and we've already
2268 // hit it, stop consuming elements in the initializer list.
2269 if (maxElementsKnown && elementIndex == maxElements)
2270 break;
2271
2272 InitializedEntity ElementEntity = InitializedEntity::InitializeElement(
2273 Context&: SemaRef.Context, Index: StructuredIndex, Parent: Entity);
2274 ElementEntity.setElementIndex(elementIndex.getExtValue());
2275
2276 unsigned EmbedElementIndexBeforeInit = CurEmbedIndex;
2277 // Check this element.
2278 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
2279 StructuredList, StructuredIndex);
2280 ++elementIndex;
2281 if ((CurEmbed || isa<EmbedExpr>(Val: Init)) && elementType->isScalarType()) {
2282 if (CurEmbed) {
2283 elementIndex =
2284 elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1;
2285 } else {
2286 auto Embed = cast<EmbedExpr>(Val: Init);
2287 elementIndex = elementIndex + Embed->getDataElementCount() -
2288 EmbedElementIndexBeforeInit - 1;
2289 }
2290 }
2291
2292 // If the array is of incomplete type, keep track of the number of
2293 // elements in the initializer.
2294 if (!maxElementsKnown && elementIndex > maxElements)
2295 maxElements = elementIndex;
2296 }
2297 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2298 // If this is an incomplete array type, the actual type needs to
2299 // be calculated here.
2300 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2301 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2302 // Sizing an array implicitly to zero is not allowed by ISO C,
2303 // but is supported by GNU.
2304 SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_typecheck_zero_array_size);
2305 }
2306
2307 DeclType = SemaRef.Context.getConstantArrayType(
2308 EltTy: elementType, ArySize: maxElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
2309 }
2310 if (!hadError) {
2311 // If there are any members of the array that get value-initialized, check
2312 // that is possible. That happens if we know the bound and don't have
2313 // enough elements, or if we're performing an array new with an unknown
2314 // bound.
2315 if ((maxElementsKnown && elementIndex < maxElements) ||
2316 Entity.isVariableLengthArrayNew())
2317 CheckEmptyInitializable(
2318 Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity),
2319 Loc: IList->getEndLoc());
2320 }
2321}
2322
2323bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2324 Expr *InitExpr,
2325 FieldDecl *Field,
2326 bool TopLevelObject) {
2327 // Handle GNU flexible array initializers.
2328 unsigned FlexArrayDiag;
2329 if (isa<InitListExpr>(Val: InitExpr) &&
2330 cast<InitListExpr>(Val: InitExpr)->getNumInits() == 0) {
2331 // Empty flexible array init always allowed as an extension
2332 FlexArrayDiag = diag::ext_flexible_array_init;
2333 } else if (!TopLevelObject) {
2334 // Disallow flexible array init on non-top-level object
2335 FlexArrayDiag = diag::err_flexible_array_init;
2336 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2337 // Disallow flexible array init on anything which is not a variable.
2338 FlexArrayDiag = diag::err_flexible_array_init;
2339 } else if (cast<VarDecl>(Val: Entity.getDecl())->hasLocalStorage()) {
2340 // Disallow flexible array init on local variables.
2341 FlexArrayDiag = diag::err_flexible_array_init;
2342 } else {
2343 // Allow other cases.
2344 FlexArrayDiag = diag::ext_flexible_array_init;
2345 }
2346
2347 if (!VerifyOnly) {
2348 SemaRef.Diag(Loc: InitExpr->getBeginLoc(), DiagID: FlexArrayDiag)
2349 << InitExpr->getBeginLoc();
2350 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member)
2351 << Field;
2352 }
2353
2354 return FlexArrayDiag != diag::ext_flexible_array_init;
2355}
2356
2357static bool isInitializedStructuredList(const InitListExpr *StructuredList) {
2358 return StructuredList && StructuredList->getNumInits() == 1U;
2359}
2360
2361void InitListChecker::CheckStructUnionTypes(
2362 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2363 CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,
2364 bool SubobjectIsDesignatorContext, unsigned &Index,
2365 InitListExpr *StructuredList, unsigned &StructuredIndex,
2366 bool TopLevelObject) {
2367 const RecordDecl *RD = DeclType->getAsRecordDecl();
2368
2369 // If the record is invalid, some of it's members are invalid. To avoid
2370 // confusion, we forgo checking the initializer for the entire record.
2371 if (RD->isInvalidDecl()) {
2372 // Assume it was supposed to consume a single initializer.
2373 ++Index;
2374 hadError = true;
2375 return;
2376 }
2377
2378 if (RD->isUnion() && IList->getNumInits() == 0) {
2379 if (!VerifyOnly)
2380 for (FieldDecl *FD : RD->fields()) {
2381 QualType ET = SemaRef.Context.getBaseElementType(QT: FD->getType());
2382 if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) {
2383 hadError = true;
2384 return;
2385 }
2386 }
2387
2388 // If there's a default initializer, use it.
2389 if (isa<CXXRecordDecl>(Val: RD) &&
2390 cast<CXXRecordDecl>(Val: RD)->hasInClassInitializer()) {
2391 if (!StructuredList)
2392 return;
2393 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2394 Field != FieldEnd; ++Field) {
2395 if (Field->hasInClassInitializer() ||
2396 (Field->isAnonymousStructOrUnion() &&
2397 Field->getType()
2398 ->castAsCXXRecordDecl()
2399 ->hasInClassInitializer())) {
2400 StructuredList->setInitializedFieldInUnion(*Field);
2401 // FIXME: Actually build a CXXDefaultInitExpr?
2402 return;
2403 }
2404 }
2405 llvm_unreachable("Couldn't find in-class initializer");
2406 }
2407
2408 // Value-initialize the first member of the union that isn't an unnamed
2409 // bitfield.
2410 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2411 Field != FieldEnd; ++Field) {
2412 if (!Field->isUnnamedBitField()) {
2413 CheckEmptyInitializable(
2414 Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity),
2415 Loc: IList->getEndLoc());
2416 if (StructuredList)
2417 StructuredList->setInitializedFieldInUnion(*Field);
2418 break;
2419 }
2420 }
2421 return;
2422 }
2423
2424 bool InitializedSomething = false;
2425
2426 // If we have any base classes, they are initialized prior to the fields.
2427 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2428 auto &Base = *I;
2429 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Init: Index) : nullptr;
2430
2431 // Designated inits always initialize fields, so if we see one, all
2432 // remaining base classes have no explicit initializer.
2433 if (isa_and_nonnull<DesignatedInitExpr>(Val: Init))
2434 Init = nullptr;
2435
2436 // C++ [over.match.class.deduct]p1.6:
2437 // each non-trailing aggregate element that is a pack expansion is assumed
2438 // to correspond to no elements of the initializer list, and (1.7) a
2439 // trailing aggregate element that is a pack expansion is assumed to
2440 // correspond to all remaining elements of the initializer list (if any).
2441
2442 // C++ [over.match.class.deduct]p1.9:
2443 // ... except that additional parameter packs of the form P_j... are
2444 // inserted into the parameter list in their original aggregate element
2445 // position corresponding to each non-trailing aggregate element of
2446 // type P_j that was skipped because it was a parameter pack, and the
2447 // trailing sequence of parameters corresponding to a trailing
2448 // aggregate element that is a pack expansion (if any) is replaced
2449 // by a single parameter of the form T_n....
2450 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2451 AggrDeductionCandidateParamTypes->push_back(
2452 Elt: SemaRef.Context.getPackExpansionType(Pattern: Base.getType(), NumExpansions: std::nullopt));
2453
2454 // Trailing pack expansion
2455 if (I + 1 == E && RD->field_empty()) {
2456 if (Index < IList->getNumInits())
2457 Index = IList->getNumInits();
2458 return;
2459 }
2460
2461 continue;
2462 }
2463
2464 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2465 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2466 Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity);
2467 if (Init) {
2468 CheckSubElementType(Entity: BaseEntity, IList, ElemType: Base.getType(), Index,
2469 StructuredList, StructuredIndex);
2470 InitializedSomething = true;
2471 } else {
2472 CheckEmptyInitializable(Entity: BaseEntity, Loc: InitLoc);
2473 }
2474
2475 if (!VerifyOnly)
2476 if (checkDestructorReference(ElementType: Base.getType(), Loc: InitLoc, SemaRef)) {
2477 hadError = true;
2478 return;
2479 }
2480 }
2481
2482 // If structDecl is a forward declaration, this loop won't do
2483 // anything except look at designated initializers; That's okay,
2484 // because an error should get printed out elsewhere. It might be
2485 // worthwhile to skip over the rest of the initializer, though.
2486 RecordDecl::field_iterator FieldEnd = RD->field_end();
2487 size_t NumRecordDecls = llvm::count_if(Range: RD->decls(), P: [&](const Decl *D) {
2488 return isa<FieldDecl>(Val: D) || isa<RecordDecl>(Val: D);
2489 });
2490 bool HasDesignatedInit = false;
2491
2492 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2493
2494 while (Index < IList->getNumInits()) {
2495 Expr *Init = IList->getInit(Init: Index);
2496 SourceLocation InitLoc = Init->getBeginLoc();
2497
2498 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) {
2499 // If we're not the subobject that matches up with the '{' for
2500 // the designator, we shouldn't be handling the
2501 // designator. Return immediately.
2502 if (!SubobjectIsDesignatorContext)
2503 return;
2504
2505 HasDesignatedInit = true;
2506
2507 // Handle this designated initializer. Field will be updated to
2508 // the next field that we'll be initializing.
2509 bool DesignatedInitFailed = CheckDesignatedInitializer(
2510 Entity, IList, DIE, DesigIdx: 0, CurrentObjectType&: DeclType, NextField: &Field, NextElementIndex: nullptr, Index,
2511 StructuredList, StructuredIndex, FinishSubobjectInit: true, TopLevelObject);
2512 if (DesignatedInitFailed)
2513 hadError = true;
2514
2515 // Find the field named by the designated initializer.
2516 DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: 0);
2517 if (!VerifyOnly && D->isFieldDesignator()) {
2518 FieldDecl *F = D->getFieldDecl();
2519 InitializedFields.insert(Ptr: F);
2520 if (!DesignatedInitFailed) {
2521 QualType ET = SemaRef.Context.getBaseElementType(QT: F->getType());
2522 if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) {
2523 hadError = true;
2524 return;
2525 }
2526 }
2527 }
2528
2529 InitializedSomething = true;
2530 continue;
2531 }
2532
2533 // Check if this is an initializer of forms:
2534 //
2535 // struct foo f = {};
2536 // struct foo g = {0};
2537 //
2538 // These are okay for randomized structures. [C99 6.7.8p19]
2539 //
2540 // Also, if there is only one element in the structure, we allow something
2541 // like this, because it's really not randomized in the traditional sense.
2542 //
2543 // struct foo h = {bar};
2544 auto IsZeroInitializer = [&](const Expr *I) {
2545 if (IList->getNumInits() == 1) {
2546 if (NumRecordDecls == 1)
2547 return true;
2548 if (const auto *IL = dyn_cast<IntegerLiteral>(Val: I))
2549 return IL->getValue().isZero();
2550 }
2551 return false;
2552 };
2553
2554 // Don't allow non-designated initializers on randomized structures.
2555 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2556 if (!VerifyOnly)
2557 SemaRef.Diag(Loc: InitLoc, DiagID: diag::err_non_designated_init_used);
2558 hadError = true;
2559 break;
2560 }
2561
2562 if (Field == FieldEnd) {
2563 // We've run out of fields. We're done.
2564 break;
2565 }
2566
2567 // We've already initialized a member of a union. We can stop entirely.
2568 if (InitializedSomething && RD->isUnion())
2569 return;
2570
2571 // Stop if we've hit a flexible array member.
2572 if (Field->getType()->isIncompleteArrayType())
2573 break;
2574
2575 if (Field->isUnnamedBitField()) {
2576 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2577 ++Field;
2578 continue;
2579 }
2580
2581 // Make sure we can use this declaration.
2582 bool InvalidUse;
2583 if (VerifyOnly)
2584 InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid);
2585 else
2586 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2587 D: *Field, Locs: IList->getInit(Init: Index)->getBeginLoc());
2588 if (InvalidUse) {
2589 ++Index;
2590 ++Field;
2591 hadError = true;
2592 continue;
2593 }
2594
2595 if (!VerifyOnly) {
2596 QualType ET = SemaRef.Context.getBaseElementType(QT: Field->getType());
2597 if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) {
2598 hadError = true;
2599 return;
2600 }
2601 }
2602
2603 InitializedEntity MemberEntity =
2604 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2605 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2606 StructuredList, StructuredIndex);
2607 InitializedSomething = true;
2608 InitializedFields.insert(Ptr: *Field);
2609 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2610 // Initialize the first field within the union.
2611 StructuredList->setInitializedFieldInUnion(*Field);
2612 }
2613
2614 ++Field;
2615 }
2616
2617 // Emit warnings for missing struct field initializers.
2618 // This check is disabled for designated initializers in C.
2619 // This matches gcc behaviour.
2620 bool IsCDesignatedInitializer =
2621 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2622 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2623 !IList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) &&
2624 !IsCDesignatedInitializer) {
2625 // It is possible we have one or more unnamed bitfields remaining.
2626 // Find first (if any) named field and emit warning.
2627 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2628 : Field,
2629 end = RD->field_end();
2630 it != end; ++it) {
2631 if (HasDesignatedInit && InitializedFields.count(Ptr: *it))
2632 continue;
2633
2634 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2635 !it->getType()->isIncompleteArrayType()) {
2636 auto Diag = HasDesignatedInit
2637 ? diag::warn_missing_designated_field_initializers
2638 : diag::warn_missing_field_initializers;
2639 SemaRef.Diag(Loc: IList->getSourceRange().getEnd(), DiagID: Diag) << *it;
2640 break;
2641 }
2642 }
2643 }
2644
2645 // Check that any remaining fields can be value-initialized if we're not
2646 // building a structured list. (If we are, we'll check this later.)
2647 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2648 !Field->getType()->isIncompleteArrayType()) {
2649 for (; Field != FieldEnd && !hadError; ++Field) {
2650 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2651 CheckEmptyInitializable(
2652 Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity),
2653 Loc: IList->getEndLoc());
2654 }
2655 }
2656
2657 // Check that the types of the remaining fields have accessible destructors.
2658 if (!VerifyOnly) {
2659 // If the initializer expression has a designated initializer, check the
2660 // elements for which a designated initializer is not provided too.
2661 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2662 : Field;
2663 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2664 QualType ET = SemaRef.Context.getBaseElementType(QT: I->getType());
2665 if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) {
2666 hadError = true;
2667 return;
2668 }
2669 }
2670 }
2671
2672 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2673 Index >= IList->getNumInits())
2674 return;
2675
2676 if (CheckFlexibleArrayInit(Entity, InitExpr: IList->getInit(Init: Index), Field: *Field,
2677 TopLevelObject)) {
2678 hadError = true;
2679 ++Index;
2680 return;
2681 }
2682
2683 InitializedEntity MemberEntity =
2684 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2685
2686 if (isa<InitListExpr>(Val: IList->getInit(Init: Index)) ||
2687 AggrDeductionCandidateParamTypes)
2688 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2689 StructuredList, StructuredIndex);
2690 else
2691 CheckImplicitInitList(Entity: MemberEntity, ParentIList: IList, T: Field->getType(), Index,
2692 StructuredList, StructuredIndex);
2693
2694 if (RD->isUnion() && isInitializedStructuredList(StructuredList)) {
2695 // Initialize the first field within the union.
2696 StructuredList->setInitializedFieldInUnion(*Field);
2697 }
2698}
2699
2700/// Expand a field designator that refers to a member of an
2701/// anonymous struct or union into a series of field designators that
2702/// refers to the field within the appropriate subobject.
2703///
2704static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2705 DesignatedInitExpr *DIE,
2706 unsigned DesigIdx,
2707 IndirectFieldDecl *IndirectField) {
2708 typedef DesignatedInitExpr::Designator Designator;
2709
2710 // Build the replacement designators.
2711 SmallVector<Designator, 4> Replacements;
2712 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2713 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2714 if (PI + 1 == PE)
2715 Replacements.push_back(Elt: Designator::CreateFieldDesignator(
2716 FieldName: (IdentifierInfo *)nullptr, DotLoc: DIE->getDesignator(Idx: DesigIdx)->getDotLoc(),
2717 FieldLoc: DIE->getDesignator(Idx: DesigIdx)->getFieldLoc()));
2718 else
2719 Replacements.push_back(Elt: Designator::CreateFieldDesignator(
2720 FieldName: (IdentifierInfo *)nullptr, DotLoc: SourceLocation(), FieldLoc: SourceLocation()));
2721 assert(isa<FieldDecl>(*PI));
2722 Replacements.back().setFieldDecl(cast<FieldDecl>(Val: *PI));
2723 }
2724
2725 // Expand the current designator into the set of replacement
2726 // designators, so we have a full subobject path down to where the
2727 // member of the anonymous struct/union is actually stored.
2728 DIE->ExpandDesignator(C: SemaRef.Context, Idx: DesigIdx, First: &Replacements[0],
2729 Last: &Replacements[0] + Replacements.size());
2730}
2731
2732static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2733 DesignatedInitExpr *DIE) {
2734 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2735 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2736 for (unsigned I = 0; I < NumIndexExprs; ++I)
2737 IndexExprs[I] = DIE->getSubExpr(Idx: I + 1);
2738 return DesignatedInitExpr::Create(C: SemaRef.Context, Designators: DIE->designators(),
2739 IndexExprs,
2740 EqualOrColonLoc: DIE->getEqualOrColonLoc(),
2741 GNUSyntax: DIE->usesGNUSyntax(), Init: DIE->getInit());
2742}
2743
2744namespace {
2745
2746// Callback to only accept typo corrections that are for field members of
2747// the given struct or union.
2748class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2749 public:
2750 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2751 : Record(RD) {}
2752
2753 bool ValidateCandidate(const TypoCorrection &candidate) override {
2754 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2755 return FD && FD->getDeclContext()->getRedeclContext()->Equals(DC: Record);
2756 }
2757
2758 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2759 return std::make_unique<FieldInitializerValidatorCCC>(args&: *this);
2760 }
2761
2762 private:
2763 const RecordDecl *Record;
2764};
2765
2766} // end anonymous namespace
2767
2768/// Check the well-formedness of a C99 designated initializer.
2769///
2770/// Determines whether the designated initializer @p DIE, which
2771/// resides at the given @p Index within the initializer list @p
2772/// IList, is well-formed for a current object of type @p DeclType
2773/// (C99 6.7.8). The actual subobject that this designator refers to
2774/// within the current subobject is returned in either
2775/// @p NextField or @p NextElementIndex (whichever is appropriate).
2776///
2777/// @param IList The initializer list in which this designated
2778/// initializer occurs.
2779///
2780/// @param DIE The designated initializer expression.
2781///
2782/// @param DesigIdx The index of the current designator.
2783///
2784/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2785/// into which the designation in @p DIE should refer.
2786///
2787/// @param NextField If non-NULL and the first designator in @p DIE is
2788/// a field, this will be set to the field declaration corresponding
2789/// to the field named by the designator. On input, this is expected to be
2790/// the next field that would be initialized in the absence of designation,
2791/// if the complete object being initialized is a struct.
2792///
2793/// @param NextElementIndex If non-NULL and the first designator in @p
2794/// DIE is an array designator or GNU array-range designator, this
2795/// will be set to the last index initialized by this designator.
2796///
2797/// @param Index Index into @p IList where the designated initializer
2798/// @p DIE occurs.
2799///
2800/// @param StructuredList The initializer list expression that
2801/// describes all of the subobject initializers in the order they'll
2802/// actually be initialized.
2803///
2804/// @returns true if there was an error, false otherwise.
2805bool
2806InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2807 InitListExpr *IList,
2808 DesignatedInitExpr *DIE,
2809 unsigned DesigIdx,
2810 QualType &CurrentObjectType,
2811 RecordDecl::field_iterator *NextField,
2812 llvm::APSInt *NextElementIndex,
2813 unsigned &Index,
2814 InitListExpr *StructuredList,
2815 unsigned &StructuredIndex,
2816 bool FinishSubobjectInit,
2817 bool TopLevelObject) {
2818 if (DesigIdx == DIE->size()) {
2819 // C++20 designated initialization can result in direct-list-initialization
2820 // of the designated subobject. This is the only way that we can end up
2821 // performing direct initialization as part of aggregate initialization, so
2822 // it needs special handling.
2823 if (DIE->isDirectInit()) {
2824 Expr *Init = DIE->getInit();
2825 assert(isa<InitListExpr>(Init) &&
2826 "designator result in direct non-list initialization?");
2827 InitializationKind Kind = InitializationKind::CreateDirectList(
2828 InitLoc: DIE->getBeginLoc(), LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc());
2829 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2830 /*TopLevelOfInitList*/ true);
2831 if (StructuredList) {
2832 ExprResult Result = VerifyOnly
2833 ? getDummyInit()
2834 : Seq.Perform(S&: SemaRef, Entity, Kind, Args: Init);
2835 UpdateStructuredListElement(StructuredList, StructuredIndex,
2836 expr: Result.get());
2837 }
2838 ++Index;
2839 if (AggrDeductionCandidateParamTypes)
2840 AggrDeductionCandidateParamTypes->push_back(Elt: CurrentObjectType);
2841 return !Seq;
2842 }
2843
2844 // Check the actual initialization for the designated object type.
2845 bool prevHadError = hadError;
2846
2847 // Temporarily remove the designator expression from the
2848 // initializer list that the child calls see, so that we don't try
2849 // to re-process the designator.
2850 unsigned OldIndex = Index;
2851 auto *OldDIE =
2852 dyn_cast_if_present<DesignatedInitExpr>(Val: IList->getInit(Init: OldIndex));
2853 if (!OldDIE)
2854 OldDIE = DIE;
2855 IList->setInit(Init: OldIndex, expr: OldDIE->getInit());
2856
2857 CheckSubElementType(Entity, IList, ElemType: CurrentObjectType, Index, StructuredList,
2858 StructuredIndex, /*DirectlyDesignated=*/true);
2859
2860 // Restore the designated initializer expression in the syntactic
2861 // form of the initializer list.
2862 if (IList->getInit(Init: OldIndex) != OldDIE->getInit())
2863 OldDIE->setInit(IList->getInit(Init: OldIndex));
2864 IList->setInit(Init: OldIndex, expr: OldDIE);
2865
2866 return hadError && !prevHadError;
2867 }
2868
2869 DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: DesigIdx);
2870 bool IsFirstDesignator = (DesigIdx == 0);
2871 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2872 // Determine the structural initializer list that corresponds to the
2873 // current subobject.
2874 if (IsFirstDesignator)
2875 StructuredList = FullyStructuredList;
2876 else {
2877 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2878 StructuredList->getInit(Init: StructuredIndex) : nullptr;
2879 if (!ExistingInit && StructuredList->hasArrayFiller())
2880 ExistingInit = StructuredList->getArrayFiller();
2881
2882 if (!ExistingInit)
2883 StructuredList = getStructuredSubobjectInit(
2884 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2885 InitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2886 else if (InitListExpr *Result = dyn_cast<InitListExpr>(Val: ExistingInit))
2887 StructuredList = Result;
2888 else {
2889 // We are creating an initializer list that initializes the
2890 // subobjects of the current object, but there was already an
2891 // initialization that completely initialized the current
2892 // subobject, e.g., by a compound literal:
2893 //
2894 // struct X { int a, b; };
2895 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2896 //
2897 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2898 // designated initializer re-initializes only its current object
2899 // subobject [0].b.
2900 diagnoseInitOverride(OldInit: ExistingInit,
2901 NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2902 /*UnionOverride=*/false,
2903 /*FullyOverwritten=*/false);
2904
2905 if (!VerifyOnly) {
2906 if (DesignatedInitUpdateExpr *E =
2907 dyn_cast<DesignatedInitUpdateExpr>(Val: ExistingInit))
2908 StructuredList = E->getUpdater();
2909 else {
2910 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2911 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2912 ExistingInit, DIE->getEndLoc());
2913 StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: DIUE);
2914 StructuredList = DIUE->getUpdater();
2915 }
2916 } else {
2917 // We don't need to track the structured representation of a
2918 // designated init update of an already-fully-initialized object in
2919 // verify-only mode. The only reason we would need the structure is
2920 // to determine where the uninitialized "holes" are, and in this
2921 // case, we know there aren't any and we can't introduce any.
2922 StructuredList = nullptr;
2923 }
2924 }
2925 }
2926 }
2927
2928 if (D->isFieldDesignator()) {
2929 // C99 6.7.8p7:
2930 //
2931 // If a designator has the form
2932 //
2933 // . identifier
2934 //
2935 // then the current object (defined below) shall have
2936 // structure or union type and the identifier shall be the
2937 // name of a member of that type.
2938 RecordDecl *RD = CurrentObjectType->getAsRecordDecl();
2939 if (!RD) {
2940 SourceLocation Loc = D->getDotLoc();
2941 if (Loc.isInvalid())
2942 Loc = D->getFieldLoc();
2943 if (!VerifyOnly)
2944 SemaRef.Diag(Loc, DiagID: diag::err_field_designator_non_aggr)
2945 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2946 ++Index;
2947 return true;
2948 }
2949
2950 FieldDecl *KnownField = D->getFieldDecl();
2951 if (!KnownField) {
2952 const IdentifierInfo *FieldName = D->getFieldName();
2953 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(ClassDecl: RD, MemberOrBase: FieldName);
2954 if (auto *FD = dyn_cast_if_present<FieldDecl>(Val: VD)) {
2955 KnownField = FD;
2956 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(Val: VD)) {
2957 // In verify mode, don't modify the original.
2958 if (VerifyOnly)
2959 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2960 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IndirectField: IFD);
2961 D = DIE->getDesignator(Idx: DesigIdx);
2962 KnownField = cast<FieldDecl>(Val: *IFD->chain_begin());
2963 }
2964 if (!KnownField) {
2965 if (VerifyOnly) {
2966 ++Index;
2967 return true; // No typo correction when just trying this out.
2968 }
2969
2970 // We found a placeholder variable
2971 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(Loc: DIE->getBeginLoc(), ClassDecl: RD,
2972 Name: FieldName)) {
2973 ++Index;
2974 return true;
2975 }
2976 // Name lookup found something, but it wasn't a field.
2977 if (DeclContextLookupResult Lookup = RD->lookup(Name: FieldName);
2978 !Lookup.empty()) {
2979 SemaRef.Diag(Loc: D->getFieldLoc(), DiagID: diag::err_field_designator_nonfield)
2980 << FieldName;
2981 SemaRef.Diag(Loc: Lookup.front()->getLocation(),
2982 DiagID: diag::note_field_designator_found);
2983 ++Index;
2984 return true;
2985 }
2986
2987 // Name lookup didn't find anything.
2988 // Determine whether this was a typo for another field name.
2989 FieldInitializerValidatorCCC CCC(RD);
2990 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2991 Typo: DeclarationNameInfo(FieldName, D->getFieldLoc()),
2992 LookupKind: Sema::LookupMemberName, /*Scope=*/S: nullptr, /*SS=*/nullptr, CCC,
2993 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: RD)) {
2994 SemaRef.diagnoseTypo(
2995 Correction: Corrected,
2996 TypoDiag: SemaRef.PDiag(DiagID: diag::err_field_designator_unknown_suggest)
2997 << FieldName << CurrentObjectType);
2998 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2999 hadError = true;
3000 } else {
3001 // Typo correction didn't find anything.
3002 SourceLocation Loc = D->getFieldLoc();
3003
3004 // The loc can be invalid with a "null" designator (i.e. an anonymous
3005 // union/struct). Do our best to approximate the location.
3006 if (Loc.isInvalid())
3007 Loc = IList->getBeginLoc();
3008
3009 SemaRef.Diag(Loc, DiagID: diag::err_field_designator_unknown)
3010 << FieldName << CurrentObjectType << DIE->getSourceRange();
3011 ++Index;
3012 return true;
3013 }
3014 }
3015 }
3016
3017 unsigned NumBases = 0;
3018 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
3019 NumBases = CXXRD->getNumBases();
3020
3021 unsigned FieldIndex = NumBases;
3022
3023 for (auto *FI : RD->fields()) {
3024 if (FI->isUnnamedBitField())
3025 continue;
3026 if (declaresSameEntity(D1: KnownField, D2: FI)) {
3027 KnownField = FI;
3028 break;
3029 }
3030 ++FieldIndex;
3031 }
3032
3033 RecordDecl::field_iterator Field =
3034 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
3035
3036 // All of the fields of a union are located at the same place in
3037 // the initializer list.
3038 if (RD->isUnion()) {
3039 FieldIndex = 0;
3040 if (StructuredList) {
3041 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
3042 if (CurrentField && !declaresSameEntity(D1: CurrentField, D2: *Field)) {
3043 assert(StructuredList->getNumInits() == 1
3044 && "A union should never have more than one initializer!");
3045
3046 Expr *ExistingInit = StructuredList->getInit(Init: 0);
3047 if (ExistingInit) {
3048 // We're about to throw away an initializer, emit warning.
3049 diagnoseInitOverride(
3050 OldInit: ExistingInit, NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
3051 /*UnionOverride=*/true,
3052 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
3053 : true);
3054 }
3055
3056 // remove existing initializer
3057 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: 0);
3058 StructuredList->setInitializedFieldInUnion(nullptr);
3059 }
3060
3061 StructuredList->setInitializedFieldInUnion(*Field);
3062 }
3063 }
3064
3065 // Make sure we can use this declaration.
3066 bool InvalidUse;
3067 if (VerifyOnly)
3068 InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid);
3069 else
3070 InvalidUse = SemaRef.DiagnoseUseOfDecl(D: *Field, Locs: D->getFieldLoc());
3071 if (InvalidUse) {
3072 ++Index;
3073 return true;
3074 }
3075
3076 // C++20 [dcl.init.list]p3:
3077 // The ordered identifiers in the designators of the designated-
3078 // initializer-list shall form a subsequence of the ordered identifiers
3079 // in the direct non-static data members of T.
3080 //
3081 // Note that this is not a condition on forming the aggregate
3082 // initialization, only on actually performing initialization,
3083 // so it is not checked in VerifyOnly mode.
3084 //
3085 // FIXME: This is the only reordering diagnostic we produce, and it only
3086 // catches cases where we have a top-level field designator that jumps
3087 // backwards. This is the only such case that is reachable in an
3088 // otherwise-valid C++20 program, so is the only case that's required for
3089 // conformance, but for consistency, we should diagnose all the other
3090 // cases where a designator takes us backwards too.
3091 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
3092 NextField &&
3093 (*NextField == RD->field_end() ||
3094 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
3095 // Find the field that we just initialized.
3096 FieldDecl *PrevField = nullptr;
3097 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
3098 if (FI->isUnnamedBitField())
3099 continue;
3100 if (*NextField != RD->field_end() &&
3101 declaresSameEntity(D1: *FI, D2: **NextField))
3102 break;
3103 PrevField = *FI;
3104 }
3105
3106 const auto GenerateDesignatedInitReorderingFixit =
3107 [&](SemaBase::SemaDiagnosticBuilder &Diag) {
3108 struct ReorderInfo {
3109 int Pos{};
3110 const Expr *InitExpr{};
3111 };
3112
3113 llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{};
3114 llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{};
3115
3116 const auto *CxxRecord =
3117 IList->getSemanticForm()->getType()->getAsCXXRecordDecl();
3118
3119 for (const FieldDecl *Field : CxxRecord->fields())
3120 MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex();
3121
3122 for (const Expr *Init : IList->inits()) {
3123 if (const auto *DI =
3124 dyn_cast_if_present<DesignatedInitExpr>(Val: Init)) {
3125 // We expect only one Designator
3126 if (DI->size() != 1)
3127 return;
3128
3129 const IdentifierInfo *const FieldName =
3130 DI->getDesignator(Idx: 0)->getFieldName();
3131 // In case we have an unknown initializer in the source, not in
3132 // the record
3133 if (MemberNameInx.contains(Val: FieldName))
3134 ReorderedInitExprs.emplace_back(
3135 Args: ReorderInfo{.Pos: MemberNameInx.at(Val: FieldName), .InitExpr: Init});
3136 }
3137 }
3138
3139 llvm::sort(C&: ReorderedInitExprs,
3140 Comp: [](const ReorderInfo &A, const ReorderInfo &B) {
3141 return A.Pos < B.Pos;
3142 });
3143
3144 llvm::SmallString<128> FixedInitList{};
3145 SourceManager &SM = SemaRef.getSourceManager();
3146 const LangOptions &LangOpts = SemaRef.getLangOpts();
3147
3148 // In a derived Record, first n base-classes are initialized first.
3149 // They do not use designated init, so skip them
3150 const ArrayRef<clang::Expr *> IListInits =
3151 IList->inits().drop_front(N: CxxRecord->getNumBases());
3152 // loop over each existing expressions and apply replacement
3153 for (const auto &[OrigExpr, Repl] :
3154 llvm::zip(t: IListInits, u&: ReorderedInitExprs)) {
3155 CharSourceRange CharRange = CharSourceRange::getTokenRange(
3156 R: Repl.InitExpr->getSourceRange());
3157 const StringRef InitText =
3158 Lexer::getSourceText(Range: CharRange, SM, LangOpts);
3159
3160 Diag << FixItHint::CreateReplacement(RemoveRange: OrigExpr->getSourceRange(),
3161 Code: InitText.str());
3162 }
3163 };
3164
3165 if (PrevField &&
3166 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
3167 SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(),
3168 DiagID: diag::ext_designated_init_reordered)
3169 << KnownField << PrevField << DIE->getSourceRange();
3170
3171 unsigned OldIndex = StructuredIndex - 1;
3172 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
3173 if (Expr *PrevInit = StructuredList->getInit(Init: OldIndex)) {
3174 auto Diag = SemaRef.Diag(Loc: PrevInit->getBeginLoc(),
3175 DiagID: diag::note_previous_field_init)
3176 << PrevField << PrevInit->getSourceRange();
3177 GenerateDesignatedInitReorderingFixit(Diag);
3178 }
3179 }
3180 }
3181 }
3182
3183
3184 // Update the designator with the field declaration.
3185 if (!VerifyOnly)
3186 D->setFieldDecl(*Field);
3187
3188 // Make sure that our non-designated initializer list has space
3189 // for a subobject corresponding to this field.
3190 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
3191 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: FieldIndex + 1);
3192
3193 // This designator names a flexible array member.
3194 if (Field->getType()->isIncompleteArrayType()) {
3195 bool Invalid = false;
3196 if ((DesigIdx + 1) != DIE->size()) {
3197 // We can't designate an object within the flexible array
3198 // member (because GCC doesn't allow it).
3199 if (!VerifyOnly) {
3200 DesignatedInitExpr::Designator *NextD
3201 = DIE->getDesignator(Idx: DesigIdx + 1);
3202 SemaRef.Diag(Loc: NextD->getBeginLoc(),
3203 DiagID: diag::err_designator_into_flexible_array_member)
3204 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
3205 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member)
3206 << *Field;
3207 }
3208 Invalid = true;
3209 }
3210
3211 if (!hadError && !isa<InitListExpr>(Val: DIE->getInit()) &&
3212 !isa<StringLiteral>(Val: DIE->getInit())) {
3213 // The initializer is not an initializer list.
3214 if (!VerifyOnly) {
3215 SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(),
3216 DiagID: diag::err_flexible_array_init_needs_braces)
3217 << DIE->getInit()->getSourceRange();
3218 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member)
3219 << *Field;
3220 }
3221 Invalid = true;
3222 }
3223
3224 // Check GNU flexible array initializer.
3225 if (!Invalid && CheckFlexibleArrayInit(Entity, InitExpr: DIE->getInit(), Field: *Field,
3226 TopLevelObject))
3227 Invalid = true;
3228
3229 if (Invalid) {
3230 ++Index;
3231 return true;
3232 }
3233
3234 // Initialize the array.
3235 bool prevHadError = hadError;
3236 unsigned newStructuredIndex = FieldIndex;
3237 unsigned OldIndex = Index;
3238 IList->setInit(Init: Index, expr: DIE->getInit());
3239
3240 InitializedEntity MemberEntity =
3241 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
3242 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
3243 StructuredList, StructuredIndex&: newStructuredIndex);
3244
3245 IList->setInit(Init: OldIndex, expr: DIE);
3246 if (hadError && !prevHadError) {
3247 ++Field;
3248 ++FieldIndex;
3249 if (NextField)
3250 *NextField = Field;
3251 StructuredIndex = FieldIndex;
3252 return true;
3253 }
3254 } else {
3255 // Recurse to check later designated subobjects.
3256 QualType FieldType = Field->getType();
3257 unsigned newStructuredIndex = FieldIndex;
3258
3259 InitializedEntity MemberEntity =
3260 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
3261 if (CheckDesignatedInitializer(Entity: MemberEntity, IList, DIE, DesigIdx: DesigIdx + 1,
3262 CurrentObjectType&: FieldType, NextField: nullptr, NextElementIndex: nullptr, Index,
3263 StructuredList, StructuredIndex&: newStructuredIndex,
3264 FinishSubobjectInit, TopLevelObject: false))
3265 return true;
3266 }
3267
3268 // Find the position of the next field to be initialized in this
3269 // subobject.
3270 ++Field;
3271 ++FieldIndex;
3272
3273 // If this the first designator, our caller will continue checking
3274 // the rest of this struct/class/union subobject.
3275 if (IsFirstDesignator) {
3276 if (Field != RD->field_end() && Field->isUnnamedBitField())
3277 ++Field;
3278
3279 if (NextField)
3280 *NextField = Field;
3281
3282 StructuredIndex = FieldIndex;
3283 return false;
3284 }
3285
3286 if (!FinishSubobjectInit)
3287 return false;
3288
3289 // We've already initialized something in the union; we're done.
3290 if (RD->isUnion())
3291 return hadError;
3292
3293 // Check the remaining fields within this class/struct/union subobject.
3294 bool prevHadError = hadError;
3295
3296 auto NoBases =
3297 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
3298 CXXRecordDecl::base_class_iterator());
3299 CheckStructUnionTypes(Entity, IList, DeclType: CurrentObjectType, Bases: NoBases, Field,
3300 SubobjectIsDesignatorContext: false, Index, StructuredList, StructuredIndex&: FieldIndex);
3301 return hadError && !prevHadError;
3302 }
3303
3304 // C99 6.7.8p6:
3305 //
3306 // If a designator has the form
3307 //
3308 // [ constant-expression ]
3309 //
3310 // then the current object (defined below) shall have array
3311 // type and the expression shall be an integer constant
3312 // expression. If the array is of unknown size, any
3313 // nonnegative value is valid.
3314 //
3315 // Additionally, cope with the GNU extension that permits
3316 // designators of the form
3317 //
3318 // [ constant-expression ... constant-expression ]
3319 const ArrayType *AT = SemaRef.Context.getAsArrayType(T: CurrentObjectType);
3320 if (!AT) {
3321 if (!VerifyOnly)
3322 SemaRef.Diag(Loc: D->getLBracketLoc(), DiagID: diag::err_array_designator_non_array)
3323 << CurrentObjectType;
3324 ++Index;
3325 return true;
3326 }
3327
3328 Expr *IndexExpr = nullptr;
3329 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3330 if (D->isArrayDesignator()) {
3331 IndexExpr = DIE->getArrayIndex(D: *D);
3332 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3333 DesignatedEndIndex = DesignatedStartIndex;
3334 } else {
3335 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3336
3337 DesignatedStartIndex =
3338 DIE->getArrayRangeStart(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3339 DesignatedEndIndex =
3340 DIE->getArrayRangeEnd(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3341 IndexExpr = DIE->getArrayRangeEnd(D: *D);
3342
3343 // Codegen can't handle evaluating array range designators that have side
3344 // effects, because we replicate the AST value for each initialized element.
3345 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3346 // elements with something that has a side effect, so codegen can emit an
3347 // "error unsupported" error instead of miscompiling the app.
3348 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3349 DIE->getInit()->HasSideEffects(Ctx: SemaRef.Context) && !VerifyOnly)
3350 FullyStructuredList->sawArrayRangeDesignator();
3351 }
3352
3353 if (isa<ConstantArrayType>(Val: AT)) {
3354 llvm::APSInt MaxElements(cast<ConstantArrayType>(Val: AT)->getSize(), false);
3355 DesignatedStartIndex
3356 = DesignatedStartIndex.extOrTrunc(width: MaxElements.getBitWidth());
3357 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3358 DesignatedEndIndex
3359 = DesignatedEndIndex.extOrTrunc(width: MaxElements.getBitWidth());
3360 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3361 if (DesignatedEndIndex >= MaxElements) {
3362 if (!VerifyOnly)
3363 SemaRef.Diag(Loc: IndexExpr->getBeginLoc(),
3364 DiagID: diag::err_array_designator_too_large)
3365 << toString(I: DesignatedEndIndex, Radix: 10) << toString(I: MaxElements, Radix: 10)
3366 << IndexExpr->getSourceRange();
3367 ++Index;
3368 return true;
3369 }
3370 } else {
3371 unsigned DesignatedIndexBitWidth =
3372 ConstantArrayType::getMaxSizeBits(Context: SemaRef.Context);
3373 DesignatedStartIndex =
3374 DesignatedStartIndex.extOrTrunc(width: DesignatedIndexBitWidth);
3375 DesignatedEndIndex =
3376 DesignatedEndIndex.extOrTrunc(width: DesignatedIndexBitWidth);
3377 DesignatedStartIndex.setIsUnsigned(true);
3378 DesignatedEndIndex.setIsUnsigned(true);
3379 }
3380
3381 bool IsStringLiteralInitUpdate =
3382 StructuredList && StructuredList->isStringLiteralInit();
3383 if (IsStringLiteralInitUpdate && VerifyOnly) {
3384 // We're just verifying an update to a string literal init. We don't need
3385 // to split the string up into individual characters to do that.
3386 StructuredList = nullptr;
3387 } else if (IsStringLiteralInitUpdate) {
3388 // We're modifying a string literal init; we have to decompose the string
3389 // so we can modify the individual characters.
3390 ASTContext &Context = SemaRef.Context;
3391 Expr *SubExpr = StructuredList->getInit(Init: 0)->IgnoreParenImpCasts();
3392
3393 // Compute the character type
3394 QualType CharTy = AT->getElementType();
3395
3396 // Compute the type of the integer literals.
3397 QualType PromotedCharTy = CharTy;
3398 if (Context.isPromotableIntegerType(T: CharTy))
3399 PromotedCharTy = Context.getPromotedIntegerType(PromotableType: CharTy);
3400 unsigned PromotedCharTyWidth = Context.getTypeSize(T: PromotedCharTy);
3401
3402 if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: SubExpr)) {
3403 // Get the length of the string.
3404 uint64_t StrLen = SL->getLength();
3405 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT);
3406 CAT && CAT->getSize().ult(RHS: StrLen))
3407 StrLen = CAT->getZExtSize();
3408 StructuredList->resizeInits(Context, NumInits: StrLen);
3409
3410 // Build a literal for each character in the string, and put them into
3411 // the init list.
3412 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3413 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(I: i));
3414 Expr *Init = new (Context) IntegerLiteral(
3415 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3416 if (CharTy != PromotedCharTy)
3417 Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast,
3418 Operand: Init, BasePath: nullptr, Cat: VK_PRValue,
3419 FPO: FPOptionsOverride());
3420 StructuredList->updateInit(C: Context, Init: i, expr: Init);
3421 }
3422 } else {
3423 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(Val: SubExpr);
3424 std::string Str;
3425 Context.getObjCEncodingForType(T: E->getEncodedType(), S&: Str);
3426
3427 // Get the length of the string.
3428 uint64_t StrLen = Str.size();
3429 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT);
3430 CAT && CAT->getSize().ult(RHS: StrLen))
3431 StrLen = CAT->getZExtSize();
3432 StructuredList->resizeInits(Context, NumInits: StrLen);
3433
3434 // Build a literal for each character in the string, and put them into
3435 // the init list.
3436 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3437 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3438 Expr *Init = new (Context) IntegerLiteral(
3439 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3440 if (CharTy != PromotedCharTy)
3441 Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast,
3442 Operand: Init, BasePath: nullptr, Cat: VK_PRValue,
3443 FPO: FPOptionsOverride());
3444 StructuredList->updateInit(C: Context, Init: i, expr: Init);
3445 }
3446 }
3447 }
3448
3449 // Make sure that our non-designated initializer list has space
3450 // for a subobject corresponding to this array element.
3451 if (StructuredList &&
3452 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3453 StructuredList->resizeInits(Context: SemaRef.Context,
3454 NumInits: DesignatedEndIndex.getZExtValue() + 1);
3455
3456 // Repeatedly perform subobject initializations in the range
3457 // [DesignatedStartIndex, DesignatedEndIndex].
3458
3459 // Move to the next designator
3460 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3461 unsigned OldIndex = Index;
3462
3463 InitializedEntity ElementEntity =
3464 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
3465
3466 while (DesignatedStartIndex <= DesignatedEndIndex) {
3467 // Recurse to check later designated subobjects.
3468 QualType ElementType = AT->getElementType();
3469 Index = OldIndex;
3470
3471 ElementEntity.setElementIndex(ElementIndex);
3472 if (CheckDesignatedInitializer(
3473 Entity: ElementEntity, IList, DIE, DesigIdx: DesigIdx + 1, CurrentObjectType&: ElementType, NextField: nullptr,
3474 NextElementIndex: nullptr, Index, StructuredList, StructuredIndex&: ElementIndex,
3475 FinishSubobjectInit: FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3476 TopLevelObject: false))
3477 return true;
3478
3479 // Move to the next index in the array that we'll be initializing.
3480 ++DesignatedStartIndex;
3481 ElementIndex = DesignatedStartIndex.getZExtValue();
3482 }
3483
3484 // If this the first designator, our caller will continue checking
3485 // the rest of this array subobject.
3486 if (IsFirstDesignator) {
3487 if (NextElementIndex)
3488 *NextElementIndex = std::move(DesignatedStartIndex);
3489 StructuredIndex = ElementIndex;
3490 return false;
3491 }
3492
3493 if (!FinishSubobjectInit)
3494 return false;
3495
3496 // Check the remaining elements within this array subobject.
3497 bool prevHadError = hadError;
3498 CheckArrayType(Entity, IList, DeclType&: CurrentObjectType, elementIndex: DesignatedStartIndex,
3499 /*SubobjectIsDesignatorContext=*/false, Index,
3500 StructuredList, StructuredIndex&: ElementIndex);
3501 return hadError && !prevHadError;
3502}
3503
3504// Get the structured initializer list for a subobject of type
3505// @p CurrentObjectType.
3506InitListExpr *
3507InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3508 QualType CurrentObjectType,
3509 InitListExpr *StructuredList,
3510 unsigned StructuredIndex,
3511 SourceRange InitRange,
3512 bool IsFullyOverwritten) {
3513 if (!StructuredList)
3514 return nullptr;
3515
3516 Expr *ExistingInit = nullptr;
3517 if (StructuredIndex < StructuredList->getNumInits())
3518 ExistingInit = StructuredList->getInit(Init: StructuredIndex);
3519
3520 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(Val: ExistingInit))
3521 // There might have already been initializers for subobjects of the current
3522 // object, but a subsequent initializer list will overwrite the entirety
3523 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3524 //
3525 // struct P { char x[6]; };
3526 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3527 //
3528 // The first designated initializer is ignored, and l.x is just "f".
3529 if (!IsFullyOverwritten)
3530 return Result;
3531
3532 if (ExistingInit) {
3533 // We are creating an initializer list that initializes the
3534 // subobjects of the current object, but there was already an
3535 // initialization that completely initialized the current
3536 // subobject:
3537 //
3538 // struct X { int a, b; };
3539 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3540 //
3541 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3542 // designated initializer overwrites the [0].b initializer
3543 // from the prior initialization.
3544 //
3545 // When the existing initializer is an expression rather than an
3546 // initializer list, we cannot decompose and update it in this way.
3547 // For example:
3548 //
3549 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3550 //
3551 // This case is handled by CheckDesignatedInitializer.
3552 diagnoseInitOverride(OldInit: ExistingInit, NewInitRange: InitRange);
3553 }
3554
3555 unsigned ExpectedNumInits = 0;
3556 if (Index < IList->getNumInits()) {
3557 if (auto *Init = dyn_cast_or_null<InitListExpr>(Val: IList->getInit(Init: Index)))
3558 ExpectedNumInits = Init->getNumInits();
3559 else
3560 ExpectedNumInits = IList->getNumInits() - Index;
3561 }
3562
3563 InitListExpr *Result = createInitListExpr(
3564 CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false);
3565
3566 // Link this new initializer list into the structured initializer
3567 // lists.
3568 StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: Result);
3569 return Result;
3570}
3571
3572InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType,
3573 SourceRange InitRange,
3574 unsigned ExpectedNumInits,
3575 bool IsExplicit) {
3576 InitListExpr *Result =
3577 new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(),
3578 {}, InitRange.getEnd(), IsExplicit);
3579
3580 QualType ResultType = CurrentObjectType;
3581 if (!ResultType->isArrayType())
3582 ResultType = ResultType.getNonLValueExprType(Context: SemaRef.Context);
3583 Result->setType(ResultType);
3584
3585 // Pre-allocate storage for the structured initializer list.
3586 unsigned NumElements = 0;
3587
3588 if (const ArrayType *AType
3589 = SemaRef.Context.getAsArrayType(T: CurrentObjectType)) {
3590 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(Val: AType)) {
3591 NumElements = CAType->getZExtSize();
3592 // Simple heuristic so that we don't allocate a very large
3593 // initializer with many empty entries at the end.
3594 if (NumElements > ExpectedNumInits)
3595 NumElements = 0;
3596 }
3597 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3598 NumElements = VType->getNumElements();
3599 } else if (CurrentObjectType->isRecordType()) {
3600 NumElements = numStructUnionElements(DeclType: CurrentObjectType);
3601 } else if (CurrentObjectType->isDependentType()) {
3602 NumElements = 1;
3603 }
3604
3605 Result->reserveInits(C: SemaRef.Context, NumInits: NumElements);
3606
3607 return Result;
3608}
3609
3610/// Update the initializer at index @p StructuredIndex within the
3611/// structured initializer list to the value @p expr.
3612void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3613 unsigned &StructuredIndex,
3614 Expr *expr) {
3615 // No structured initializer list to update
3616 if (!StructuredList)
3617 return;
3618
3619 if (Expr *PrevInit = StructuredList->updateInit(C: SemaRef.Context,
3620 Init: StructuredIndex, expr)) {
3621 // This initializer overwrites a previous initializer.
3622 // No need to diagnose when `expr` is nullptr because a more relevant
3623 // diagnostic has already been issued and this diagnostic is potentially
3624 // noise.
3625 if (expr)
3626 diagnoseInitOverride(OldInit: PrevInit, NewInitRange: expr->getSourceRange());
3627 }
3628
3629 ++StructuredIndex;
3630}
3631
3632bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3633 const InitializedEntity &Entity, InitListExpr *From) {
3634 QualType Type = Entity.getType();
3635 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3636 /*TreatUnavailableAsInvalid=*/false,
3637 /*InOverloadResolution=*/true);
3638 return !Check.HadError();
3639}
3640
3641/// Check that the given Index expression is a valid array designator
3642/// value. This is essentially just a wrapper around
3643/// VerifyIntegerConstantExpression that also checks for negative values
3644/// and produces a reasonable diagnostic if there is a
3645/// failure. Returns the index expression, possibly with an implicit cast
3646/// added, on success. If everything went okay, Value will receive the
3647/// value of the constant expression.
3648static ExprResult
3649CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3650 SourceLocation Loc = Index->getBeginLoc();
3651
3652 // Make sure this is an integer constant expression.
3653 ExprResult Result =
3654 S.VerifyIntegerConstantExpression(E: Index, Result: &Value, CanFold: AllowFoldKind::Allow);
3655 if (Result.isInvalid())
3656 return Result;
3657
3658 if (Value.isSigned() && Value.isNegative())
3659 return S.Diag(Loc, DiagID: diag::err_array_designator_negative)
3660 << toString(I: Value, Radix: 10) << Index->getSourceRange();
3661
3662 Value.setIsUnsigned(true);
3663 return Result;
3664}
3665
3666ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3667 SourceLocation EqualOrColonLoc,
3668 bool GNUSyntax,
3669 ExprResult Init) {
3670 typedef DesignatedInitExpr::Designator ASTDesignator;
3671
3672 bool Invalid = false;
3673 SmallVector<ASTDesignator, 32> Designators;
3674 SmallVector<Expr *, 32> InitExpressions;
3675
3676 // Build designators and check array designator expressions.
3677 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3678 const Designator &D = Desig.getDesignator(Idx);
3679
3680 if (D.isFieldDesignator()) {
3681 Designators.push_back(Elt: ASTDesignator::CreateFieldDesignator(
3682 FieldName: D.getFieldDecl(), DotLoc: D.getDotLoc(), FieldLoc: D.getFieldLoc()));
3683 } else if (D.isArrayDesignator()) {
3684 Expr *Index = D.getArrayIndex();
3685 llvm::APSInt IndexValue;
3686 if (!Index->isTypeDependent() && !Index->isValueDependent())
3687 Index = CheckArrayDesignatorExpr(S&: *this, Index, Value&: IndexValue).get();
3688 if (!Index)
3689 Invalid = true;
3690 else {
3691 Designators.push_back(Elt: ASTDesignator::CreateArrayDesignator(
3692 Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), RBracketLoc: D.getRBracketLoc()));
3693 InitExpressions.push_back(Elt: Index);
3694 }
3695 } else if (D.isArrayRangeDesignator()) {
3696 Expr *StartIndex = D.getArrayRangeStart();
3697 Expr *EndIndex = D.getArrayRangeEnd();
3698 llvm::APSInt StartValue;
3699 llvm::APSInt EndValue;
3700 bool StartDependent = StartIndex->isTypeDependent() ||
3701 StartIndex->isValueDependent();
3702 bool EndDependent = EndIndex->isTypeDependent() ||
3703 EndIndex->isValueDependent();
3704 if (!StartDependent)
3705 StartIndex =
3706 CheckArrayDesignatorExpr(S&: *this, Index: StartIndex, Value&: StartValue).get();
3707 if (!EndDependent)
3708 EndIndex = CheckArrayDesignatorExpr(S&: *this, Index: EndIndex, Value&: EndValue).get();
3709
3710 if (!StartIndex || !EndIndex)
3711 Invalid = true;
3712 else {
3713 // Make sure we're comparing values with the same bit width.
3714 if (StartDependent || EndDependent) {
3715 // Nothing to compute.
3716 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3717 EndValue = EndValue.extend(width: StartValue.getBitWidth());
3718 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3719 StartValue = StartValue.extend(width: EndValue.getBitWidth());
3720
3721 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3722 Diag(Loc: D.getEllipsisLoc(), DiagID: diag::err_array_designator_empty_range)
3723 << toString(I: StartValue, Radix: 10) << toString(I: EndValue, Radix: 10)
3724 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3725 Invalid = true;
3726 } else {
3727 Designators.push_back(Elt: ASTDesignator::CreateArrayRangeDesignator(
3728 Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), EllipsisLoc: D.getEllipsisLoc(),
3729 RBracketLoc: D.getRBracketLoc()));
3730 InitExpressions.push_back(Elt: StartIndex);
3731 InitExpressions.push_back(Elt: EndIndex);
3732 }
3733 }
3734 }
3735 }
3736
3737 if (Invalid || Init.isInvalid())
3738 return ExprError();
3739
3740 return DesignatedInitExpr::Create(C: Context, Designators, IndexExprs: InitExpressions,
3741 EqualOrColonLoc, GNUSyntax,
3742 Init: Init.getAs<Expr>());
3743}
3744
3745//===----------------------------------------------------------------------===//
3746// Initialization entity
3747//===----------------------------------------------------------------------===//
3748
3749InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3750 const InitializedEntity &Parent)
3751 : Parent(&Parent), Index(Index)
3752{
3753 if (const ArrayType *AT = Context.getAsArrayType(T: Parent.getType())) {
3754 Kind = EK_ArrayElement;
3755 Type = AT->getElementType();
3756 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3757 Kind = EK_VectorElement;
3758 Type = VT->getElementType();
3759 } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) {
3760 Kind = EK_MatrixElement;
3761 Type = MT->getElementType();
3762 } else {
3763 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3764 assert(CT && "Unexpected type");
3765 Kind = EK_ComplexElement;
3766 Type = CT->getElementType();
3767 }
3768}
3769
3770InitializedEntity
3771InitializedEntity::InitializeBase(ASTContext &Context,
3772 const CXXBaseSpecifier *Base,
3773 bool IsInheritedVirtualBase,
3774 const InitializedEntity *Parent) {
3775 InitializedEntity Result;
3776 Result.Kind = EK_Base;
3777 Result.Parent = Parent;
3778 Result.Base = {Base, IsInheritedVirtualBase};
3779 Result.Type = Base->getType();
3780 return Result;
3781}
3782
3783DeclarationName InitializedEntity::getName() const {
3784 switch (getKind()) {
3785 case EK_Parameter:
3786 case EK_Parameter_CF_Audited: {
3787 ParmVarDecl *D = Parameter.getPointer();
3788 return (D ? D->getDeclName() : DeclarationName());
3789 }
3790
3791 case EK_Variable:
3792 case EK_Member:
3793 case EK_ParenAggInitMember:
3794 case EK_Binding:
3795 case EK_TemplateParameter:
3796 return Variable.VariableOrMember->getDeclName();
3797
3798 case EK_LambdaCapture:
3799 return DeclarationName(Capture.VarID);
3800
3801 case EK_Result:
3802 case EK_StmtExprResult:
3803 case EK_Exception:
3804 case EK_New:
3805 case EK_Temporary:
3806 case EK_Base:
3807 case EK_Delegating:
3808 case EK_ArrayElement:
3809 case EK_VectorElement:
3810 case EK_MatrixElement:
3811 case EK_ComplexElement:
3812 case EK_BlockElement:
3813 case EK_LambdaToBlockConversionBlockElement:
3814 case EK_CompoundLiteralInit:
3815 case EK_RelatedResult:
3816 return DeclarationName();
3817 }
3818
3819 llvm_unreachable("Invalid EntityKind!");
3820}
3821
3822ValueDecl *InitializedEntity::getDecl() const {
3823 switch (getKind()) {
3824 case EK_Variable:
3825 case EK_Member:
3826 case EK_ParenAggInitMember:
3827 case EK_Binding:
3828 case EK_TemplateParameter:
3829 return cast<ValueDecl>(Val: Variable.VariableOrMember);
3830
3831 case EK_Parameter:
3832 case EK_Parameter_CF_Audited:
3833 return Parameter.getPointer();
3834
3835 case EK_Result:
3836 case EK_StmtExprResult:
3837 case EK_Exception:
3838 case EK_New:
3839 case EK_Temporary:
3840 case EK_Base:
3841 case EK_Delegating:
3842 case EK_ArrayElement:
3843 case EK_VectorElement:
3844 case EK_MatrixElement:
3845 case EK_ComplexElement:
3846 case EK_BlockElement:
3847 case EK_LambdaToBlockConversionBlockElement:
3848 case EK_LambdaCapture:
3849 case EK_CompoundLiteralInit:
3850 case EK_RelatedResult:
3851 return nullptr;
3852 }
3853
3854 llvm_unreachable("Invalid EntityKind!");
3855}
3856
3857bool InitializedEntity::allowsNRVO() const {
3858 switch (getKind()) {
3859 case EK_Result:
3860 case EK_Exception:
3861 return LocAndNRVO.NRVO == NRVOKind::Allowed;
3862
3863 case EK_StmtExprResult:
3864 case EK_Variable:
3865 case EK_Parameter:
3866 case EK_Parameter_CF_Audited:
3867 case EK_TemplateParameter:
3868 case EK_Member:
3869 case EK_ParenAggInitMember:
3870 case EK_Binding:
3871 case EK_New:
3872 case EK_Temporary:
3873 case EK_CompoundLiteralInit:
3874 case EK_Base:
3875 case EK_Delegating:
3876 case EK_ArrayElement:
3877 case EK_VectorElement:
3878 case EK_MatrixElement:
3879 case EK_ComplexElement:
3880 case EK_BlockElement:
3881 case EK_LambdaToBlockConversionBlockElement:
3882 case EK_LambdaCapture:
3883 case EK_RelatedResult:
3884 break;
3885 }
3886
3887 return false;
3888}
3889
3890unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3891 assert(getParent() != this);
3892 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3893 for (unsigned I = 0; I != Depth; ++I)
3894 OS << "`-";
3895
3896 switch (getKind()) {
3897 case EK_Variable: OS << "Variable"; break;
3898 case EK_Parameter: OS << "Parameter"; break;
3899 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3900 break;
3901 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3902 case EK_Result: OS << "Result"; break;
3903 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3904 case EK_Exception: OS << "Exception"; break;
3905 case EK_Member:
3906 case EK_ParenAggInitMember:
3907 OS << "Member";
3908 break;
3909 case EK_Binding: OS << "Binding"; break;
3910 case EK_New: OS << "New"; break;
3911 case EK_Temporary: OS << "Temporary"; break;
3912 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3913 case EK_RelatedResult: OS << "RelatedResult"; break;
3914 case EK_Base: OS << "Base"; break;
3915 case EK_Delegating: OS << "Delegating"; break;
3916 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3917 case EK_VectorElement: OS << "VectorElement " << Index; break;
3918 case EK_MatrixElement:
3919 OS << "MatrixElement " << Index;
3920 break;
3921 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3922 case EK_BlockElement: OS << "Block"; break;
3923 case EK_LambdaToBlockConversionBlockElement:
3924 OS << "Block (lambda)";
3925 break;
3926 case EK_LambdaCapture:
3927 OS << "LambdaCapture ";
3928 OS << DeclarationName(Capture.VarID);
3929 break;
3930 }
3931
3932 if (auto *D = getDecl()) {
3933 OS << " ";
3934 D->printQualifiedName(OS);
3935 }
3936
3937 OS << " '" << getType() << "'\n";
3938
3939 return Depth + 1;
3940}
3941
3942LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3943 dumpImpl(OS&: llvm::errs());
3944}
3945
3946//===----------------------------------------------------------------------===//
3947// Initialization sequence
3948//===----------------------------------------------------------------------===//
3949
3950void InitializationSequence::Step::Destroy() {
3951 switch (Kind) {
3952 case SK_ResolveAddressOfOverloadedFunction:
3953 case SK_CastDerivedToBasePRValue:
3954 case SK_CastDerivedToBaseXValue:
3955 case SK_CastDerivedToBaseLValue:
3956 case SK_BindReference:
3957 case SK_BindReferenceToTemporary:
3958 case SK_FinalCopy:
3959 case SK_ExtraneousCopyToTemporary:
3960 case SK_UserConversion:
3961 case SK_QualificationConversionPRValue:
3962 case SK_QualificationConversionXValue:
3963 case SK_QualificationConversionLValue:
3964 case SK_FunctionReferenceConversion:
3965 case SK_AtomicConversion:
3966 case SK_ListInitialization:
3967 case SK_UnwrapInitList:
3968 case SK_RewrapInitList:
3969 case SK_ConstructorInitialization:
3970 case SK_ConstructorInitializationFromList:
3971 case SK_ZeroInitialization:
3972 case SK_CAssignment:
3973 case SK_StringInit:
3974 case SK_ObjCObjectConversion:
3975 case SK_ArrayLoopIndex:
3976 case SK_ArrayLoopInit:
3977 case SK_ArrayInit:
3978 case SK_GNUArrayInit:
3979 case SK_ParenthesizedArrayInit:
3980 case SK_PassByIndirectCopyRestore:
3981 case SK_PassByIndirectRestore:
3982 case SK_ProduceObjCObject:
3983 case SK_StdInitializerList:
3984 case SK_StdInitializerListConstructorCall:
3985 case SK_OCLSamplerInit:
3986 case SK_OCLZeroOpaqueType:
3987 case SK_ParenthesizedListInit:
3988 case SK_HLSLBufferConversion:
3989 break;
3990
3991 case SK_ConversionSequence:
3992 case SK_ConversionSequenceNoNarrowing:
3993 delete ICS;
3994 }
3995}
3996
3997bool InitializationSequence::isDirectReferenceBinding() const {
3998 // There can be some lvalue adjustments after the SK_BindReference step.
3999 for (const Step &S : llvm::reverse(C: Steps)) {
4000 if (S.Kind == SK_BindReference)
4001 return true;
4002 if (S.Kind == SK_BindReferenceToTemporary)
4003 return false;
4004 }
4005 return false;
4006}
4007
4008bool InitializationSequence::isAmbiguous() const {
4009 if (!Failed())
4010 return false;
4011
4012 switch (getFailureKind()) {
4013 case FK_TooManyInitsForReference:
4014 case FK_ParenthesizedListInitForReference:
4015 case FK_ArrayNeedsInitList:
4016 case FK_ArrayNeedsInitListOrStringLiteral:
4017 case FK_ArrayNeedsInitListOrWideStringLiteral:
4018 case FK_NarrowStringIntoWideCharArray:
4019 case FK_WideStringIntoCharArray:
4020 case FK_IncompatWideStringIntoWideChar:
4021 case FK_PlainStringIntoUTF8Char:
4022 case FK_UTF8StringIntoPlainChar:
4023 case FK_AddressOfOverloadFailed: // FIXME: Could do better
4024 case FK_NonConstLValueReferenceBindingToTemporary:
4025 case FK_NonConstLValueReferenceBindingToBitfield:
4026 case FK_NonConstLValueReferenceBindingToVectorElement:
4027 case FK_NonConstLValueReferenceBindingToMatrixElement:
4028 case FK_NonConstLValueReferenceBindingToUnrelated:
4029 case FK_RValueReferenceBindingToLValue:
4030 case FK_ReferenceAddrspaceMismatchTemporary:
4031 case FK_ReferenceInitDropsQualifiers:
4032 case FK_ReferenceInitFailed:
4033 case FK_ConversionFailed:
4034 case FK_ConversionFromPropertyFailed:
4035 case FK_TooManyInitsForScalar:
4036 case FK_ParenthesizedListInitForScalar:
4037 case FK_ReferenceBindingToInitList:
4038 case FK_InitListBadDestinationType:
4039 case FK_DefaultInitOfConst:
4040 case FK_Incomplete:
4041 case FK_ArrayTypeMismatch:
4042 case FK_NonConstantArrayInit:
4043 case FK_ListInitializationFailed:
4044 case FK_VariableLengthArrayHasInitializer:
4045 case FK_PlaceholderType:
4046 case FK_ExplicitConstructor:
4047 case FK_AddressOfUnaddressableFunction:
4048 case FK_ParenthesizedListInitFailed:
4049 case FK_DesignatedInitForNonAggregate:
4050 case FK_HLSLInitListFlatteningFailed:
4051 return false;
4052
4053 case FK_ReferenceInitOverloadFailed:
4054 case FK_UserConversionOverloadFailed:
4055 case FK_ConstructorOverloadFailed:
4056 case FK_ListConstructorOverloadFailed:
4057 return FailedOverloadResult == OR_Ambiguous;
4058 }
4059
4060 llvm_unreachable("Invalid EntityKind!");
4061}
4062
4063bool InitializationSequence::isConstructorInitialization() const {
4064 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
4065}
4066
4067void
4068InitializationSequence
4069::AddAddressOverloadResolutionStep(FunctionDecl *Function,
4070 DeclAccessPair Found,
4071 bool HadMultipleCandidates) {
4072 Step S;
4073 S.Kind = SK_ResolveAddressOfOverloadedFunction;
4074 S.Type = Function->getType();
4075 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4076 S.Function.Function = Function;
4077 S.Function.FoundDecl = Found;
4078 Steps.push_back(Elt: S);
4079}
4080
4081void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
4082 ExprValueKind VK) {
4083 Step S;
4084 switch (VK) {
4085 case VK_PRValue:
4086 S.Kind = SK_CastDerivedToBasePRValue;
4087 break;
4088 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
4089 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
4090 }
4091 S.Type = BaseType;
4092 Steps.push_back(Elt: S);
4093}
4094
4095void InitializationSequence::AddReferenceBindingStep(QualType T,
4096 bool BindingTemporary) {
4097 Step S;
4098 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
4099 S.Type = T;
4100 Steps.push_back(Elt: S);
4101}
4102
4103void InitializationSequence::AddFinalCopy(QualType T) {
4104 Step S;
4105 S.Kind = SK_FinalCopy;
4106 S.Type = T;
4107 Steps.push_back(Elt: S);
4108}
4109
4110void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
4111 Step S;
4112 S.Kind = SK_ExtraneousCopyToTemporary;
4113 S.Type = T;
4114 Steps.push_back(Elt: S);
4115}
4116
4117void
4118InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
4119 DeclAccessPair FoundDecl,
4120 QualType T,
4121 bool HadMultipleCandidates) {
4122 Step S;
4123 S.Kind = SK_UserConversion;
4124 S.Type = T;
4125 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4126 S.Function.Function = Function;
4127 S.Function.FoundDecl = FoundDecl;
4128 Steps.push_back(Elt: S);
4129}
4130
4131void InitializationSequence::AddQualificationConversionStep(QualType Ty,
4132 ExprValueKind VK) {
4133 Step S;
4134 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
4135 switch (VK) {
4136 case VK_PRValue:
4137 S.Kind = SK_QualificationConversionPRValue;
4138 break;
4139 case VK_XValue:
4140 S.Kind = SK_QualificationConversionXValue;
4141 break;
4142 case VK_LValue:
4143 S.Kind = SK_QualificationConversionLValue;
4144 break;
4145 }
4146 S.Type = Ty;
4147 Steps.push_back(Elt: S);
4148}
4149
4150void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
4151 Step S;
4152 S.Kind = SK_FunctionReferenceConversion;
4153 S.Type = Ty;
4154 Steps.push_back(Elt: S);
4155}
4156
4157void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
4158 Step S;
4159 S.Kind = SK_AtomicConversion;
4160 S.Type = Ty;
4161 Steps.push_back(Elt: S);
4162}
4163
4164void InitializationSequence::AddConversionSequenceStep(
4165 const ImplicitConversionSequence &ICS, QualType T,
4166 bool TopLevelOfInitList) {
4167 Step S;
4168 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
4169 : SK_ConversionSequence;
4170 S.Type = T;
4171 S.ICS = new ImplicitConversionSequence(ICS);
4172 Steps.push_back(Elt: S);
4173}
4174
4175void InitializationSequence::AddListInitializationStep(QualType T) {
4176 Step S;
4177 S.Kind = SK_ListInitialization;
4178 S.Type = T;
4179 Steps.push_back(Elt: S);
4180}
4181
4182void InitializationSequence::AddConstructorInitializationStep(
4183 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
4184 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
4185 Step S;
4186 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
4187 : SK_ConstructorInitializationFromList
4188 : SK_ConstructorInitialization;
4189 S.Type = T;
4190 S.Function.HadMultipleCandidates = HadMultipleCandidates;
4191 S.Function.Function = Constructor;
4192 S.Function.FoundDecl = FoundDecl;
4193 Steps.push_back(Elt: S);
4194}
4195
4196void InitializationSequence::AddZeroInitializationStep(QualType T) {
4197 Step S;
4198 S.Kind = SK_ZeroInitialization;
4199 S.Type = T;
4200 Steps.push_back(Elt: S);
4201}
4202
4203void InitializationSequence::AddCAssignmentStep(QualType T) {
4204 Step S;
4205 S.Kind = SK_CAssignment;
4206 S.Type = T;
4207 Steps.push_back(Elt: S);
4208}
4209
4210void InitializationSequence::AddStringInitStep(QualType T) {
4211 Step S;
4212 S.Kind = SK_StringInit;
4213 S.Type = T;
4214 Steps.push_back(Elt: S);
4215}
4216
4217void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
4218 Step S;
4219 S.Kind = SK_ObjCObjectConversion;
4220 S.Type = T;
4221 Steps.push_back(Elt: S);
4222}
4223
4224void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
4225 Step S;
4226 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
4227 S.Type = T;
4228 Steps.push_back(Elt: S);
4229}
4230
4231void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
4232 Step S;
4233 S.Kind = SK_ArrayLoopIndex;
4234 S.Type = EltT;
4235 Steps.insert(I: Steps.begin(), Elt: S);
4236
4237 S.Kind = SK_ArrayLoopInit;
4238 S.Type = T;
4239 Steps.push_back(Elt: S);
4240}
4241
4242void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
4243 Step S;
4244 S.Kind = SK_ParenthesizedArrayInit;
4245 S.Type = T;
4246 Steps.push_back(Elt: S);
4247}
4248
4249void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
4250 bool shouldCopy) {
4251 Step s;
4252 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
4253 : SK_PassByIndirectRestore);
4254 s.Type = type;
4255 Steps.push_back(Elt: s);
4256}
4257
4258void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
4259 Step S;
4260 S.Kind = SK_ProduceObjCObject;
4261 S.Type = T;
4262 Steps.push_back(Elt: S);
4263}
4264
4265void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
4266 Step S;
4267 S.Kind = SK_StdInitializerList;
4268 S.Type = T;
4269 Steps.push_back(Elt: S);
4270}
4271
4272void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
4273 Step S;
4274 S.Kind = SK_OCLSamplerInit;
4275 S.Type = T;
4276 Steps.push_back(Elt: S);
4277}
4278
4279void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
4280 Step S;
4281 S.Kind = SK_OCLZeroOpaqueType;
4282 S.Type = T;
4283 Steps.push_back(Elt: S);
4284}
4285
4286void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
4287 Step S;
4288 S.Kind = SK_ParenthesizedListInit;
4289 S.Type = T;
4290 Steps.push_back(Elt: S);
4291}
4292
4293void InitializationSequence::AddUnwrapInitListInitStep(
4294 InitListExpr *Syntactic) {
4295 assert(Syntactic->getNumInits() == 1 &&
4296 "Can only unwrap trivial init lists.");
4297 Step S;
4298 S.Kind = SK_UnwrapInitList;
4299 S.Type = Syntactic->getInit(Init: 0)->getType();
4300 Steps.insert(I: Steps.begin(), Elt: S);
4301}
4302
4303void InitializationSequence::RewrapReferenceInitList(QualType T,
4304 InitListExpr *Syntactic) {
4305 assert(Syntactic->getNumInits() == 1 &&
4306 "Can only rewrap trivial init lists.");
4307 Step S;
4308 S.Kind = SK_UnwrapInitList;
4309 S.Type = Syntactic->getInit(Init: 0)->getType();
4310 Steps.insert(I: Steps.begin(), Elt: S);
4311
4312 S.Kind = SK_RewrapInitList;
4313 S.Type = T;
4314 S.WrappingSyntacticList = Syntactic;
4315 Steps.push_back(Elt: S);
4316}
4317
4318void InitializationSequence::AddHLSLBufferConversionStep(QualType T) {
4319 Step S;
4320 S.Kind = SK_HLSLBufferConversion;
4321 S.Type = T;
4322 Steps.push_back(Elt: S);
4323}
4324
4325void InitializationSequence::SetOverloadFailure(FailureKind Failure,
4326 OverloadingResult Result) {
4327 setSequenceKind(FailedSequence);
4328 this->Failure = Failure;
4329 this->FailedOverloadResult = Result;
4330}
4331
4332//===----------------------------------------------------------------------===//
4333// Attempt initialization
4334//===----------------------------------------------------------------------===//
4335
4336/// Tries to add a zero initializer. Returns true if that worked.
4337static bool
4338maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
4339 const InitializedEntity &Entity) {
4340 if (Entity.getKind() != InitializedEntity::EK_Variable)
4341 return false;
4342
4343 VarDecl *VD = cast<VarDecl>(Val: Entity.getDecl());
4344 if (VD->getInit() || VD->getEndLoc().isMacroID())
4345 return false;
4346
4347 QualType VariableTy = VD->getType().getCanonicalType();
4348 SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc());
4349 std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc);
4350 if (!Init.empty()) {
4351 Sequence.AddZeroInitializationStep(T: Entity.getType());
4352 Sequence.SetZeroInitializationFixit(Fixit: Init, L: Loc);
4353 return true;
4354 }
4355 return false;
4356}
4357
4358static void MaybeProduceObjCObject(Sema &S,
4359 InitializationSequence &Sequence,
4360 const InitializedEntity &Entity) {
4361 if (!S.getLangOpts().ObjCAutoRefCount) return;
4362
4363 /// When initializing a parameter, produce the value if it's marked
4364 /// __attribute__((ns_consumed)).
4365 if (Entity.isParameterKind()) {
4366 if (!Entity.isParameterConsumed())
4367 return;
4368
4369 assert(Entity.getType()->isObjCRetainableType() &&
4370 "consuming an object of unretainable type?");
4371 Sequence.AddProduceObjCObjectStep(T: Entity.getType());
4372
4373 /// When initializing a return value, if the return type is a
4374 /// retainable type, then returns need to immediately retain the
4375 /// object. If an autorelease is required, it will be done at the
4376 /// last instant.
4377 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4378 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
4379 if (!Entity.getType()->isObjCRetainableType())
4380 return;
4381
4382 Sequence.AddProduceObjCObjectStep(T: Entity.getType());
4383 }
4384}
4385
4386/// Initialize an array from another array
4387static void TryArrayCopy(Sema &S, const InitializationKind &Kind,
4388 const InitializedEntity &Entity, Expr *Initializer,
4389 QualType DestType, InitializationSequence &Sequence,
4390 bool TreatUnavailableAsInvalid) {
4391 // If source is a prvalue, use it directly.
4392 if (Initializer->isPRValue()) {
4393 Sequence.AddArrayInitStep(T: DestType, /*IsGNUExtension*/ false);
4394 return;
4395 }
4396
4397 // Emit element-at-a-time copy loop.
4398 InitializedEntity Element =
4399 InitializedEntity::InitializeElement(Context&: S.Context, Index: 0, Parent: Entity);
4400 QualType InitEltT =
4401 S.Context.getAsArrayType(T: Initializer->getType())->getElementType();
4402
4403 // FIXME: Here's a functional memory leak cuz we don't have a temporary
4404 // allocator at the moment
4405 OpaqueValueExpr *OVE = new (S.Context) OpaqueValueExpr(
4406 Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(),
4407 Initializer->getObjectKind());
4408 Expr *OVEAsExpr = OVE;
4409 Sequence.InitializeFrom(S, Entity: Element, Kind, Args: OVEAsExpr,
4410 /*TopLevelOfInitList*/ false,
4411 TreatUnavailableAsInvalid);
4412 if (Sequence)
4413 Sequence.AddArrayInitLoopStep(T: Entity.getType(), EltT: InitEltT);
4414}
4415
4416static void TryListInitialization(Sema &S,
4417 const InitializedEntity &Entity,
4418 const InitializationKind &Kind,
4419 InitListExpr *InitList,
4420 InitializationSequence &Sequence,
4421 bool TreatUnavailableAsInvalid);
4422
4423/// When initializing from init list via constructor, handle
4424/// initialization of an object of type std::initializer_list<T>.
4425///
4426/// \return true if we have handled initialization of an object of type
4427/// std::initializer_list<T>, false otherwise.
4428static bool TryInitializerListConstruction(Sema &S,
4429 InitListExpr *List,
4430 QualType DestType,
4431 InitializationSequence &Sequence,
4432 bool TreatUnavailableAsInvalid) {
4433 QualType E;
4434 if (!S.isStdInitializerList(Ty: DestType, Element: &E))
4435 return false;
4436
4437 if (!S.isCompleteType(Loc: List->getExprLoc(), T: E)) {
4438 Sequence.setIncompleteTypeFailure(E);
4439 return true;
4440 }
4441
4442 // Try initializing a temporary array from the init list.
4443 QualType ArrayType = S.Context.getConstantArrayType(
4444 EltTy: E.withConst(),
4445 ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()),
4446 List->getNumInitsWithEmbedExpanded()),
4447 SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0);
4448 InitializedEntity HiddenArray =
4449 InitializedEntity::InitializeTemporary(Type: ArrayType);
4450 InitializationKind Kind = InitializationKind::CreateDirectList(
4451 InitLoc: List->getExprLoc(), LBraceLoc: List->getBeginLoc(), RBraceLoc: List->getEndLoc());
4452 TryListInitialization(S, Entity: HiddenArray, Kind, InitList: List, Sequence,
4453 TreatUnavailableAsInvalid);
4454 if (Sequence)
4455 Sequence.AddStdInitializerListConstructionStep(T: DestType);
4456 return true;
4457}
4458
4459/// Determine if the constructor has the signature of a copy or move
4460/// constructor for the type T of the class in which it was found. That is,
4461/// determine if its first parameter is of type T or reference to (possibly
4462/// cv-qualified) T.
4463static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
4464 const ConstructorInfo &Info) {
4465 if (Info.Constructor->getNumParams() == 0)
4466 return false;
4467
4468 QualType ParmT =
4469 Info.Constructor->getParamDecl(i: 0)->getType().getNonReferenceType();
4470 CanQualType ClassT = Ctx.getCanonicalTagType(
4471 TD: cast<CXXRecordDecl>(Val: Info.FoundDecl->getDeclContext()));
4472
4473 return Ctx.hasSameUnqualifiedType(T1: ParmT, T2: ClassT);
4474}
4475
4476static OverloadingResult ResolveConstructorOverload(
4477 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4478 OverloadCandidateSet &CandidateSet, QualType DestType,
4479 DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,
4480 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4481 bool IsListInit, bool RequireActualConstructor,
4482 bool SecondStepOfCopyInit = false) {
4483 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByConstructor);
4484 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4485
4486 for (NamedDecl *D : Ctors) {
4487 auto Info = getConstructorInfo(ND: D);
4488 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4489 continue;
4490
4491 if (OnlyListConstructors && !S.isInitListConstructor(Ctor: Info.Constructor))
4492 continue;
4493
4494 // C++11 [over.best.ics]p4:
4495 // ... and the constructor or user-defined conversion function is a
4496 // candidate by
4497 // - 13.3.1.3, when the argument is the temporary in the second step
4498 // of a class copy-initialization, or
4499 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4500 // - the second phase of 13.3.1.7 when the initializer list has exactly
4501 // one element that is itself an initializer list, and the target is
4502 // the first parameter of a constructor of class X, and the conversion
4503 // is to X or reference to (possibly cv-qualified X),
4504 // user-defined conversion sequences are not considered.
4505 bool SuppressUserConversions =
4506 SecondStepOfCopyInit ||
4507 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) &&
4508 hasCopyOrMoveCtorParam(Ctx&: S.Context, Info));
4509
4510 if (Info.ConstructorTmpl)
4511 S.AddTemplateOverloadCandidate(
4512 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4513 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args, CandidateSet, SuppressUserConversions,
4514 /*PartialOverloading=*/false, AllowExplicit);
4515 else {
4516 // C++ [over.match.copy]p1:
4517 // - When initializing a temporary to be bound to the first parameter
4518 // of a constructor [for type T] that takes a reference to possibly
4519 // cv-qualified T as its first argument, called with a single
4520 // argument in the context of direct-initialization, explicit
4521 // conversion functions are also considered.
4522 // FIXME: What if a constructor template instantiates to such a signature?
4523 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4524 Args.size() == 1 &&
4525 hasCopyOrMoveCtorParam(Ctx&: S.Context, Info);
4526 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args,
4527 CandidateSet, SuppressUserConversions,
4528 /*PartialOverloading=*/false, AllowExplicit,
4529 AllowExplicitConversion: AllowExplicitConv);
4530 }
4531 }
4532
4533 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4534 //
4535 // When initializing an object of class type T by constructor
4536 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4537 // from a single expression of class type U, conversion functions of
4538 // U that convert to the non-reference type cv T are candidates.
4539 // Explicit conversion functions are only candidates during
4540 // direct-initialization.
4541 //
4542 // Note: SecondStepOfCopyInit is only ever true in this case when
4543 // evaluating whether to produce a C++98 compatibility warning.
4544 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4545 !RequireActualConstructor && !SecondStepOfCopyInit) {
4546 Expr *Initializer = Args[0];
4547 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4548 if (SourceRD && S.isCompleteType(Loc: DeclLoc, T: Initializer->getType())) {
4549 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4550 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4551 NamedDecl *D = *I;
4552 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
4553 D = D->getUnderlyingDecl();
4554
4555 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
4556 CXXConversionDecl *Conv;
4557 if (ConvTemplate)
4558 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4559 else
4560 Conv = cast<CXXConversionDecl>(Val: D);
4561
4562 if (ConvTemplate)
4563 S.AddTemplateConversionCandidate(
4564 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
4565 CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit,
4566 /*AllowResultConversion*/ false);
4567 else
4568 S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer,
4569 ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit,
4570 AllowExplicit,
4571 /*AllowResultConversion*/ false);
4572 }
4573 }
4574 }
4575
4576 // Perform overload resolution and return the result.
4577 return CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best);
4578}
4579
4580/// Attempt initialization by constructor (C++ [dcl.init]), which
4581/// enumerates the constructors of the initialized entity and performs overload
4582/// resolution to select the best.
4583/// \param DestType The destination class type.
4584/// \param DestArrayType The destination type, which is either DestType or
4585/// a (possibly multidimensional) array of DestType.
4586/// \param IsListInit Is this list-initialization?
4587/// \param IsInitListCopy Is this non-list-initialization resulting from a
4588/// list-initialization from {x} where x is the same
4589/// aggregate type as the entity?
4590static void TryConstructorInitialization(Sema &S,
4591 const InitializedEntity &Entity,
4592 const InitializationKind &Kind,
4593 MultiExprArg Args, QualType DestType,
4594 QualType DestArrayType,
4595 InitializationSequence &Sequence,
4596 bool IsListInit = false,
4597 bool IsInitListCopy = false) {
4598 assert(((!IsListInit && !IsInitListCopy) ||
4599 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4600 "IsListInit/IsInitListCopy must come with a single initializer list "
4601 "argument.");
4602 InitListExpr *ILE =
4603 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Val: Args[0]) : nullptr;
4604 MultiExprArg UnwrappedArgs =
4605 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4606
4607 // The type we're constructing needs to be complete.
4608 if (!S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) {
4609 Sequence.setIncompleteTypeFailure(DestType);
4610 return;
4611 }
4612
4613 bool RequireActualConstructor =
4614 !(Entity.getKind() != InitializedEntity::EK_Base &&
4615 Entity.getKind() != InitializedEntity::EK_Delegating &&
4616 Entity.getKind() !=
4617 InitializedEntity::EK_LambdaToBlockConversionBlockElement);
4618
4619 bool CopyElisionPossible = false;
4620 auto ElideConstructor = [&] {
4621 // Convert qualifications if necessary.
4622 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
4623 if (ILE)
4624 Sequence.RewrapReferenceInitList(T: DestType, Syntactic: ILE);
4625 };
4626
4627 // C++17 [dcl.init]p17:
4628 // - If the initializer expression is a prvalue and the cv-unqualified
4629 // version of the source type is the same class as the class of the
4630 // destination, the initializer expression is used to initialize the
4631 // destination object.
4632 // Per DR (no number yet), this does not apply when initializing a base
4633 // class or delegating to another constructor from a mem-initializer.
4634 // ObjC++: Lambda captured by the block in the lambda to block conversion
4635 // should avoid copy elision.
4636 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4637 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4638 S.Context.hasSameUnqualifiedType(T1: UnwrappedArgs[0]->getType(), T2: DestType)) {
4639 if (ILE && !DestType->isAggregateType()) {
4640 // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4641 // Make this an elision if this won't call an initializer-list
4642 // constructor. (Always on an aggregate type or check constructors first.)
4643
4644 // This effectively makes our resolution as follows. The parts in angle
4645 // brackets are additions.
4646 // C++17 [over.match.list]p(1.2):
4647 // - If no viable initializer-list constructor is found <and the
4648 // initializer list does not consist of exactly a single element with
4649 // the same cv-unqualified class type as T>, [...]
4650 // C++17 [dcl.init.list]p(3.6):
4651 // - Otherwise, if T is a class type, constructors are considered. The
4652 // applicable constructors are enumerated and the best one is chosen
4653 // through overload resolution. <If no constructor is found and the
4654 // initializer list consists of exactly a single element with the same
4655 // cv-unqualified class type as T, the object is initialized from that
4656 // element (by copy-initialization for copy-list-initialization, or by
4657 // direct-initialization for direct-list-initialization). Otherwise, >
4658 // if a narrowing conversion [...]
4659 assert(!IsInitListCopy &&
4660 "IsInitListCopy only possible with aggregate types");
4661 CopyElisionPossible = true;
4662 } else {
4663 ElideConstructor();
4664 return;
4665 }
4666 }
4667
4668 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
4669 // Build the candidate set directly in the initialization sequence
4670 // structure, so that it will persist if we fail.
4671 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4672
4673 // Determine whether we are allowed to call explicit constructors or
4674 // explicit conversion operators.
4675 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4676 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4677
4678 // - Otherwise, if T is a class type, constructors are considered. The
4679 // applicable constructors are enumerated, and the best one is chosen
4680 // through overload resolution.
4681 DeclContext::lookup_result Ctors = S.LookupConstructors(Class: DestRecordDecl);
4682
4683 OverloadingResult Result = OR_No_Viable_Function;
4684 OverloadCandidateSet::iterator Best;
4685 bool AsInitializerList = false;
4686
4687 // C++11 [over.match.list]p1, per DR1467:
4688 // When objects of non-aggregate type T are list-initialized, such that
4689 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4690 // according to the rules in this section, overload resolution selects
4691 // the constructor in two phases:
4692 //
4693 // - Initially, the candidate functions are the initializer-list
4694 // constructors of the class T and the argument list consists of the
4695 // initializer list as a single argument.
4696 if (IsListInit) {
4697 AsInitializerList = true;
4698
4699 // If the initializer list has no elements and T has a default constructor,
4700 // the first phase is omitted.
4701 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(Class: DestRecordDecl)))
4702 Result = ResolveConstructorOverload(
4703 S, DeclLoc: Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4704 CopyInitializing: CopyInitialization, AllowExplicit,
4705 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4706
4707 if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4708 // No initializer list candidate
4709 ElideConstructor();
4710 return;
4711 }
4712 }
4713
4714 // if the initialization is direct-initialization, or if it is
4715 // copy-initialization where the cv-unqualified version of the source type is
4716 // the same as or is derived from the class of the destination type,
4717 // constructors are considered.
4718 if ((Kind.getKind() == InitializationKind::IK_Direct ||
4719 Kind.getKind() == InitializationKind::IK_Copy) &&
4720 Args.size() == 1 &&
4721 S.getASTContext().hasSameUnqualifiedType(
4722 T1: Args[0]->getType().getNonReferenceType(),
4723 T2: DestType.getNonReferenceType()))
4724 RequireActualConstructor = true;
4725
4726 // C++11 [over.match.list]p1:
4727 // - If no viable initializer-list constructor is found, overload resolution
4728 // is performed again, where the candidate functions are all the
4729 // constructors of the class T and the argument list consists of the
4730 // elements of the initializer list.
4731 if (Result == OR_No_Viable_Function) {
4732 AsInitializerList = false;
4733 Result = ResolveConstructorOverload(
4734 S, DeclLoc: Kind.getLocation(), Args: UnwrappedArgs, CandidateSet, DestType, Ctors,
4735 Best, CopyInitializing: CopyInitialization, AllowExplicit,
4736 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4737 }
4738 if (Result) {
4739 Sequence.SetOverloadFailure(
4740 Failure: IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4741 : InitializationSequence::FK_ConstructorOverloadFailed,
4742 Result);
4743
4744 if (Result != OR_Deleted)
4745 return;
4746 }
4747
4748 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4749
4750 // In C++17, ResolveConstructorOverload can select a conversion function
4751 // instead of a constructor.
4752 if (auto *CD = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4753 // Add the user-defined conversion step that calls the conversion function.
4754 QualType ConvType = CD->getConversionType();
4755 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4756 "should not have selected this conversion function");
4757 Sequence.AddUserConversionStep(Function: CD, FoundDecl: Best->FoundDecl, T: ConvType,
4758 HadMultipleCandidates);
4759 if (!S.Context.hasSameType(T1: ConvType, T2: DestType))
4760 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
4761 if (IsListInit)
4762 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: ILE);
4763 return;
4764 }
4765
4766 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
4767 if (Result != OR_Deleted) {
4768 if (!IsListInit &&
4769 (Kind.getKind() == InitializationKind::IK_Default ||
4770 Kind.getKind() == InitializationKind::IK_Direct) &&
4771 !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) &&
4772 DestRecordDecl->isAggregate() &&
4773 DestRecordDecl->hasUninitializedExplicitInitFields() &&
4774 !S.isUnevaluatedContext()) {
4775 S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init)
4776 << /* Var-in-Record */ 1 << DestRecordDecl;
4777 emitUninitializedExplicitInitFields(S, R: DestRecordDecl);
4778 }
4779
4780 // C++11 [dcl.init]p6:
4781 // If a program calls for the default initialization of an object
4782 // of a const-qualified type T, T shall be a class type with a
4783 // user-provided default constructor.
4784 // C++ core issue 253 proposal:
4785 // If the implicit default constructor initializes all subobjects, no
4786 // initializer should be required.
4787 // The 253 proposal is for example needed to process libstdc++ headers
4788 // in 5.x.
4789 if (Kind.getKind() == InitializationKind::IK_Default &&
4790 Entity.getType().isConstQualified()) {
4791 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4792 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4793 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4794 return;
4795 }
4796 }
4797
4798 // C++11 [over.match.list]p1:
4799 // In copy-list-initialization, if an explicit constructor is chosen, the
4800 // initializer is ill-formed.
4801 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4802 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4803 return;
4804 }
4805 }
4806
4807 // [class.copy.elision]p3:
4808 // In some copy-initialization contexts, a two-stage overload resolution
4809 // is performed.
4810 // If the first overload resolution selects a deleted function, we also
4811 // need the initialization sequence to decide whether to perform the second
4812 // overload resolution.
4813 // For deleted functions in other contexts, there is no need to get the
4814 // initialization sequence.
4815 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4816 return;
4817
4818 // Add the constructor initialization step. Any cv-qualification conversion is
4819 // subsumed by the initialization.
4820 Sequence.AddConstructorInitializationStep(
4821 FoundDecl: Best->FoundDecl, Constructor: CtorDecl, T: DestArrayType, HadMultipleCandidates,
4822 FromInitList: IsListInit | IsInitListCopy, AsInitList: AsInitializerList);
4823}
4824
4825static void TryOrBuildParenListInitialization(
4826 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4827 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
4828 ExprResult *Result = nullptr);
4829
4830/// Attempt to initialize an object of a class type either by
4831/// direct-initialization, or by copy-initialization from an
4832/// expression of the same or derived class type. This corresponds
4833/// to the first two sub-bullets of C++2c [dcl.init.general] p16.6.
4834///
4835/// \param IsAggrListInit Is this non-list-initialization being done as
4836/// part of a list-initialization of an aggregate
4837/// from a single expression of the same or
4838/// derived class type (C++2c [dcl.init.list] p3.2)?
4839static void TryConstructorOrParenListInitialization(
4840 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4841 MultiExprArg Args, QualType DestType, InitializationSequence &Sequence,
4842 bool IsAggrListInit) {
4843 // C++2c [dcl.init.general] p16.6:
4844 // * Otherwise, if the destination type is a class type:
4845 // * If the initializer expression is a prvalue and
4846 // the cv-unqualified version of the source type is the same
4847 // as the destination type, the initializer expression is used
4848 // to initialize the destination object.
4849 // * Otherwise, if the initialization is direct-initialization,
4850 // or if it is copy-initialization where the cv-unqualified
4851 // version of the source type is the same as or is derived from
4852 // the class of the destination type, constructors are considered.
4853 // The applicable constructors are enumerated, and the best one
4854 // is chosen through overload resolution. Then:
4855 // * If overload resolution is successful, the selected
4856 // constructor is called to initialize the object, with
4857 // the initializer expression or expression-list as its
4858 // argument(s).
4859 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestArrayType: DestType,
4860 Sequence, /*IsListInit=*/false, IsInitListCopy: IsAggrListInit);
4861
4862 // * Otherwise, if no constructor is viable, the destination type
4863 // is an aggregate class, and the initializer is a parenthesized
4864 // expression-list, the object is initialized as follows. [...]
4865 // Parenthesized initialization of aggregates is a C++20 feature.
4866 if (S.getLangOpts().CPlusPlus20 &&
4867 Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() &&
4868 Sequence.getFailureKind() ==
4869 InitializationSequence::FK_ConstructorOverloadFailed &&
4870 Sequence.getFailedOverloadResult() == OR_No_Viable_Function &&
4871 (IsAggrListInit || DestType->isAggregateType()))
4872 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence,
4873 /*VerifyOnly=*/true);
4874
4875 // * Otherwise, the initialization is ill-formed.
4876}
4877
4878static bool
4879ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4880 Expr *Initializer,
4881 QualType &SourceType,
4882 QualType &UnqualifiedSourceType,
4883 QualType UnqualifiedTargetType,
4884 InitializationSequence &Sequence) {
4885 if (S.Context.getCanonicalType(T: UnqualifiedSourceType) ==
4886 S.Context.OverloadTy) {
4887 DeclAccessPair Found;
4888 bool HadMultipleCandidates = false;
4889 if (FunctionDecl *Fn
4890 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer,
4891 TargetType: UnqualifiedTargetType,
4892 Complain: false, Found,
4893 pHadMultipleCandidates: &HadMultipleCandidates)) {
4894 Sequence.AddAddressOverloadResolutionStep(Function: Fn, Found,
4895 HadMultipleCandidates);
4896 SourceType = Fn->getType();
4897 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4898 } else if (!UnqualifiedTargetType->isRecordType()) {
4899 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4900 return true;
4901 }
4902 }
4903 return false;
4904}
4905
4906static void TryReferenceInitializationCore(Sema &S,
4907 const InitializedEntity &Entity,
4908 const InitializationKind &Kind,
4909 Expr *Initializer,
4910 QualType cv1T1, QualType T1,
4911 Qualifiers T1Quals,
4912 QualType cv2T2, QualType T2,
4913 Qualifiers T2Quals,
4914 InitializationSequence &Sequence,
4915 bool TopLevelOfInitList);
4916
4917static void TryValueInitialization(Sema &S,
4918 const InitializedEntity &Entity,
4919 const InitializationKind &Kind,
4920 InitializationSequence &Sequence,
4921 InitListExpr *InitList = nullptr);
4922
4923/// Attempt list initialization of a reference.
4924static void TryReferenceListInitialization(Sema &S,
4925 const InitializedEntity &Entity,
4926 const InitializationKind &Kind,
4927 InitListExpr *InitList,
4928 InitializationSequence &Sequence,
4929 bool TreatUnavailableAsInvalid) {
4930 // First, catch C++03 where this isn't possible.
4931 if (!S.getLangOpts().CPlusPlus11) {
4932 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4933 return;
4934 }
4935 // Can't reference initialize a compound literal.
4936 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4937 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4938 return;
4939 }
4940
4941 QualType DestType = Entity.getType();
4942 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4943 Qualifiers T1Quals;
4944 QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals);
4945
4946 // Reference initialization via an initializer list works thus:
4947 // If the initializer list consists of a single element that is
4948 // reference-related to the referenced type, bind directly to that element
4949 // (possibly creating temporaries).
4950 // Otherwise, initialize a temporary with the initializer list and
4951 // bind to that.
4952 if (InitList->getNumInits() == 1) {
4953 Expr *Initializer = InitList->getInit(Init: 0);
4954 QualType cv2T2 = S.getCompletedType(E: Initializer);
4955 Qualifiers T2Quals;
4956 QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals);
4957
4958 // If this fails, creating a temporary wouldn't work either.
4959 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2,
4960 UnqualifiedTargetType: T1, Sequence))
4961 return;
4962
4963 SourceLocation DeclLoc = Initializer->getBeginLoc();
4964 Sema::ReferenceCompareResult RefRelationship
4965 = S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2);
4966 if (RefRelationship >= Sema::Ref_Related) {
4967 // Try to bind the reference here.
4968 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4969 T1Quals, cv2T2, T2, T2Quals, Sequence,
4970 /*TopLevelOfInitList=*/true);
4971 if (Sequence)
4972 Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList);
4973 return;
4974 }
4975
4976 // Update the initializer if we've resolved an overloaded function.
4977 if (!Sequence.steps().empty())
4978 Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList);
4979 }
4980 // Perform address space compatibility check.
4981 QualType cv1T1IgnoreAS = cv1T1;
4982 if (T1Quals.hasAddressSpace()) {
4983 Qualifiers T2Quals;
4984 (void)S.Context.getUnqualifiedArrayType(T: InitList->getType(), Quals&: T2Quals);
4985 if (!T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext())) {
4986 Sequence.SetFailed(
4987 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4988 return;
4989 }
4990 // Ignore address space of reference type at this point and perform address
4991 // space conversion after the reference binding step.
4992 cv1T1IgnoreAS =
4993 S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace());
4994 }
4995 // Not reference-related. Create a temporary and bind to that.
4996 InitializedEntity TempEntity =
4997 InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS);
4998
4999 TryListInitialization(S, Entity: TempEntity, Kind, InitList, Sequence,
5000 TreatUnavailableAsInvalid);
5001 if (Sequence) {
5002 if (DestType->isRValueReferenceType() ||
5003 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
5004 Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS,
5005 /*BindingTemporary=*/true);
5006 if (S.getLangOpts().CPlusPlus20 &&
5007 isa<IncompleteArrayType>(Val: T1->getUnqualifiedDesugaredType()) &&
5008 DestType->isRValueReferenceType()) {
5009 // C++20 [dcl.init.list]p3.10:
5010 // List-initialization of an object or reference of type T is defined as
5011 // follows:
5012 // ..., unless T is “reference to array of unknown bound of U”, in which
5013 // case the type of the prvalue is the type of x in the declaration U
5014 // x[] H, where H is the initializer list.
5015
5016 // The call to AddReferenceBindingStep above converts the rvalue to an
5017 // xvalue. Convert that xvalue to the incomplete array type.
5018 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: clang::VK_XValue);
5019 }
5020 if (T1Quals.hasAddressSpace())
5021 Sequence.AddQualificationConversionStep(
5022 Ty: cv1T1, VK: DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
5023 } else
5024 Sequence.SetFailed(
5025 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
5026 }
5027}
5028
5029/// Attempt list initialization (C++0x [dcl.init.list])
5030static void TryListInitialization(Sema &S,
5031 const InitializedEntity &Entity,
5032 const InitializationKind &Kind,
5033 InitListExpr *InitList,
5034 InitializationSequence &Sequence,
5035 bool TreatUnavailableAsInvalid) {
5036 QualType DestType = Entity.getType();
5037
5038 if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, Init: InitList)) {
5039 Sequence.SetFailed(InitializationSequence::FK_HLSLInitListFlatteningFailed);
5040 return;
5041 }
5042
5043 // C++ doesn't allow scalar initialization with more than one argument.
5044 // But C99 complex numbers are scalars and it makes sense there.
5045 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
5046 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
5047 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
5048 return;
5049 }
5050 if (DestType->isReferenceType()) {
5051 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
5052 TreatUnavailableAsInvalid);
5053 return;
5054 }
5055
5056 if (DestType->isRecordType() &&
5057 !S.isCompleteType(Loc: InitList->getBeginLoc(), T: DestType)) {
5058 Sequence.setIncompleteTypeFailure(DestType);
5059 return;
5060 }
5061
5062 // C++20 [dcl.init.list]p3:
5063 // - If the braced-init-list contains a designated-initializer-list, T shall
5064 // be an aggregate class. [...] Aggregate initialization is performed.
5065 //
5066 // We allow arrays here too in order to support array designators.
5067 //
5068 // FIXME: This check should precede the handling of reference initialization.
5069 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
5070 // as a tentative DR resolution.
5071 bool IsDesignatedInit = InitList->hasDesignatedInit();
5072 if (!DestType->isAggregateType() && IsDesignatedInit) {
5073 Sequence.SetFailed(
5074 InitializationSequence::FK_DesignatedInitForNonAggregate);
5075 return;
5076 }
5077
5078 // C++11 [dcl.init.list]p3, per DR1467 and DR2137:
5079 // - If T is an aggregate class and the initializer list has a single element
5080 // of type cv U, where U is T or a class derived from T, the object is
5081 // initialized from that element (by copy-initialization for
5082 // copy-list-initialization, or by direct-initialization for
5083 // direct-list-initialization).
5084 // - Otherwise, if T is a character array and the initializer list has a
5085 // single element that is an appropriately-typed string literal
5086 // (8.5.2 [dcl.init.string]), initialization is performed as described
5087 // in that section.
5088 // - Otherwise, if T is an aggregate, [...] (continue below).
5089 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
5090 !IsDesignatedInit) {
5091 if (DestType->isRecordType() && DestType->isAggregateType()) {
5092 QualType InitType = InitList->getInit(Init: 0)->getType();
5093 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: DestType) ||
5094 S.IsDerivedFrom(Loc: InitList->getBeginLoc(), Derived: InitType, Base: DestType)) {
5095 InitializationKind SubKind =
5096 Kind.getKind() == InitializationKind::IK_DirectList
5097 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5098 LParenLoc: InitList->getLBraceLoc(),
5099 RParenLoc: InitList->getRBraceLoc())
5100 : Kind;
5101 Expr *InitListAsExpr = InitList;
5102 TryConstructorOrParenListInitialization(
5103 S, Entity, Kind: SubKind, Args: InitListAsExpr, DestType, Sequence,
5104 /*IsAggrListInit=*/true);
5105 return;
5106 }
5107 }
5108 if (const ArrayType *DestAT = S.Context.getAsArrayType(T: DestType)) {
5109 Expr *SubInit[1] = {InitList->getInit(Init: 0)};
5110
5111 // C++17 [dcl.struct.bind]p1:
5112 // ... If the assignment-expression in the initializer has array type A
5113 // and no ref-qualifier is present, e has type cv A and each element is
5114 // copy-initialized or direct-initialized from the corresponding element
5115 // of the assignment-expression as specified by the form of the
5116 // initializer. ...
5117 //
5118 // This is a special case not following list-initialization.
5119 if (isa<ConstantArrayType>(Val: DestAT) &&
5120 Entity.getKind() == InitializedEntity::EK_Variable &&
5121 isa<DecompositionDecl>(Val: Entity.getDecl())) {
5122 assert(
5123 S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) &&
5124 "Deduced to other type?");
5125 assert(Kind.getKind() == clang::InitializationKind::IK_DirectList &&
5126 "List-initialize structured bindings but not "
5127 "direct-list-initialization?");
5128 TryArrayCopy(S,
5129 Kind: InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5130 LParenLoc: InitList->getLBraceLoc(),
5131 RParenLoc: InitList->getRBraceLoc()),
5132 Entity, Initializer: SubInit[0], DestType, Sequence,
5133 TreatUnavailableAsInvalid);
5134 if (Sequence)
5135 Sequence.AddUnwrapInitListInitStep(Syntactic: InitList);
5136 return;
5137 }
5138
5139 if (!isa<VariableArrayType>(Val: DestAT) &&
5140 IsStringInit(Init: SubInit[0], AT: DestAT, Context&: S.Context) == SIF_None) {
5141 InitializationKind SubKind =
5142 Kind.getKind() == InitializationKind::IK_DirectList
5143 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5144 LParenLoc: InitList->getLBraceLoc(),
5145 RParenLoc: InitList->getRBraceLoc())
5146 : Kind;
5147 Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit,
5148 /*TopLevelOfInitList*/ true,
5149 TreatUnavailableAsInvalid);
5150
5151 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
5152 // the element is not an appropriately-typed string literal, in which
5153 // case we should proceed as in C++11 (below).
5154 if (Sequence) {
5155 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
5156 return;
5157 }
5158 }
5159 }
5160 }
5161
5162 // C++11 [dcl.init.list]p3:
5163 // - If T is an aggregate, aggregate initialization is performed.
5164 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
5165 (S.getLangOpts().CPlusPlus11 &&
5166 S.isStdInitializerList(Ty: DestType, Element: nullptr) && !IsDesignatedInit)) {
5167 if (S.getLangOpts().CPlusPlus11) {
5168 // - Otherwise, if the initializer list has no elements and T is a
5169 // class type with a default constructor, the object is
5170 // value-initialized.
5171 if (InitList->getNumInits() == 0) {
5172 CXXRecordDecl *RD = DestType->castAsCXXRecordDecl();
5173 if (S.LookupDefaultConstructor(Class: RD)) {
5174 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
5175 return;
5176 }
5177 }
5178
5179 // - Otherwise, if T is a specialization of std::initializer_list<E>,
5180 // an initializer_list object constructed [...]
5181 if (TryInitializerListConstruction(S, List: InitList, DestType, Sequence,
5182 TreatUnavailableAsInvalid))
5183 return;
5184
5185 // - Otherwise, if T is a class type, constructors are considered.
5186 Expr *InitListAsExpr = InitList;
5187 TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType,
5188 DestArrayType: DestType, Sequence, /*InitListSyntax*/IsListInit: true);
5189 } else
5190 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
5191 return;
5192 }
5193
5194 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
5195 InitList->getNumInits() == 1) {
5196 Expr *E = InitList->getInit(Init: 0);
5197
5198 // - Otherwise, if T is an enumeration with a fixed underlying type,
5199 // the initializer-list has a single element v, and the initialization
5200 // is direct-list-initialization, the object is initialized with the
5201 // value T(v); if a narrowing conversion is required to convert v to
5202 // the underlying type of T, the program is ill-formed.
5203 if (S.getLangOpts().CPlusPlus17 &&
5204 Kind.getKind() == InitializationKind::IK_DirectList &&
5205 DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() &&
5206 !S.Context.hasSameUnqualifiedType(T1: E->getType(), T2: DestType) &&
5207 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
5208 E->getType()->isFloatingType())) {
5209 // There are two ways that T(v) can work when T is an enumeration type.
5210 // If there is either an implicit conversion sequence from v to T or
5211 // a conversion function that can convert from v to T, then we use that.
5212 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
5213 // type, it is converted to the enumeration type via its underlying type.
5214 // There is no overlap possible between these two cases (except when the
5215 // source value is already of the destination type), and the first
5216 // case is handled by the general case for single-element lists below.
5217 ImplicitConversionSequence ICS;
5218 ICS.setStandard();
5219 ICS.Standard.setAsIdentityConversion();
5220 if (!E->isPRValue())
5221 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
5222 // If E is of a floating-point type, then the conversion is ill-formed
5223 // due to narrowing, but go through the motions in order to produce the
5224 // right diagnostic.
5225 ICS.Standard.Second = E->getType()->isFloatingType()
5226 ? ICK_Floating_Integral
5227 : ICK_Integral_Conversion;
5228 ICS.Standard.setFromType(E->getType());
5229 ICS.Standard.setToType(Idx: 0, T: E->getType());
5230 ICS.Standard.setToType(Idx: 1, T: DestType);
5231 ICS.Standard.setToType(Idx: 2, T: DestType);
5232 Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2),
5233 /*TopLevelOfInitList*/true);
5234 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
5235 return;
5236 }
5237
5238 // - Otherwise, if the initializer list has a single element of type E
5239 // [...references are handled above...], the object or reference is
5240 // initialized from that element (by copy-initialization for
5241 // copy-list-initialization, or by direct-initialization for
5242 // direct-list-initialization); if a narrowing conversion is required
5243 // to convert the element to T, the program is ill-formed.
5244 //
5245 // Per core-24034, this is direct-initialization if we were performing
5246 // direct-list-initialization and copy-initialization otherwise.
5247 // We can't use InitListChecker for this, because it always performs
5248 // copy-initialization. This only matters if we might use an 'explicit'
5249 // conversion operator, or for the special case conversion of nullptr_t to
5250 // bool, so we only need to handle those cases.
5251 //
5252 // FIXME: Why not do this in all cases?
5253 Expr *Init = InitList->getInit(Init: 0);
5254 if (Init->getType()->isRecordType() ||
5255 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
5256 InitializationKind SubKind =
5257 Kind.getKind() == InitializationKind::IK_DirectList
5258 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
5259 LParenLoc: InitList->getLBraceLoc(),
5260 RParenLoc: InitList->getRBraceLoc())
5261 : Kind;
5262 Expr *SubInit[1] = { Init };
5263 Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit,
5264 /*TopLevelOfInitList*/true,
5265 TreatUnavailableAsInvalid);
5266 if (Sequence)
5267 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
5268 return;
5269 }
5270 }
5271
5272 InitListChecker CheckInitList(S, Entity, InitList,
5273 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
5274 if (CheckInitList.HadError()) {
5275 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
5276 return;
5277 }
5278
5279 // Add the list initialization step with the built init list.
5280 Sequence.AddListInitializationStep(T: DestType);
5281}
5282
5283/// Try a reference initialization that involves calling a conversion
5284/// function.
5285static OverloadingResult TryRefInitWithConversionFunction(
5286 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5287 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
5288 InitializationSequence &Sequence) {
5289 QualType DestType = Entity.getType();
5290 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5291 QualType T1 = cv1T1.getUnqualifiedType();
5292 QualType cv2T2 = Initializer->getType();
5293 QualType T2 = cv2T2.getUnqualifiedType();
5294
5295 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
5296 "Must have incompatible references when binding via conversion");
5297
5298 // Build the candidate set directly in the initialization sequence
5299 // structure, so that it will persist if we fail.
5300 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5301 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5302
5303 // Determine whether we are allowed to call explicit conversion operators.
5304 // Note that none of [over.match.copy], [over.match.conv], nor
5305 // [over.match.ref] permit an explicit constructor to be chosen when
5306 // initializing a reference, not even for direct-initialization.
5307 bool AllowExplicitCtors = false;
5308 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
5309
5310 if (AllowRValues && T1->isRecordType() &&
5311 S.isCompleteType(Loc: Kind.getLocation(), T: T1)) {
5312 auto *T1RecordDecl = T1->castAsCXXRecordDecl();
5313 if (T1RecordDecl->isInvalidDecl())
5314 return OR_No_Viable_Function;
5315 // The type we're converting to is a class type. Enumerate its constructors
5316 // to see if there is a suitable conversion.
5317 for (NamedDecl *D : S.LookupConstructors(Class: T1RecordDecl)) {
5318 auto Info = getConstructorInfo(ND: D);
5319 if (!Info.Constructor)
5320 continue;
5321
5322 if (!Info.Constructor->isInvalidDecl() &&
5323 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5324 if (Info.ConstructorTmpl)
5325 S.AddTemplateOverloadCandidate(
5326 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
5327 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet,
5328 /*SuppressUserConversions=*/true,
5329 /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors);
5330 else
5331 S.AddOverloadCandidate(
5332 Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: Initializer, CandidateSet,
5333 /*SuppressUserConversions=*/true,
5334 /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors);
5335 }
5336 }
5337 }
5338
5339 if (T2->isRecordType() && S.isCompleteType(Loc: Kind.getLocation(), T: T2)) {
5340 const auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5341 if (T2RecordDecl->isInvalidDecl())
5342 return OR_No_Viable_Function;
5343 // The type we're converting from is a class type, enumerate its conversion
5344 // functions.
5345 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5346 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5347 NamedDecl *D = *I;
5348 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5349 if (isa<UsingShadowDecl>(Val: D))
5350 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5351
5352 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
5353 CXXConversionDecl *Conv;
5354 if (ConvTemplate)
5355 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5356 else
5357 Conv = cast<CXXConversionDecl>(Val: D);
5358
5359 // If the conversion function doesn't return a reference type,
5360 // it can't be considered for this conversion unless we're allowed to
5361 // consider rvalues.
5362 // FIXME: Do we need to make sure that we only consider conversion
5363 // candidates with reference-compatible results? That might be needed to
5364 // break recursion.
5365 if ((AllowRValues ||
5366 Conv->getConversionType()->isLValueReferenceType())) {
5367 if (ConvTemplate)
5368 S.AddTemplateConversionCandidate(
5369 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
5370 CandidateSet,
5371 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs);
5372 else
5373 S.AddConversionCandidate(
5374 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, CandidateSet,
5375 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs);
5376 }
5377 }
5378 }
5379
5380 SourceLocation DeclLoc = Initializer->getBeginLoc();
5381
5382 // Perform overload resolution. If it fails, return the failed result.
5383 OverloadCandidateSet::iterator Best;
5384 if (OverloadingResult Result
5385 = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best))
5386 return Result;
5387
5388 FunctionDecl *Function = Best->Function;
5389 // This is the overload that will be used for this initialization step if we
5390 // use this initialization. Mark it as referenced.
5391 Function->setReferenced();
5392
5393 // Compute the returned type and value kind of the conversion.
5394 QualType cv3T3;
5395 if (isa<CXXConversionDecl>(Val: Function))
5396 cv3T3 = Function->getReturnType();
5397 else
5398 cv3T3 = T1;
5399
5400 ExprValueKind VK = VK_PRValue;
5401 if (cv3T3->isLValueReferenceType())
5402 VK = VK_LValue;
5403 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
5404 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
5405 cv3T3 = cv3T3.getNonLValueExprType(Context: S.Context);
5406
5407 // Add the user-defined conversion step.
5408 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5409 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: cv3T3,
5410 HadMultipleCandidates);
5411
5412 // Determine whether we'll need to perform derived-to-base adjustments or
5413 // other conversions.
5414 Sema::ReferenceConversions RefConv;
5415 Sema::ReferenceCompareResult NewRefRelationship =
5416 S.CompareReferenceRelationship(Loc: DeclLoc, T1, T2: cv3T3, Conv: &RefConv);
5417
5418 // Add the final conversion sequence, if necessary.
5419 if (NewRefRelationship == Sema::Ref_Incompatible) {
5420 assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) &&
5421 "should not have conversion after constructor");
5422
5423 ImplicitConversionSequence ICS;
5424 ICS.setStandard();
5425 ICS.Standard = Best->FinalConversion;
5426 Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2));
5427
5428 // Every implicit conversion results in a prvalue, except for a glvalue
5429 // derived-to-base conversion, which we handle below.
5430 cv3T3 = ICS.Standard.getToType(Idx: 2);
5431 VK = VK_PRValue;
5432 }
5433
5434 // If the converted initializer is a prvalue, its type T4 is adjusted to
5435 // type "cv1 T4" and the temporary materialization conversion is applied.
5436 //
5437 // We adjust the cv-qualifications to match the reference regardless of
5438 // whether we have a prvalue so that the AST records the change. In this
5439 // case, T4 is "cv3 T3".
5440 QualType cv1T4 = S.Context.getQualifiedType(T: cv3T3, Qs: cv1T1.getQualifiers());
5441 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
5442 Sequence.AddQualificationConversionStep(Ty: cv1T4, VK);
5443 Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: VK == VK_PRValue);
5444 VK = IsLValueRef ? VK_LValue : VK_XValue;
5445
5446 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5447 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK);
5448 else if (RefConv & Sema::ReferenceConversions::ObjC)
5449 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5450 else if (RefConv & Sema::ReferenceConversions::Function)
5451 Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1);
5452 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5453 if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1))
5454 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK);
5455 }
5456
5457 return OR_Success;
5458}
5459
5460static void CheckCXX98CompatAccessibleCopy(Sema &S,
5461 const InitializedEntity &Entity,
5462 Expr *CurInitExpr);
5463
5464/// Attempt reference initialization (C++0x [dcl.init.ref])
5465static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,
5466 const InitializationKind &Kind,
5467 Expr *Initializer,
5468 InitializationSequence &Sequence,
5469 bool TopLevelOfInitList) {
5470 QualType DestType = Entity.getType();
5471 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
5472 Qualifiers T1Quals;
5473 QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals);
5474 QualType cv2T2 = S.getCompletedType(E: Initializer);
5475 Qualifiers T2Quals;
5476 QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals);
5477
5478 // If the initializer is the address of an overloaded function, try
5479 // to resolve the overloaded function. If all goes well, T2 is the
5480 // type of the resulting function.
5481 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2,
5482 UnqualifiedTargetType: T1, Sequence))
5483 return;
5484
5485 // Delegate everything else to a subfunction.
5486 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
5487 T1Quals, cv2T2, T2, T2Quals, Sequence,
5488 TopLevelOfInitList);
5489}
5490
5491/// Determine whether an expression is a non-referenceable glvalue (one to
5492/// which a reference can never bind). Attempting to bind a reference to
5493/// such a glvalue will always create a temporary.
5494static bool isNonReferenceableGLValue(Expr *E) {
5495 return E->refersToBitField() || E->refersToVectorElement() ||
5496 E->refersToMatrixElement();
5497}
5498
5499/// Reference initialization without resolving overloaded functions.
5500///
5501/// We also can get here in C if we call a builtin which is declared as
5502/// a function with a parameter of reference type (such as __builtin_va_end()).
5503static void TryReferenceInitializationCore(Sema &S,
5504 const InitializedEntity &Entity,
5505 const InitializationKind &Kind,
5506 Expr *Initializer,
5507 QualType cv1T1, QualType T1,
5508 Qualifiers T1Quals,
5509 QualType cv2T2, QualType T2,
5510 Qualifiers T2Quals,
5511 InitializationSequence &Sequence,
5512 bool TopLevelOfInitList) {
5513 QualType DestType = Entity.getType();
5514 SourceLocation DeclLoc = Initializer->getBeginLoc();
5515
5516 // Compute some basic properties of the types and the initializer.
5517 bool isLValueRef = DestType->isLValueReferenceType();
5518 bool isRValueRef = !isLValueRef;
5519 Expr::Classification InitCategory = Initializer->Classify(Ctx&: S.Context);
5520
5521 Sema::ReferenceConversions RefConv;
5522 Sema::ReferenceCompareResult RefRelationship =
5523 S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2, Conv: &RefConv);
5524
5525 // C++0x [dcl.init.ref]p5:
5526 // A reference to type "cv1 T1" is initialized by an expression of type
5527 // "cv2 T2" as follows:
5528 //
5529 // - If the reference is an lvalue reference and the initializer
5530 // expression
5531 // Note the analogous bullet points for rvalue refs to functions. Because
5532 // there are no function rvalues in C++, rvalue refs to functions are treated
5533 // like lvalue refs.
5534 OverloadingResult ConvOvlResult = OR_Success;
5535 bool T1Function = T1->isFunctionType();
5536 if (isLValueRef || T1Function) {
5537 if (InitCategory.isLValue() && !isNonReferenceableGLValue(E: Initializer) &&
5538 (RefRelationship == Sema::Ref_Compatible ||
5539 (Kind.isCStyleOrFunctionalCast() &&
5540 RefRelationship == Sema::Ref_Related))) {
5541 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5542 // reference-compatible with "cv2 T2," or
5543 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5544 Sema::ReferenceConversions::ObjC)) {
5545 // If we're converting the pointee, add any qualifiers first;
5546 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5547 if (RefConv & (Sema::ReferenceConversions::Qualification))
5548 Sequence.AddQualificationConversionStep(
5549 Ty: S.Context.getQualifiedType(T: T2, Qs: T1Quals),
5550 VK: Initializer->getValueKind());
5551 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5552 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: VK_LValue);
5553 else
5554 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5555 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5556 // Perform a (possibly multi-level) qualification conversion.
5557 Sequence.AddQualificationConversionStep(Ty: cv1T1,
5558 VK: Initializer->getValueKind());
5559 } else if (RefConv & Sema::ReferenceConversions::Function) {
5560 Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1);
5561 }
5562
5563 // We only create a temporary here when binding a reference to a
5564 // bit-field or vector element. Those cases are't supposed to be
5565 // handled by this bullet, but the outcome is the same either way.
5566 Sequence.AddReferenceBindingStep(T: cv1T1, BindingTemporary: false);
5567 return;
5568 }
5569
5570 // - has a class type (i.e., T2 is a class type), where T1 is not
5571 // reference-related to T2, and can be implicitly converted to an
5572 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5573 // with "cv3 T3" (this conversion is selected by enumerating the
5574 // applicable conversion functions (13.3.1.6) and choosing the best
5575 // one through overload resolution (13.3)),
5576 // If we have an rvalue ref to function type here, the rhs must be
5577 // an rvalue. DR1287 removed the "implicitly" here.
5578 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5579 (isLValueRef || InitCategory.isRValue())) {
5580 if (S.getLangOpts().CPlusPlus) {
5581 // Try conversion functions only for C++.
5582 ConvOvlResult = TryRefInitWithConversionFunction(
5583 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5584 /*IsLValueRef*/ isLValueRef, Sequence);
5585 if (ConvOvlResult == OR_Success)
5586 return;
5587 if (ConvOvlResult != OR_No_Viable_Function)
5588 Sequence.SetOverloadFailure(
5589 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5590 Result: ConvOvlResult);
5591 } else {
5592 ConvOvlResult = OR_No_Viable_Function;
5593 }
5594 }
5595 }
5596
5597 // - Otherwise, the reference shall be an lvalue reference to a
5598 // non-volatile const type (i.e., cv1 shall be const), or the reference
5599 // shall be an rvalue reference.
5600 // For address spaces, we interpret this to mean that an addr space
5601 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5602 if (isLValueRef &&
5603 !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5604 T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) {
5605 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy)
5606 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5607 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5608 Sequence.SetOverloadFailure(
5609 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5610 Result: ConvOvlResult);
5611 else if (!InitCategory.isLValue())
5612 Sequence.SetFailed(
5613 T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext())
5614 ? InitializationSequence::
5615 FK_NonConstLValueReferenceBindingToTemporary
5616 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
5617 else {
5618 InitializationSequence::FailureKind FK;
5619 switch (RefRelationship) {
5620 case Sema::Ref_Compatible:
5621 if (Initializer->refersToBitField())
5622 FK = InitializationSequence::
5623 FK_NonConstLValueReferenceBindingToBitfield;
5624 else if (Initializer->refersToVectorElement())
5625 FK = InitializationSequence::
5626 FK_NonConstLValueReferenceBindingToVectorElement;
5627 else if (Initializer->refersToMatrixElement())
5628 FK = InitializationSequence::
5629 FK_NonConstLValueReferenceBindingToMatrixElement;
5630 else
5631 llvm_unreachable("unexpected kind of compatible initializer");
5632 break;
5633 case Sema::Ref_Related:
5634 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5635 break;
5636 case Sema::Ref_Incompatible:
5637 FK = InitializationSequence::
5638 FK_NonConstLValueReferenceBindingToUnrelated;
5639 break;
5640 }
5641 Sequence.SetFailed(FK);
5642 }
5643 return;
5644 }
5645
5646 // - If the initializer expression
5647 // - is an
5648 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5649 // [1z] rvalue (but not a bit-field) or
5650 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5651 //
5652 // Note: functions are handled above and below rather than here...
5653 if (!T1Function &&
5654 (RefRelationship == Sema::Ref_Compatible ||
5655 (Kind.isCStyleOrFunctionalCast() &&
5656 RefRelationship == Sema::Ref_Related)) &&
5657 ((InitCategory.isXValue() && !isNonReferenceableGLValue(E: Initializer)) ||
5658 (InitCategory.isPRValue() &&
5659 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5660 T2->isArrayType())))) {
5661 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5662 if (InitCategory.isPRValue() && T2->isRecordType()) {
5663 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5664 // compiler the freedom to perform a copy here or bind to the
5665 // object, while C++0x requires that we bind directly to the
5666 // object. Hence, we always bind to the object without making an
5667 // extra copy. However, in C++03 requires that we check for the
5668 // presence of a suitable copy constructor:
5669 //
5670 // The constructor that would be used to make the copy shall
5671 // be callable whether or not the copy is actually done.
5672 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5673 Sequence.AddExtraneousCopyToTemporary(T: cv2T2);
5674 else if (S.getLangOpts().CPlusPlus11)
5675 CheckCXX98CompatAccessibleCopy(S, Entity, CurInitExpr: Initializer);
5676 }
5677
5678 // C++1z [dcl.init.ref]/5.2.1.2:
5679 // If the converted initializer is a prvalue, its type T4 is adjusted
5680 // to type "cv1 T4" and the temporary materialization conversion is
5681 // applied.
5682 // Postpone address space conversions to after the temporary materialization
5683 // conversion to allow creating temporaries in the alloca address space.
5684 auto T1QualsIgnoreAS = T1Quals;
5685 auto T2QualsIgnoreAS = T2Quals;
5686 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5687 T1QualsIgnoreAS.removeAddressSpace();
5688 T2QualsIgnoreAS.removeAddressSpace();
5689 }
5690 // Strip the existing ObjC lifetime qualifier from cv2T2 before combining
5691 // with T1's qualifiers.
5692 QualType T2ForQualConv = cv2T2;
5693 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) {
5694 Qualifiers T2BaseQuals =
5695 T2ForQualConv.getQualifiers().withoutObjCLifetime();
5696 T2ForQualConv = S.Context.getQualifiedType(
5697 T: T2ForQualConv.getUnqualifiedType(), Qs: T2BaseQuals);
5698 }
5699 QualType cv1T4 = S.Context.getQualifiedType(T: T2ForQualConv, Qs: T1QualsIgnoreAS);
5700 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5701 Sequence.AddQualificationConversionStep(Ty: cv1T4, VK: ValueKind);
5702 Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: ValueKind == VK_PRValue);
5703 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5704 // Add addr space conversion if required.
5705 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5706 auto T4Quals = cv1T4.getQualifiers();
5707 T4Quals.addAddressSpace(space: T1Quals.getAddressSpace());
5708 QualType cv1T4WithAS = S.Context.getQualifiedType(T: T2, Qs: T4Quals);
5709 Sequence.AddQualificationConversionStep(Ty: cv1T4WithAS, VK: ValueKind);
5710 cv1T4 = cv1T4WithAS;
5711 }
5712
5713 // In any case, the reference is bound to the resulting glvalue (or to
5714 // an appropriate base class subobject).
5715 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5716 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: ValueKind);
5717 else if (RefConv & Sema::ReferenceConversions::ObjC)
5718 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5719 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5720 if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1))
5721 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: ValueKind);
5722 }
5723 return;
5724 }
5725
5726 // - has a class type (i.e., T2 is a class type), where T1 is not
5727 // reference-related to T2, and can be implicitly converted to an
5728 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5729 // where "cv1 T1" is reference-compatible with "cv3 T3",
5730 //
5731 // DR1287 removes the "implicitly" here.
5732 if (T2->isRecordType()) {
5733 if (RefRelationship == Sema::Ref_Incompatible) {
5734 ConvOvlResult = TryRefInitWithConversionFunction(
5735 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5736 /*IsLValueRef*/ isLValueRef, Sequence);
5737 if (ConvOvlResult)
5738 Sequence.SetOverloadFailure(
5739 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5740 Result: ConvOvlResult);
5741
5742 return;
5743 }
5744
5745 if (RefRelationship == Sema::Ref_Compatible &&
5746 isRValueRef && InitCategory.isLValue()) {
5747 Sequence.SetFailed(
5748 InitializationSequence::FK_RValueReferenceBindingToLValue);
5749 return;
5750 }
5751
5752 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5753 return;
5754 }
5755
5756 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5757 // from the initializer expression using the rules for a non-reference
5758 // copy-initialization (8.5). The reference is then bound to the
5759 // temporary. [...]
5760
5761 // Ignore address space of reference type at this point and perform address
5762 // space conversion after the reference binding step.
5763 QualType cv1T1IgnoreAS =
5764 T1Quals.hasAddressSpace()
5765 ? S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace())
5766 : cv1T1;
5767
5768 InitializedEntity TempEntity =
5769 InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS);
5770
5771 // FIXME: Why do we use an implicit conversion here rather than trying
5772 // copy-initialization?
5773 ImplicitConversionSequence ICS
5774 = S.TryImplicitConversion(From: Initializer, ToType: TempEntity.getType(),
5775 /*SuppressUserConversions=*/false,
5776 AllowExplicit: Sema::AllowedExplicit::None,
5777 /*FIXME:InOverloadResolution=*/InOverloadResolution: false,
5778 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5779 /*AllowObjCWritebackConversion=*/false);
5780
5781 if (ICS.isBad()) {
5782 // FIXME: Use the conversion function set stored in ICS to turn
5783 // this into an overloading ambiguity diagnostic. However, we need
5784 // to keep that set as an OverloadCandidateSet rather than as some
5785 // other kind of set.
5786 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5787 Sequence.SetOverloadFailure(
5788 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5789 Result: ConvOvlResult);
5790 else if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy)
5791 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5792 else
5793 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5794 return;
5795 } else {
5796 Sequence.AddConversionSequenceStep(ICS, T: TempEntity.getType(),
5797 TopLevelOfInitList);
5798 }
5799
5800 // [...] If T1 is reference-related to T2, cv1 must be the
5801 // same cv-qualification as, or greater cv-qualification
5802 // than, cv2; otherwise, the program is ill-formed.
5803 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5804 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5805 if (RefRelationship == Sema::Ref_Related &&
5806 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5807 !T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) {
5808 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5809 return;
5810 }
5811
5812 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5813 // reference, the initializer expression shall not be an lvalue.
5814 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5815 InitCategory.isLValue()) {
5816 Sequence.SetFailed(
5817 InitializationSequence::FK_RValueReferenceBindingToLValue);
5818 return;
5819 }
5820
5821 Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, /*BindingTemporary=*/true);
5822
5823 if (T1Quals.hasAddressSpace()) {
5824 if (!Qualifiers::isAddressSpaceSupersetOf(
5825 A: T1Quals.getAddressSpace(), B: LangAS::Default, Ctx: S.getASTContext())) {
5826 Sequence.SetFailed(
5827 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5828 return;
5829 }
5830 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: isLValueRef ? VK_LValue
5831 : VK_XValue);
5832 }
5833}
5834
5835/// Attempt character array initialization from a string literal
5836/// (C++ [dcl.init.string], C99 6.7.8).
5837static void TryStringLiteralInitialization(Sema &S,
5838 const InitializedEntity &Entity,
5839 const InitializationKind &Kind,
5840 Expr *Initializer,
5841 InitializationSequence &Sequence) {
5842 Sequence.AddStringInitStep(T: Entity.getType());
5843}
5844
5845/// Attempt value initialization (C++ [dcl.init]p7).
5846static void TryValueInitialization(Sema &S,
5847 const InitializedEntity &Entity,
5848 const InitializationKind &Kind,
5849 InitializationSequence &Sequence,
5850 InitListExpr *InitList) {
5851 assert((!InitList || InitList->getNumInits() == 0) &&
5852 "Shouldn't use value-init for non-empty init lists");
5853
5854 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5855 //
5856 // To value-initialize an object of type T means:
5857 QualType T = Entity.getType();
5858 assert(!T->isVoidType() && "Cannot value-init void");
5859
5860 // -- if T is an array type, then each element is value-initialized;
5861 T = S.Context.getBaseElementType(QT: T);
5862
5863 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
5864 bool NeedZeroInitialization = true;
5865 // C++98:
5866 // -- if T is a class type (clause 9) with a user-declared constructor
5867 // (12.1), then the default constructor for T is called (and the
5868 // initialization is ill-formed if T has no accessible default
5869 // constructor);
5870 // C++11:
5871 // -- if T is a class type (clause 9) with either no default constructor
5872 // (12.1 [class.ctor]) or a default constructor that is user-provided
5873 // or deleted, then the object is default-initialized;
5874 //
5875 // Note that the C++11 rule is the same as the C++98 rule if there are no
5876 // defaulted or deleted constructors, so we just use it unconditionally.
5877 CXXConstructorDecl *CD = S.LookupDefaultConstructor(Class: ClassDecl);
5878 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5879 NeedZeroInitialization = false;
5880
5881 // -- if T is a (possibly cv-qualified) non-union class type without a
5882 // user-provided or deleted default constructor, then the object is
5883 // zero-initialized and, if T has a non-trivial default constructor,
5884 // default-initialized;
5885 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5886 // constructor' part was removed by DR1507.
5887 if (NeedZeroInitialization)
5888 Sequence.AddZeroInitializationStep(T: Entity.getType());
5889
5890 // C++03:
5891 // -- if T is a non-union class type without a user-declared constructor,
5892 // then every non-static data member and base class component of T is
5893 // value-initialized;
5894 // [...] A program that calls for [...] value-initialization of an
5895 // entity of reference type is ill-formed.
5896 //
5897 // C++11 doesn't need this handling, because value-initialization does not
5898 // occur recursively there, and the implicit default constructor is
5899 // defined as deleted in the problematic cases.
5900 if (!S.getLangOpts().CPlusPlus11 &&
5901 ClassDecl->hasUninitializedReferenceMember()) {
5902 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5903 return;
5904 }
5905
5906 // If this is list-value-initialization, pass the empty init list on when
5907 // building the constructor call. This affects the semantics of a few
5908 // things (such as whether an explicit default constructor can be called).
5909 Expr *InitListAsExpr = InitList;
5910 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5911 bool InitListSyntax = InitList;
5912
5913 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5914 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5915 return TryConstructorInitialization(
5916 S, Entity, Kind, Args, DestType: T, DestArrayType: Entity.getType(), Sequence, IsListInit: InitListSyntax);
5917 }
5918
5919 Sequence.AddZeroInitializationStep(T: Entity.getType());
5920}
5921
5922/// Attempt default initialization (C++ [dcl.init]p6).
5923static void TryDefaultInitialization(Sema &S,
5924 const InitializedEntity &Entity,
5925 const InitializationKind &Kind,
5926 InitializationSequence &Sequence) {
5927 assert(Kind.getKind() == InitializationKind::IK_Default);
5928
5929 // C++ [dcl.init]p6:
5930 // To default-initialize an object of type T means:
5931 // - if T is an array type, each element is default-initialized;
5932 QualType DestType = S.Context.getBaseElementType(QT: Entity.getType());
5933
5934 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5935 // constructor for T is called (and the initialization is ill-formed if
5936 // T has no accessible default constructor);
5937 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5938 TryConstructorInitialization(S, Entity, Kind, Args: {}, DestType,
5939 DestArrayType: Entity.getType(), Sequence);
5940 return;
5941 }
5942
5943 // - otherwise, no initialization is performed.
5944
5945 // If a program calls for the default initialization of an object of
5946 // a const-qualified type T, T shall be a class type with a user-provided
5947 // default constructor.
5948 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5949 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5950 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5951 return;
5952 }
5953
5954 // If the destination type has a lifetime property, zero-initialize it.
5955 if (DestType.getQualifiers().hasObjCLifetime()) {
5956 Sequence.AddZeroInitializationStep(T: Entity.getType());
5957 return;
5958 }
5959}
5960
5961static void TryOrBuildParenListInitialization(
5962 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5963 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5964 ExprResult *Result) {
5965 unsigned EntityIndexToProcess = 0;
5966 SmallVector<Expr *, 4> InitExprs;
5967 QualType ResultType;
5968 Expr *ArrayFiller = nullptr;
5969 FieldDecl *InitializedFieldInUnion = nullptr;
5970
5971 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5972 const InitializationKind &SubKind,
5973 Expr *Arg, Expr **InitExpr = nullptr) {
5974 InitializationSequence IS = InitializationSequence(
5975 S, SubEntity, SubKind,
5976 Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5977
5978 if (IS.Failed()) {
5979 if (!VerifyOnly) {
5980 IS.Diagnose(S, Entity: SubEntity, Kind: SubKind,
5981 Args: Arg ? ArrayRef(Arg) : ArrayRef<Expr *>());
5982 } else {
5983 Sequence.SetFailed(
5984 InitializationSequence::FK_ParenthesizedListInitFailed);
5985 }
5986
5987 return false;
5988 }
5989 if (!VerifyOnly) {
5990 ExprResult ER;
5991 ER = IS.Perform(S, Entity: SubEntity, Kind: SubKind,
5992 Args: Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>());
5993
5994 if (ER.isInvalid())
5995 return false;
5996
5997 if (InitExpr)
5998 *InitExpr = ER.get();
5999 else
6000 InitExprs.push_back(Elt: ER.get());
6001 }
6002 return true;
6003 };
6004
6005 if (const ArrayType *AT =
6006 S.getASTContext().getAsArrayType(T: Entity.getType())) {
6007 uint64_t ArrayLength;
6008 // C++ [dcl.init]p16.5
6009 // if the destination type is an array, the object is initialized as
6010 // follows. Let x1, . . . , xk be the elements of the expression-list. If
6011 // the destination type is an array of unknown bound, it is defined as
6012 // having k elements.
6013 if (const ConstantArrayType *CAT =
6014 S.getASTContext().getAsConstantArrayType(T: Entity.getType())) {
6015 ArrayLength = CAT->getZExtSize();
6016 ResultType = Entity.getType();
6017 } else if (const VariableArrayType *VAT =
6018 S.getASTContext().getAsVariableArrayType(T: Entity.getType())) {
6019 // Braced-initialization of variable array types is not allowed, even if
6020 // the size is greater than or equal to the number of args, so we don't
6021 // allow them to be initialized via parenthesized aggregate initialization
6022 // either.
6023 const Expr *SE = VAT->getSizeExpr();
6024 S.Diag(Loc: SE->getBeginLoc(), DiagID: diag::err_variable_object_no_init)
6025 << SE->getSourceRange();
6026 return;
6027 } else {
6028 assert(Entity.getType()->isIncompleteArrayType());
6029 ArrayLength = Args.size();
6030 }
6031 EntityIndexToProcess = ArrayLength;
6032
6033 // ...the ith array element is copy-initialized with xi for each
6034 // 1 <= i <= k
6035 for (Expr *E : Args) {
6036 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
6037 Context&: S.getASTContext(), Index: EntityIndexToProcess, Parent: Entity);
6038 InitializationKind SubKind = InitializationKind::CreateForInit(
6039 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
6040 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6041 return;
6042 }
6043 // ...and value-initialized for each k < i <= n;
6044 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
6045 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
6046 Context&: S.getASTContext(), Index: Args.size(), Parent: Entity);
6047 InitializationKind SubKind = InitializationKind::CreateValue(
6048 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true);
6049 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
6050 return;
6051 }
6052
6053 if (ResultType.isNull()) {
6054 ResultType = S.Context.getConstantArrayType(
6055 EltTy: AT->getElementType(), ArySize: llvm::APInt(/*numBits=*/32, ArrayLength),
6056 /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6057 }
6058 } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) {
6059 bool IsUnion = RD->isUnion();
6060 if (RD->isInvalidDecl()) {
6061 // Exit early to avoid confusion when processing members.
6062 // We do the same for braced list initialization in
6063 // `CheckStructUnionTypes`.
6064 Sequence.SetFailed(
6065 clang::InitializationSequence::FK_ParenthesizedListInitFailed);
6066 return;
6067 }
6068
6069 if (!IsUnion) {
6070 for (const CXXBaseSpecifier &Base : RD->bases()) {
6071 InitializedEntity SubEntity = InitializedEntity::InitializeBase(
6072 Context&: S.getASTContext(), Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity);
6073 if (EntityIndexToProcess < Args.size()) {
6074 // C++ [dcl.init]p16.6.2.2.
6075 // ...the object is initialized is follows. Let e1, ..., en be the
6076 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
6077 // the elements of the expression-list...The element ei is
6078 // copy-initialized with xi for 1 <= i <= k.
6079 Expr *E = Args[EntityIndexToProcess];
6080 InitializationKind SubKind = InitializationKind::CreateForInit(
6081 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
6082 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6083 return;
6084 } else {
6085 // We've processed all of the args, but there are still base classes
6086 // that have to be initialized.
6087 // C++ [dcl.init]p17.6.2.2
6088 // The remaining elements...otherwise are value initialzed
6089 InitializationKind SubKind = InitializationKind::CreateValue(
6090 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(),
6091 /*IsImplicit=*/isImplicit: true);
6092 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6093 return;
6094 }
6095 EntityIndexToProcess++;
6096 }
6097 }
6098
6099 for (FieldDecl *FD : RD->fields()) {
6100 // Unnamed bitfields should not be initialized at all, either with an arg
6101 // or by default.
6102 if (FD->isUnnamedBitField())
6103 continue;
6104
6105 InitializedEntity SubEntity =
6106 InitializedEntity::InitializeMemberFromParenAggInit(Member: FD);
6107
6108 if (EntityIndexToProcess < Args.size()) {
6109 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
6110 Expr *E = Args[EntityIndexToProcess];
6111
6112 // Incomplete array types indicate flexible array members. Do not allow
6113 // paren list initializations of structs with these members, as GCC
6114 // doesn't either.
6115 if (FD->getType()->isIncompleteArrayType()) {
6116 if (!VerifyOnly) {
6117 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_flexible_array_init)
6118 << SourceRange(E->getBeginLoc(), E->getEndLoc());
6119 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_flexible_array_member) << FD;
6120 }
6121 Sequence.SetFailed(
6122 InitializationSequence::FK_ParenthesizedListInitFailed);
6123 return;
6124 }
6125
6126 InitializationKind SubKind = InitializationKind::CreateForInit(
6127 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
6128 if (!HandleInitializedEntity(SubEntity, SubKind, E))
6129 return;
6130
6131 // Unions should have only one initializer expression, so we bail out
6132 // after processing the first field. If there are more initializers then
6133 // it will be caught when we later check whether EntityIndexToProcess is
6134 // less than Args.size();
6135 if (IsUnion) {
6136 InitializedFieldInUnion = FD;
6137 EntityIndexToProcess = 1;
6138 break;
6139 }
6140 } else {
6141 // We've processed all of the args, but there are still members that
6142 // have to be initialized.
6143 if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() &&
6144 !S.isUnevaluatedContext()) {
6145 S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init)
6146 << /* Var-in-Record */ 0 << FD;
6147 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD;
6148 }
6149
6150 if (FD->hasInClassInitializer()) {
6151 if (!VerifyOnly) {
6152 // C++ [dcl.init]p16.6.2.2
6153 // The remaining elements are initialized with their default
6154 // member initializers, if any
6155 ExprResult DIE = S.BuildCXXDefaultInitExpr(
6156 Loc: Kind.getParenOrBraceRange().getEnd(), Field: FD);
6157 if (DIE.isInvalid())
6158 return;
6159 S.checkInitializerLifetime(Entity: SubEntity, Init: DIE.get());
6160 InitExprs.push_back(Elt: DIE.get());
6161 }
6162 } else {
6163 // C++ [dcl.init]p17.6.2.2
6164 // The remaining elements...otherwise are value initialzed
6165 if (FD->getType()->isReferenceType()) {
6166 Sequence.SetFailed(
6167 InitializationSequence::FK_ParenthesizedListInitFailed);
6168 if (!VerifyOnly) {
6169 SourceRange SR = Kind.getParenOrBraceRange();
6170 S.Diag(Loc: SR.getEnd(), DiagID: diag::err_init_reference_member_uninitialized)
6171 << FD->getType() << SR;
6172 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_uninit_reference_member);
6173 }
6174 return;
6175 }
6176 InitializationKind SubKind = InitializationKind::CreateValue(
6177 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true);
6178 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
6179 return;
6180 }
6181 }
6182 EntityIndexToProcess++;
6183 }
6184 ResultType = Entity.getType();
6185 }
6186
6187 // Not all of the args have been processed, so there must've been more args
6188 // than were required to initialize the element.
6189 if (EntityIndexToProcess < Args.size()) {
6190 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
6191 if (!VerifyOnly) {
6192 QualType T = Entity.getType();
6193 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5;
6194 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
6195 Args.back()->getEndLoc());
6196 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers)
6197 << InitKind << ExcessInitSR;
6198 }
6199 return;
6200 }
6201
6202 if (VerifyOnly) {
6203 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
6204 Sequence.AddParenthesizedListInitStep(T: Entity.getType());
6205 } else if (Result) {
6206 SourceRange SR = Kind.getParenOrBraceRange();
6207 auto *CPLIE = CXXParenListInitExpr::Create(
6208 C&: S.getASTContext(), Args: InitExprs, T: ResultType, NumUserSpecifiedExprs: Args.size(),
6209 InitLoc: Kind.getLocation(), LParenLoc: SR.getBegin(), RParenLoc: SR.getEnd());
6210 if (ArrayFiller)
6211 CPLIE->setArrayFiller(ArrayFiller);
6212 if (InitializedFieldInUnion)
6213 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
6214 *Result = CPLIE;
6215 S.Diag(Loc: Kind.getLocation(),
6216 DiagID: diag::warn_cxx17_compat_aggregate_init_paren_list)
6217 << Kind.getLocation() << SR << ResultType;
6218 }
6219}
6220
6221/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
6222/// which enumerates all conversion functions and performs overload resolution
6223/// to select the best.
6224static void TryUserDefinedConversion(Sema &S,
6225 QualType DestType,
6226 const InitializationKind &Kind,
6227 Expr *Initializer,
6228 InitializationSequence &Sequence,
6229 bool TopLevelOfInitList) {
6230 assert(!DestType->isReferenceType() && "References are handled elsewhere");
6231 QualType SourceType = Initializer->getType();
6232 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
6233 "Must have a class type to perform a user-defined conversion");
6234
6235 // Build the candidate set directly in the initialization sequence
6236 // structure, so that it will persist if we fail.
6237 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
6238 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
6239 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
6240
6241 // Determine whether we are allowed to call explicit constructors or
6242 // explicit conversion operators.
6243 bool AllowExplicit = Kind.AllowExplicit();
6244
6245 if (DestType->isRecordType()) {
6246 // The type we're converting to is a class type. Enumerate its constructors
6247 // to see if there is a suitable conversion.
6248 // Try to complete the type we're converting to.
6249 if (S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) {
6250 auto *DestRecordDecl = DestType->castAsCXXRecordDecl();
6251 for (NamedDecl *D : S.LookupConstructors(Class: DestRecordDecl)) {
6252 auto Info = getConstructorInfo(ND: D);
6253 if (!Info.Constructor)
6254 continue;
6255
6256 if (!Info.Constructor->isInvalidDecl() &&
6257 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
6258 if (Info.ConstructorTmpl)
6259 S.AddTemplateOverloadCandidate(
6260 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
6261 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet,
6262 /*SuppressUserConversions=*/true,
6263 /*PartialOverloading*/ false, AllowExplicit);
6264 else
6265 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
6266 Args: Initializer, CandidateSet,
6267 /*SuppressUserConversions=*/true,
6268 /*PartialOverloading*/ false, AllowExplicit);
6269 }
6270 }
6271 }
6272 }
6273
6274 SourceLocation DeclLoc = Initializer->getBeginLoc();
6275
6276 if (SourceType->isRecordType()) {
6277 // The type we're converting from is a class type, enumerate its conversion
6278 // functions.
6279
6280 // We can only enumerate the conversion functions for a complete type; if
6281 // the type isn't complete, simply skip this step.
6282 if (S.isCompleteType(Loc: DeclLoc, T: SourceType)) {
6283 auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl();
6284 const auto &Conversions =
6285 SourceRecordDecl->getVisibleConversionFunctions();
6286 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6287 NamedDecl *D = *I;
6288 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
6289 if (isa<UsingShadowDecl>(Val: D))
6290 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6291
6292 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
6293 CXXConversionDecl *Conv;
6294 if (ConvTemplate)
6295 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
6296 else
6297 Conv = cast<CXXConversionDecl>(Val: D);
6298
6299 if (ConvTemplate)
6300 S.AddTemplateConversionCandidate(
6301 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
6302 CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit);
6303 else
6304 S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer,
6305 ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit,
6306 AllowExplicit);
6307 }
6308 }
6309 }
6310
6311 // Perform overload resolution. If it fails, return the failed result.
6312 OverloadCandidateSet::iterator Best;
6313 if (OverloadingResult Result
6314 = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
6315 Sequence.SetOverloadFailure(
6316 Failure: InitializationSequence::FK_UserConversionOverloadFailed, Result);
6317
6318 // [class.copy.elision]p3:
6319 // In some copy-initialization contexts, a two-stage overload resolution
6320 // is performed.
6321 // If the first overload resolution selects a deleted function, we also
6322 // need the initialization sequence to decide whether to perform the second
6323 // overload resolution.
6324 if (!(Result == OR_Deleted &&
6325 Kind.getKind() == InitializationKind::IK_Copy))
6326 return;
6327 }
6328
6329 FunctionDecl *Function = Best->Function;
6330 Function->setReferenced();
6331 bool HadMultipleCandidates = (CandidateSet.size() > 1);
6332
6333 if (isa<CXXConstructorDecl>(Val: Function)) {
6334 // Add the user-defined conversion step. Any cv-qualification conversion is
6335 // subsumed by the initialization. Per DR5, the created temporary is of the
6336 // cv-unqualified type of the destination.
6337 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl,
6338 T: DestType.getUnqualifiedType(),
6339 HadMultipleCandidates);
6340
6341 // C++14 and before:
6342 // - if the function is a constructor, the call initializes a temporary
6343 // of the cv-unqualified version of the destination type. The [...]
6344 // temporary [...] is then used to direct-initialize, according to the
6345 // rules above, the object that is the destination of the
6346 // copy-initialization.
6347 // Note that this just performs a simple object copy from the temporary.
6348 //
6349 // C++17:
6350 // - if the function is a constructor, the call is a prvalue of the
6351 // cv-unqualified version of the destination type whose return object
6352 // is initialized by the constructor. The call is used to
6353 // direct-initialize, according to the rules above, the object that
6354 // is the destination of the copy-initialization.
6355 // Therefore we need to do nothing further.
6356 //
6357 // FIXME: Mark this copy as extraneous.
6358 if (!S.getLangOpts().CPlusPlus17)
6359 Sequence.AddFinalCopy(T: DestType);
6360 else if (DestType.hasQualifiers())
6361 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
6362 return;
6363 }
6364
6365 // Add the user-defined conversion step that calls the conversion function.
6366 QualType ConvType = Function->getCallResultType();
6367 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: ConvType,
6368 HadMultipleCandidates);
6369
6370 if (ConvType->isRecordType()) {
6371 if (S.getLangOpts().HLSL &&
6372 ConvType.getAddressSpace() == LangAS::hlsl_constant &&
6373 S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType)) {
6374 Sequence.AddHLSLBufferConversionStep(T: ConvType);
6375 return;
6376 }
6377
6378 // The call is used to direct-initialize [...] the object that is the
6379 // destination of the copy-initialization.
6380 //
6381 // In C++17, this does not call a constructor if we enter /17.6.1:
6382 // - If the initializer expression is a prvalue and the cv-unqualified
6383 // version of the source type is the same as the class of the
6384 // destination [... do not make an extra copy]
6385 //
6386 // FIXME: Mark this copy as extraneous.
6387 if (!S.getLangOpts().CPlusPlus17 ||
6388 Function->getReturnType()->isReferenceType() ||
6389 !S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType))
6390 Sequence.AddFinalCopy(T: DestType);
6391 else if (!S.Context.hasSameType(T1: ConvType, T2: DestType))
6392 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
6393 return;
6394 }
6395
6396 // If the conversion following the call to the conversion function
6397 // is interesting, add it as a separate step.
6398 assert(Best->HasFinalConversion);
6399 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
6400 Best->FinalConversion.Third) {
6401 ImplicitConversionSequence ICS;
6402 ICS.setStandard();
6403 ICS.Standard = Best->FinalConversion;
6404 Sequence.AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList);
6405 }
6406}
6407
6408/// The non-zero enum values here are indexes into diagnostic alternatives.
6409enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
6410
6411/// Determines whether this expression is an acceptable ICR source.
6412static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
6413 bool isAddressOf, bool &isWeakAccess) {
6414 // Skip parens.
6415 e = e->IgnoreParens();
6416
6417 // Skip address-of nodes.
6418 if (UnaryOperator *op = dyn_cast<UnaryOperator>(Val: e)) {
6419 if (op->getOpcode() == UO_AddrOf)
6420 return isInvalidICRSource(C, e: op->getSubExpr(), /*addressof*/ isAddressOf: true,
6421 isWeakAccess);
6422
6423 // Skip certain casts.
6424 } else if (CastExpr *ce = dyn_cast<CastExpr>(Val: e)) {
6425 switch (ce->getCastKind()) {
6426 case CK_Dependent:
6427 case CK_BitCast:
6428 case CK_LValueBitCast:
6429 case CK_NoOp:
6430 return isInvalidICRSource(C, e: ce->getSubExpr(), isAddressOf, isWeakAccess);
6431
6432 case CK_ArrayToPointerDecay:
6433 return IIK_nonscalar;
6434
6435 case CK_NullToPointer:
6436 return IIK_okay;
6437
6438 default:
6439 break;
6440 }
6441
6442 // If we have a declaration reference, it had better be a local variable.
6443 } else if (isa<DeclRefExpr>(Val: e)) {
6444 // set isWeakAccess to true, to mean that there will be an implicit
6445 // load which requires a cleanup.
6446 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
6447 isWeakAccess = true;
6448
6449 if (!isAddressOf) return IIK_nonlocal;
6450
6451 VarDecl *var = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: e)->getDecl());
6452 if (!var) return IIK_nonlocal;
6453
6454 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
6455
6456 // If we have a conditional operator, check both sides.
6457 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(Val: e)) {
6458 if (InvalidICRKind iik = isInvalidICRSource(C, e: cond->getLHS(), isAddressOf,
6459 isWeakAccess))
6460 return iik;
6461
6462 return isInvalidICRSource(C, e: cond->getRHS(), isAddressOf, isWeakAccess);
6463
6464 // These are never scalar.
6465 } else if (isa<ArraySubscriptExpr>(Val: e)) {
6466 return IIK_nonscalar;
6467
6468 // Otherwise, it needs to be a null pointer constant.
6469 } else {
6470 return (e->isNullPointerConstant(Ctx&: C, NPC: Expr::NPC_ValueDependentIsNull)
6471 ? IIK_okay : IIK_nonlocal);
6472 }
6473
6474 return IIK_nonlocal;
6475}
6476
6477/// Check whether the given expression is a valid operand for an
6478/// indirect copy/restore.
6479static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
6480 assert(src->isPRValue());
6481 bool isWeakAccess = false;
6482 InvalidICRKind iik = isInvalidICRSource(C&: S.Context, e: src, isAddressOf: false, isWeakAccess);
6483 // If isWeakAccess to true, there will be an implicit
6484 // load which requires a cleanup.
6485 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
6486 S.Cleanup.setExprNeedsCleanups(true);
6487
6488 if (iik == IIK_okay) return;
6489
6490 S.Diag(Loc: src->getExprLoc(), DiagID: diag::err_arc_nonlocal_writeback)
6491 << ((unsigned) iik - 1) // shift index into diagnostic explanations
6492 << src->getSourceRange();
6493}
6494
6495/// Determine whether we have compatible array types for the
6496/// purposes of GNU by-copy array initialization.
6497static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
6498 const ArrayType *Source) {
6499 // If the source and destination array types are equivalent, we're
6500 // done.
6501 if (Context.hasSameType(T1: QualType(Dest, 0), T2: QualType(Source, 0)))
6502 return true;
6503
6504 // Make sure that the element types are the same.
6505 if (!Context.hasSameType(T1: Dest->getElementType(), T2: Source->getElementType()))
6506 return false;
6507
6508 // The only mismatch we allow is when the destination is an
6509 // incomplete array type and the source is a constant array type.
6510 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6511}
6512
6513static bool tryObjCWritebackConversion(Sema &S,
6514 InitializationSequence &Sequence,
6515 const InitializedEntity &Entity,
6516 Expr *Initializer) {
6517 bool ArrayDecay = false;
6518 QualType ArgType = Initializer->getType();
6519 QualType ArgPointee;
6520 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(T: ArgType)) {
6521 ArrayDecay = true;
6522 ArgPointee = ArgArrayType->getElementType();
6523 ArgType = S.Context.getPointerType(T: ArgPointee);
6524 }
6525
6526 // Handle write-back conversion.
6527 QualType ConvertedArgType;
6528 if (!S.ObjC().isObjCWritebackConversion(FromType: ArgType, ToType: Entity.getType(),
6529 ConvertedType&: ConvertedArgType))
6530 return false;
6531
6532 // We should copy unless we're passing to an argument explicitly
6533 // marked 'out'.
6534 bool ShouldCopy = true;
6535 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl()))
6536 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6537
6538 // Do we need an lvalue conversion?
6539 if (ArrayDecay || Initializer->isGLValue()) {
6540 ImplicitConversionSequence ICS;
6541 ICS.setStandard();
6542 ICS.Standard.setAsIdentityConversion();
6543
6544 QualType ResultType;
6545 if (ArrayDecay) {
6546 ICS.Standard.First = ICK_Array_To_Pointer;
6547 ResultType = S.Context.getPointerType(T: ArgPointee);
6548 } else {
6549 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
6550 ResultType = Initializer->getType().getNonLValueExprType(Context: S.Context);
6551 }
6552
6553 Sequence.AddConversionSequenceStep(ICS, T: ResultType);
6554 }
6555
6556 Sequence.AddPassByIndirectCopyRestoreStep(type: Entity.getType(), shouldCopy: ShouldCopy);
6557 return true;
6558}
6559
6560static bool TryOCLSamplerInitialization(Sema &S,
6561 InitializationSequence &Sequence,
6562 QualType DestType,
6563 Expr *Initializer) {
6564 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6565 (!Initializer->isIntegerConstantExpr(Ctx: S.Context) &&
6566 !Initializer->getType()->isSamplerT()))
6567 return false;
6568
6569 Sequence.AddOCLSamplerInitStep(T: DestType);
6570 return true;
6571}
6572
6573static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) {
6574 std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx);
6575 return Value && Value->isZero();
6576}
6577
6578static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
6579 InitializationSequence &Sequence,
6580 QualType DestType,
6581 Expr *Initializer) {
6582 if (!S.getLangOpts().OpenCL)
6583 return false;
6584
6585 //
6586 // OpenCL 1.2 spec, s6.12.10
6587 //
6588 // The event argument can also be used to associate the
6589 // async_work_group_copy with a previous async copy allowing
6590 // an event to be shared by multiple async copies; otherwise
6591 // event should be zero.
6592 //
6593 if (DestType->isEventT() || DestType->isQueueT()) {
6594 if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext()))
6595 return false;
6596
6597 Sequence.AddOCLZeroOpaqueTypeStep(T: DestType);
6598 return true;
6599 }
6600
6601 // We should allow zero initialization for all types defined in the
6602 // cl_intel_device_side_avc_motion_estimation extension, except
6603 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6604 if (S.getOpenCLOptions().isAvailableOption(
6605 Ext: "cl_intel_device_side_avc_motion_estimation", LO: S.getLangOpts()) &&
6606 DestType->isOCLIntelSubgroupAVCType()) {
6607 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6608 DestType->isOCLIntelSubgroupAVCMceResultType())
6609 return false;
6610 if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext()))
6611 return false;
6612
6613 Sequence.AddOCLZeroOpaqueTypeStep(T: DestType);
6614 return true;
6615 }
6616
6617 return false;
6618}
6619
6620InitializationSequence::InitializationSequence(
6621 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6622 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6623 : FailedOverloadResult(OR_Success),
6624 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6625 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6626 TreatUnavailableAsInvalid);
6627}
6628
6629/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6630/// address of that function, this returns true. Otherwise, it returns false.
6631static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6632 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
6633 if (!DRE || !isa<FunctionDecl>(Val: DRE->getDecl()))
6634 return false;
6635
6636 return !S.checkAddressOfFunctionIsAvailable(
6637 Function: cast<FunctionDecl>(Val: DRE->getDecl()));
6638}
6639
6640/// Determine whether we can perform an elementwise array copy for this kind
6641/// of entity.
6642static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6643 switch (Entity.getKind()) {
6644 case InitializedEntity::EK_LambdaCapture:
6645 // C++ [expr.prim.lambda]p24:
6646 // For array members, the array elements are direct-initialized in
6647 // increasing subscript order.
6648 return true;
6649
6650 case InitializedEntity::EK_Variable:
6651 // C++ [dcl.decomp]p1:
6652 // [...] each element is copy-initialized or direct-initialized from the
6653 // corresponding element of the assignment-expression [...]
6654 return isa<DecompositionDecl>(Val: Entity.getDecl());
6655
6656 case InitializedEntity::EK_Member:
6657 // C++ [class.copy.ctor]p14:
6658 // - if the member is an array, each element is direct-initialized with
6659 // the corresponding subobject of x
6660 return Entity.isImplicitMemberInitializer();
6661
6662 case InitializedEntity::EK_ArrayElement:
6663 // All the above cases are intended to apply recursively, even though none
6664 // of them actually say that.
6665 if (auto *E = Entity.getParent())
6666 return canPerformArrayCopy(Entity: *E);
6667 break;
6668
6669 default:
6670 break;
6671 }
6672
6673 return false;
6674}
6675
6676static const FieldDecl *getConstField(const RecordDecl *RD) {
6677 assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode");
6678 for (const FieldDecl *FD : RD->fields()) {
6679 // If the field is a flexible array member, we don't want to consider it
6680 // as a const field because there's no way to initialize the FAM anyway.
6681 const ASTContext &Ctx = FD->getASTContext();
6682 if (Decl::isFlexibleArrayMemberLike(
6683 Context: Ctx, D: FD, Ty: FD->getType(),
6684 StrictFlexArraysLevel: Ctx.getLangOpts().getStrictFlexArraysLevel(),
6685 /*IgnoreTemplateOrMacroSubstitution=*/true))
6686 continue;
6687
6688 QualType QT = FD->getType();
6689 if (QT.isConstQualified())
6690 return FD;
6691 if (const auto *RD = QT->getAsRecordDecl()) {
6692 if (const FieldDecl *FD = getConstField(RD))
6693 return FD;
6694 }
6695 }
6696 return nullptr;
6697}
6698
6699void InitializationSequence::InitializeFrom(Sema &S,
6700 const InitializedEntity &Entity,
6701 const InitializationKind &Kind,
6702 MultiExprArg Args,
6703 bool TopLevelOfInitList,
6704 bool TreatUnavailableAsInvalid) {
6705 ASTContext &Context = S.Context;
6706
6707 // Eliminate non-overload placeholder types in the arguments. We
6708 // need to do this before checking whether types are dependent
6709 // because lowering a pseudo-object expression might well give us
6710 // something of dependent type.
6711 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6712 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6713 // FIXME: should we be doing this here?
6714 ExprResult result = S.CheckPlaceholderExpr(E: Args[I]);
6715 if (result.isInvalid()) {
6716 SetFailed(FK_PlaceholderType);
6717 return;
6718 }
6719 Args[I] = result.get();
6720 }
6721
6722 // C++0x [dcl.init]p16:
6723 // The semantics of initializers are as follows. The destination type is
6724 // the type of the object or reference being initialized and the source
6725 // type is the type of the initializer expression. The source type is not
6726 // defined when the initializer is a braced-init-list or when it is a
6727 // parenthesized list of expressions.
6728 QualType DestType = Entity.getType();
6729
6730 if (DestType->isDependentType() ||
6731 Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
6732 SequenceKind = DependentSequence;
6733 return;
6734 }
6735
6736 // Almost everything is a normal sequence.
6737 setSequenceKind(NormalSequence);
6738
6739 QualType SourceType;
6740 Expr *Initializer = nullptr;
6741 if (Args.size() == 1) {
6742 Initializer = Args[0];
6743 if (S.getLangOpts().ObjC) {
6744 if (S.ObjC().CheckObjCBridgeRelatedConversions(
6745 Loc: Initializer->getBeginLoc(), DestType, SrcType: Initializer->getType(),
6746 SrcExpr&: Initializer) ||
6747 S.ObjC().CheckConversionToObjCLiteral(DstType: DestType, SrcExpr&: Initializer))
6748 Args[0] = Initializer;
6749 }
6750 if (!isa<InitListExpr>(Val: Initializer))
6751 SourceType = Initializer->getType();
6752 }
6753
6754 // - If the initializer is a (non-parenthesized) braced-init-list, the
6755 // object is list-initialized (8.5.4).
6756 if (Kind.getKind() != InitializationKind::IK_Direct) {
6757 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Val: Initializer)) {
6758 TryListInitialization(S, Entity, Kind, InitList, Sequence&: *this,
6759 TreatUnavailableAsInvalid);
6760 return;
6761 }
6762 }
6763
6764 if (!S.getLangOpts().CPlusPlus &&
6765 Kind.getKind() == InitializationKind::IK_Default) {
6766 if (RecordDecl *Rec = DestType->getAsRecordDecl()) {
6767 VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: Entity.getDecl());
6768 if (Rec->hasUninitializedExplicitInitFields()) {
6769 if (Var && !Initializer && !S.isUnevaluatedContext()) {
6770 S.Diag(Loc: Var->getLocation(), DiagID: diag::warn_field_requires_explicit_init)
6771 << /* Var-in-Record */ 1 << Rec;
6772 emitUninitializedExplicitInitFields(S, R: Rec);
6773 }
6774 }
6775 // If the record has any members which are const (recursively checked),
6776 // then we want to diagnose those as being uninitialized if there is no
6777 // initializer present. However, we only do this for structure types, not
6778 // union types, because an unitialized field in a union is generally
6779 // reasonable, especially in C where unions can be used for type punning.
6780 if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) {
6781 if (const FieldDecl *FD = getConstField(RD: Rec)) {
6782 unsigned DiagID = diag::warn_default_init_const_field_unsafe;
6783 if (Var->getStorageDuration() == SD_Static ||
6784 Var->getStorageDuration() == SD_Thread)
6785 DiagID = diag::warn_default_init_const_field;
6786
6787 bool EmitCppCompat = !S.Diags.isIgnored(
6788 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
6789 Loc: Var->getLocation());
6790
6791 S.Diag(Loc: Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat;
6792 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_default_init_const_member) << FD;
6793 }
6794 }
6795 }
6796 }
6797
6798 // - If the destination type is a reference type, see 8.5.3.
6799 if (DestType->isReferenceType()) {
6800 // C++0x [dcl.init.ref]p1:
6801 // A variable declared to be a T& or T&&, that is, "reference to type T"
6802 // (8.3.2), shall be initialized by an object, or function, of type T or
6803 // by an object that can be converted into a T.
6804 // (Therefore, multiple arguments are not permitted.)
6805 if (Args.size() != 1)
6806 SetFailed(FK_TooManyInitsForReference);
6807 // C++17 [dcl.init.ref]p5:
6808 // A reference [...] is initialized by an expression [...] as follows:
6809 // If the initializer is not an expression, presumably we should reject,
6810 // but the standard fails to actually say so.
6811 else if (isa<InitListExpr>(Val: Args[0]))
6812 SetFailed(FK_ParenthesizedListInitForReference);
6813 else
6814 TryReferenceInitialization(S, Entity, Kind, Initializer: Args[0], Sequence&: *this,
6815 TopLevelOfInitList);
6816 return;
6817 }
6818
6819 // - If the initializer is (), the object is value-initialized.
6820 if (Kind.getKind() == InitializationKind::IK_Value ||
6821 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6822 TryValueInitialization(S, Entity, Kind, Sequence&: *this);
6823 return;
6824 }
6825
6826 // Handle default initialization.
6827 if (Kind.getKind() == InitializationKind::IK_Default) {
6828 TryDefaultInitialization(S, Entity, Kind, Sequence&: *this);
6829 return;
6830 }
6831
6832 // - If the destination type is an array of characters, an array of
6833 // char16_t, an array of char32_t, or an array of wchar_t, and the
6834 // initializer is a string literal, see 8.5.2.
6835 // - Otherwise, if the destination type is an array, the program is
6836 // ill-formed.
6837 // - Except in HLSL, where non-decaying array parameters behave like
6838 // non-array types for initialization.
6839 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6840 const ArrayType *DestAT = Context.getAsArrayType(T: DestType);
6841 if (Initializer && isa<VariableArrayType>(Val: DestAT)) {
6842 SetFailed(FK_VariableLengthArrayHasInitializer);
6843 return;
6844 }
6845
6846 if (Initializer) {
6847 switch (IsStringInit(Init: Initializer, AT: DestAT, Context)) {
6848 case SIF_None:
6849 TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence&: *this);
6850 return;
6851 case SIF_NarrowStringIntoWideChar:
6852 SetFailed(FK_NarrowStringIntoWideCharArray);
6853 return;
6854 case SIF_WideStringIntoChar:
6855 SetFailed(FK_WideStringIntoCharArray);
6856 return;
6857 case SIF_IncompatWideStringIntoWideChar:
6858 SetFailed(FK_IncompatWideStringIntoWideChar);
6859 return;
6860 case SIF_PlainStringIntoUTF8Char:
6861 SetFailed(FK_PlainStringIntoUTF8Char);
6862 return;
6863 case SIF_UTF8StringIntoPlainChar:
6864 SetFailed(FK_UTF8StringIntoPlainChar);
6865 return;
6866 case SIF_Other:
6867 break;
6868 }
6869 }
6870
6871 if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(Val: DestAT)) {
6872 QualType SrcType = Entity.getType();
6873 if (SrcType->isArrayParameterType())
6874 SrcType =
6875 cast<ArrayParameterType>(Val&: SrcType)->getConstantArrayType(Ctx: Context);
6876 if (S.Context.hasSameUnqualifiedType(T1: DestType, T2: SrcType)) {
6877 TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this,
6878 TreatUnavailableAsInvalid);
6879 return;
6880 }
6881 }
6882
6883 // Some kinds of initialization permit an array to be initialized from
6884 // another array of the same type, and perform elementwise initialization.
6885 if (Initializer && isa<ConstantArrayType>(Val: DestAT) &&
6886 S.Context.hasSameUnqualifiedType(T1: Initializer->getType(),
6887 T2: Entity.getType()) &&
6888 canPerformArrayCopy(Entity)) {
6889 TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this,
6890 TreatUnavailableAsInvalid);
6891 return;
6892 }
6893
6894 // Note: as an GNU C extension, we allow initialization of an
6895 // array from a compound literal that creates an array of the same
6896 // type, so long as the initializer has no side effects.
6897 if (!S.getLangOpts().CPlusPlus && Initializer &&
6898 isa<CompoundLiteralExpr>(Val: Initializer->IgnoreParens()) &&
6899 Initializer->getType()->isArrayType()) {
6900 const ArrayType *SourceAT
6901 = Context.getAsArrayType(T: Initializer->getType());
6902 if (!hasCompatibleArrayTypes(Context&: S.Context, Dest: DestAT, Source: SourceAT))
6903 SetFailed(FK_ArrayTypeMismatch);
6904 else if (Initializer->HasSideEffects(Ctx: S.Context))
6905 SetFailed(FK_NonConstantArrayInit);
6906 else {
6907 AddArrayInitStep(T: DestType, /*IsGNUExtension*/true);
6908 }
6909 }
6910 // Note: as a GNU C++ extension, we allow list-initialization of a
6911 // class member of array type from a parenthesized initializer list.
6912 else if (S.getLangOpts().CPlusPlus &&
6913 Entity.getKind() == InitializedEntity::EK_Member &&
6914 isa_and_nonnull<InitListExpr>(Val: Initializer)) {
6915 TryListInitialization(S, Entity, Kind, InitList: cast<InitListExpr>(Val: Initializer),
6916 Sequence&: *this, TreatUnavailableAsInvalid);
6917 AddParenthesizedArrayInitStep(T: DestType);
6918 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6919 Kind.getKind() == InitializationKind::IK_Direct)
6920 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
6921 /*VerifyOnly=*/true);
6922 else if (DestAT->getElementType()->isCharType())
6923 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6924 else if (IsWideCharCompatible(T: DestAT->getElementType(), Context))
6925 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6926 else
6927 SetFailed(FK_ArrayNeedsInitList);
6928
6929 return;
6930 }
6931
6932 // Determine whether we should consider writeback conversions for
6933 // Objective-C ARC.
6934 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6935 Entity.isParameterKind();
6936
6937 if (TryOCLSamplerInitialization(S, Sequence&: *this, DestType, Initializer))
6938 return;
6939
6940 // We're at the end of the line for C: it's either a write-back conversion
6941 // or it's a C assignment. There's no need to check anything else.
6942 if (!S.getLangOpts().CPlusPlus) {
6943 assert(Initializer && "Initializer must be non-null");
6944 // If allowed, check whether this is an Objective-C writeback conversion.
6945 if (allowObjCWritebackConversion &&
6946 tryObjCWritebackConversion(S, Sequence&: *this, Entity, Initializer)) {
6947 return;
6948 }
6949
6950 if (TryOCLZeroOpaqueTypeInitialization(S, Sequence&: *this, DestType, Initializer))
6951 return;
6952
6953 // Handle initialization in C
6954 AddCAssignmentStep(T: DestType);
6955 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
6956 return;
6957 }
6958
6959 assert(S.getLangOpts().CPlusPlus);
6960
6961 // - If the destination type is a (possibly cv-qualified) class type:
6962 // (except for HLSL, where user-defined record types do not have
6963 // constructors or conversion functions)
6964 if (DestType->isRecordType() &&
6965 (!S.getLangOpts().HLSL ||
6966 DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
6967 // - If the initialization is direct-initialization, or if it is
6968 // copy-initialization where the cv-unqualified version of the
6969 // source type is the same class as, or a derived class of, the
6970 // class of the destination, constructors are considered. [...]
6971 if (Kind.getKind() == InitializationKind::IK_Direct ||
6972 (Kind.getKind() == InitializationKind::IK_Copy &&
6973 (Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType) ||
6974 (Initializer && S.IsDerivedFrom(Loc: Initializer->getBeginLoc(),
6975 Derived: SourceType, Base: DestType))))) {
6976 TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType,
6977 Sequence&: *this, /*IsAggrListInit=*/false);
6978 } else {
6979 // - Otherwise (i.e., for the remaining copy-initialization cases),
6980 // user-defined conversion sequences that can convert from the
6981 // source type to the destination type or (when a conversion
6982 // function is used) to a derived class thereof are enumerated as
6983 // described in 13.3.1.4, and the best one is chosen through
6984 // overload resolution (13.3).
6985 assert(Initializer && "Initializer must be non-null");
6986 TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this,
6987 TopLevelOfInitList);
6988 }
6989 return;
6990 }
6991
6992 assert(Args.size() >= 1 && "Zero-argument case handled above");
6993
6994 // For HLSL ext vector types we allow list initialization behavior for C++
6995 // functional cast expressions which look like constructor syntax. This is
6996 // accomplished by converting initialization arguments to InitListExpr.
6997 auto ShouldTryListInitialization = [&]() -> bool {
6998 // Only try list initialization for HLSL.
6999 if (!S.getLangOpts().HLSL)
7000 return false;
7001
7002 bool DestIsVec = DestType->isExtVectorType();
7003 bool DestIsMat = DestType->isConstantMatrixType();
7004
7005 // If the destination type is neither a vector nor a matrix, then don't try
7006 // list initialization.
7007 if (!DestIsVec && !DestIsMat)
7008 return false;
7009
7010 // If there is only a single source argument, then only try list
7011 // initialization if initializing a matrix with a vector or vice versa.
7012 if (Args.size() == 1) {
7013 assert(!SourceType.isNull() &&
7014 "Source QualType should not be null when arg size is exactly 1");
7015 bool SourceIsVec = SourceType->isExtVectorType();
7016 bool SourceIsMat = SourceType->isConstantMatrixType();
7017
7018 if (DestIsMat && !SourceIsVec)
7019 return false;
7020 if (DestIsVec && !SourceIsMat)
7021 return false;
7022 }
7023
7024 // Try list initialization if the source type is null or if the
7025 // destination and source types differ.
7026 return SourceType.isNull() ||
7027 !Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType);
7028 };
7029 if (ShouldTryListInitialization()) {
7030 InitListExpr *ILE = new (Context)
7031 InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args,
7032 Args.back()->getEndLoc(), /*isExplicit=*/false);
7033 ILE->setType(DestType);
7034 Args[0] = ILE;
7035 TryListInitialization(S, Entity, Kind, InitList: ILE, Sequence&: *this,
7036 TreatUnavailableAsInvalid);
7037 return;
7038 }
7039
7040 // The remaining cases all need a source type.
7041 if (Args.size() > 1) {
7042 SetFailed(FK_TooManyInitsForScalar);
7043 return;
7044 } else if (isa<InitListExpr>(Val: Args[0])) {
7045 SetFailed(FK_ParenthesizedListInitForScalar);
7046 return;
7047 }
7048
7049 // - Otherwise, if the source type is a (possibly cv-qualified) class
7050 // type, conversion functions are considered.
7051 // (except for HLSL, where user-defined record types do not have
7052 // constructors or conversion functions).
7053 if (!SourceType.isNull() && SourceType->isRecordType() &&
7054 (!S.getLangOpts().HLSL ||
7055 SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) {
7056 assert(Initializer && "Initializer must be non-null");
7057 // For a conversion to _Atomic(T) from either T or a class type derived
7058 // from T, initialize the T object then convert to _Atomic type.
7059 bool NeedAtomicConversion = false;
7060 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
7061 if (Context.hasSameUnqualifiedType(T1: SourceType, T2: Atomic->getValueType()) ||
7062 S.IsDerivedFrom(Loc: Initializer->getBeginLoc(), Derived: SourceType,
7063 Base: Atomic->getValueType())) {
7064 DestType = Atomic->getValueType();
7065 NeedAtomicConversion = true;
7066 }
7067 }
7068
7069 TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this,
7070 TopLevelOfInitList);
7071 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
7072 if (!Failed() && NeedAtomicConversion)
7073 AddAtomicConversionStep(Ty: Entity.getType());
7074 return;
7075 }
7076
7077 // - Otherwise, if the initialization is direct-initialization, the source
7078 // type is std::nullptr_t, and the destination type is bool, the initial
7079 // value of the object being initialized is false.
7080 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
7081 DestType->isBooleanType() &&
7082 Kind.getKind() == InitializationKind::IK_Direct) {
7083 AddConversionSequenceStep(
7084 ICS: ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
7085 NeedLValToRVal: Initializer->isGLValue()),
7086 T: DestType);
7087 return;
7088 }
7089
7090 // - Otherwise, the initial value of the object being initialized is the
7091 // (possibly converted) value of the initializer expression. Standard
7092 // conversions (Clause 4) will be used, if necessary, to convert the
7093 // initializer expression to the cv-unqualified version of the
7094 // destination type; no user-defined conversions are considered.
7095
7096 ImplicitConversionSequence ICS
7097 = S.TryImplicitConversion(From: Initializer, ToType: DestType,
7098 /*SuppressUserConversions*/true,
7099 AllowExplicit: Sema::AllowedExplicit::None,
7100 /*InOverloadResolution*/ false,
7101 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
7102 AllowObjCWritebackConversion: allowObjCWritebackConversion);
7103
7104 if (ICS.isStandard() &&
7105 ICS.Standard.Second == ICK_Writeback_Conversion) {
7106 // Objective-C ARC writeback conversion.
7107
7108 // We should copy unless we're passing to an argument explicitly
7109 // marked 'out'.
7110 bool ShouldCopy = true;
7111 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl()))
7112 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
7113
7114 // If there was an lvalue adjustment, add it as a separate conversion.
7115 if (ICS.Standard.First == ICK_Array_To_Pointer ||
7116 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7117 ImplicitConversionSequence LvalueICS;
7118 LvalueICS.setStandard();
7119 LvalueICS.Standard.setAsIdentityConversion();
7120 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(Idx: 0));
7121 LvalueICS.Standard.First = ICS.Standard.First;
7122 AddConversionSequenceStep(ICS: LvalueICS, T: ICS.Standard.getToType(Idx: 0));
7123 }
7124
7125 AddPassByIndirectCopyRestoreStep(type: DestType, shouldCopy: ShouldCopy);
7126 } else if (ICS.isBad()) {
7127 if (DeclAccessPair Found;
7128 Initializer->getType() == Context.OverloadTy &&
7129 !S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, TargetType: DestType,
7130 /*Complain=*/false, Found))
7131 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
7132 else if (Initializer->getType()->isFunctionType() &&
7133 isExprAnUnaddressableFunction(S, E: Initializer))
7134 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
7135 else
7136 SetFailed(InitializationSequence::FK_ConversionFailed);
7137 } else {
7138 AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList);
7139
7140 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
7141 }
7142}
7143
7144InitializationSequence::~InitializationSequence() {
7145 for (auto &S : Steps)
7146 S.Destroy();
7147}
7148
7149//===----------------------------------------------------------------------===//
7150// Perform initialization
7151//===----------------------------------------------------------------------===//
7152static AssignmentAction getAssignmentAction(const InitializedEntity &Entity,
7153 bool Diagnose = false) {
7154 switch(Entity.getKind()) {
7155 case InitializedEntity::EK_Variable:
7156 case InitializedEntity::EK_New:
7157 case InitializedEntity::EK_Exception:
7158 case InitializedEntity::EK_Base:
7159 case InitializedEntity::EK_Delegating:
7160 return AssignmentAction::Initializing;
7161
7162 case InitializedEntity::EK_Parameter:
7163 if (Entity.getDecl() &&
7164 isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext()))
7165 return AssignmentAction::Sending;
7166
7167 return AssignmentAction::Passing;
7168
7169 case InitializedEntity::EK_Parameter_CF_Audited:
7170 if (Entity.getDecl() &&
7171 isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext()))
7172 return AssignmentAction::Sending;
7173
7174 return !Diagnose ? AssignmentAction::Passing
7175 : AssignmentAction::Passing_CFAudited;
7176
7177 case InitializedEntity::EK_Result:
7178 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
7179 return AssignmentAction::Returning;
7180
7181 case InitializedEntity::EK_Temporary:
7182 case InitializedEntity::EK_RelatedResult:
7183 // FIXME: Can we tell apart casting vs. converting?
7184 return AssignmentAction::Casting;
7185
7186 case InitializedEntity::EK_TemplateParameter:
7187 // This is really initialization, but refer to it as conversion for
7188 // consistency with CheckConvertedConstantExpression.
7189 return AssignmentAction::Converting;
7190
7191 case InitializedEntity::EK_Member:
7192 case InitializedEntity::EK_ParenAggInitMember:
7193 case InitializedEntity::EK_Binding:
7194 case InitializedEntity::EK_ArrayElement:
7195 case InitializedEntity::EK_VectorElement:
7196 case InitializedEntity::EK_MatrixElement:
7197 case InitializedEntity::EK_ComplexElement:
7198 case InitializedEntity::EK_BlockElement:
7199 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7200 case InitializedEntity::EK_LambdaCapture:
7201 case InitializedEntity::EK_CompoundLiteralInit:
7202 return AssignmentAction::Initializing;
7203 }
7204
7205 llvm_unreachable("Invalid EntityKind!");
7206}
7207
7208/// Whether we should bind a created object as a temporary when
7209/// initializing the given entity.
7210static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
7211 switch (Entity.getKind()) {
7212 case InitializedEntity::EK_ArrayElement:
7213 case InitializedEntity::EK_Member:
7214 case InitializedEntity::EK_ParenAggInitMember:
7215 case InitializedEntity::EK_Result:
7216 case InitializedEntity::EK_StmtExprResult:
7217 case InitializedEntity::EK_New:
7218 case InitializedEntity::EK_Variable:
7219 case InitializedEntity::EK_Base:
7220 case InitializedEntity::EK_Delegating:
7221 case InitializedEntity::EK_VectorElement:
7222 case InitializedEntity::EK_MatrixElement:
7223 case InitializedEntity::EK_ComplexElement:
7224 case InitializedEntity::EK_Exception:
7225 case InitializedEntity::EK_BlockElement:
7226 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7227 case InitializedEntity::EK_LambdaCapture:
7228 case InitializedEntity::EK_CompoundLiteralInit:
7229 case InitializedEntity::EK_TemplateParameter:
7230 return false;
7231
7232 case InitializedEntity::EK_Parameter:
7233 case InitializedEntity::EK_Parameter_CF_Audited:
7234 case InitializedEntity::EK_Temporary:
7235 case InitializedEntity::EK_RelatedResult:
7236 case InitializedEntity::EK_Binding:
7237 return true;
7238 }
7239
7240 llvm_unreachable("missed an InitializedEntity kind?");
7241}
7242
7243/// Whether the given entity, when initialized with an object
7244/// created for that initialization, requires destruction.
7245static bool shouldDestroyEntity(const InitializedEntity &Entity) {
7246 switch (Entity.getKind()) {
7247 case InitializedEntity::EK_Result:
7248 case InitializedEntity::EK_StmtExprResult:
7249 case InitializedEntity::EK_New:
7250 case InitializedEntity::EK_Base:
7251 case InitializedEntity::EK_Delegating:
7252 case InitializedEntity::EK_VectorElement:
7253 case InitializedEntity::EK_MatrixElement:
7254 case InitializedEntity::EK_ComplexElement:
7255 case InitializedEntity::EK_BlockElement:
7256 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7257 case InitializedEntity::EK_LambdaCapture:
7258 return false;
7259
7260 case InitializedEntity::EK_Member:
7261 case InitializedEntity::EK_ParenAggInitMember:
7262 case InitializedEntity::EK_Binding:
7263 case InitializedEntity::EK_Variable:
7264 case InitializedEntity::EK_Parameter:
7265 case InitializedEntity::EK_Parameter_CF_Audited:
7266 case InitializedEntity::EK_TemplateParameter:
7267 case InitializedEntity::EK_Temporary:
7268 case InitializedEntity::EK_ArrayElement:
7269 case InitializedEntity::EK_Exception:
7270 case InitializedEntity::EK_CompoundLiteralInit:
7271 case InitializedEntity::EK_RelatedResult:
7272 return true;
7273 }
7274
7275 llvm_unreachable("missed an InitializedEntity kind?");
7276}
7277
7278/// Get the location at which initialization diagnostics should appear.
7279static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
7280 Expr *Initializer) {
7281 switch (Entity.getKind()) {
7282 case InitializedEntity::EK_Result:
7283 case InitializedEntity::EK_StmtExprResult:
7284 return Entity.getReturnLoc();
7285
7286 case InitializedEntity::EK_Exception:
7287 return Entity.getThrowLoc();
7288
7289 case InitializedEntity::EK_Variable:
7290 case InitializedEntity::EK_Binding:
7291 return Entity.getDecl()->getLocation();
7292
7293 case InitializedEntity::EK_LambdaCapture:
7294 return Entity.getCaptureLoc();
7295
7296 case InitializedEntity::EK_ArrayElement:
7297 case InitializedEntity::EK_Member:
7298 case InitializedEntity::EK_ParenAggInitMember:
7299 case InitializedEntity::EK_Parameter:
7300 case InitializedEntity::EK_Parameter_CF_Audited:
7301 case InitializedEntity::EK_TemplateParameter:
7302 case InitializedEntity::EK_Temporary:
7303 case InitializedEntity::EK_New:
7304 case InitializedEntity::EK_Base:
7305 case InitializedEntity::EK_Delegating:
7306 case InitializedEntity::EK_VectorElement:
7307 case InitializedEntity::EK_MatrixElement:
7308 case InitializedEntity::EK_ComplexElement:
7309 case InitializedEntity::EK_BlockElement:
7310 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7311 case InitializedEntity::EK_CompoundLiteralInit:
7312 case InitializedEntity::EK_RelatedResult:
7313 return Initializer->getBeginLoc();
7314 }
7315 llvm_unreachable("missed an InitializedEntity kind?");
7316}
7317
7318/// Make a (potentially elidable) temporary copy of the object
7319/// provided by the given initializer by calling the appropriate copy
7320/// constructor.
7321///
7322/// \param S The Sema object used for type-checking.
7323///
7324/// \param T The type of the temporary object, which must either be
7325/// the type of the initializer expression or a superclass thereof.
7326///
7327/// \param Entity The entity being initialized.
7328///
7329/// \param CurInit The initializer expression.
7330///
7331/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
7332/// is permitted in C++03 (but not C++0x) when binding a reference to
7333/// an rvalue.
7334///
7335/// \returns An expression that copies the initializer expression into
7336/// a temporary object, or an error expression if a copy could not be
7337/// created.
7338static ExprResult CopyObject(Sema &S,
7339 QualType T,
7340 const InitializedEntity &Entity,
7341 ExprResult CurInit,
7342 bool IsExtraneousCopy) {
7343 if (CurInit.isInvalid())
7344 return CurInit;
7345 // Determine which class type we're copying to.
7346 Expr *CurInitExpr = (Expr *)CurInit.get();
7347 auto *Class = T->getAsCXXRecordDecl();
7348 if (!Class)
7349 return CurInit;
7350
7351 SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInit.get());
7352
7353 // Make sure that the type we are copying is complete.
7354 if (S.RequireCompleteType(Loc, T, DiagID: diag::err_temp_copy_incomplete))
7355 return CurInit;
7356
7357 // Perform overload resolution using the class's constructors. Per
7358 // C++11 [dcl.init]p16, second bullet for class types, this initialization
7359 // is direct-initialization.
7360 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7361 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
7362
7363 OverloadCandidateSet::iterator Best;
7364 switch (ResolveConstructorOverload(
7365 S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: T, Ctors, Best,
7366 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7367 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7368 /*RequireActualConstructor=*/false,
7369 /*SecondStepOfCopyInit=*/true)) {
7370 case OR_Success:
7371 break;
7372
7373 case OR_No_Viable_Function:
7374 CandidateSet.NoteCandidates(
7375 PA: PartialDiagnosticAt(
7376 Loc, S.PDiag(DiagID: IsExtraneousCopy && !S.isSFINAEContext()
7377 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
7378 : diag::err_temp_copy_no_viable)
7379 << (int)Entity.getKind() << CurInitExpr->getType()
7380 << CurInitExpr->getSourceRange()),
7381 S, OCD: OCD_AllCandidates, Args: CurInitExpr);
7382 if (!IsExtraneousCopy || S.isSFINAEContext())
7383 return ExprError();
7384 return CurInit;
7385
7386 case OR_Ambiguous:
7387 CandidateSet.NoteCandidates(
7388 PA: PartialDiagnosticAt(Loc, S.PDiag(DiagID: diag::err_temp_copy_ambiguous)
7389 << (int)Entity.getKind()
7390 << CurInitExpr->getType()
7391 << CurInitExpr->getSourceRange()),
7392 S, OCD: OCD_AmbiguousCandidates, Args: CurInitExpr);
7393 return ExprError();
7394
7395 case OR_Deleted:
7396 S.Diag(Loc, DiagID: diag::err_temp_copy_deleted)
7397 << (int)Entity.getKind() << CurInitExpr->getType()
7398 << CurInitExpr->getSourceRange();
7399 S.NoteDeletedFunction(FD: Best->Function);
7400 return ExprError();
7401 }
7402
7403 bool HadMultipleCandidates = CandidateSet.size() > 1;
7404
7405 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
7406 SmallVector<Expr*, 8> ConstructorArgs;
7407 CurInit.get(); // Ownership transferred into MultiExprArg, below.
7408
7409 S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Best->FoundDecl, Entity,
7410 IsCopyBindingRefToTemp: IsExtraneousCopy);
7411
7412 if (IsExtraneousCopy) {
7413 // If this is a totally extraneous copy for C++03 reference
7414 // binding purposes, just return the original initialization
7415 // expression. We don't generate an (elided) copy operation here
7416 // because doing so would require us to pass down a flag to avoid
7417 // infinite recursion, where each step adds another extraneous,
7418 // elidable copy.
7419
7420 // Instantiate the default arguments of any extra parameters in
7421 // the selected copy constructor, as if we were going to create a
7422 // proper call to the copy constructor.
7423 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
7424 ParmVarDecl *Parm = Constructor->getParamDecl(i: I);
7425 if (S.RequireCompleteType(Loc, T: Parm->getType(),
7426 DiagID: diag::err_call_incomplete_argument))
7427 break;
7428
7429 // Build the default argument expression; we don't actually care
7430 // if this succeeds or not, because this routine will complain
7431 // if there was a problem.
7432 S.BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Constructor, Param: Parm);
7433 }
7434
7435 return CurInitExpr;
7436 }
7437
7438 // Determine the arguments required to actually perform the
7439 // constructor call (we might have derived-to-base conversions, or
7440 // the copy constructor may have default arguments).
7441 if (S.CompleteConstructorCall(Constructor, DeclInitType: T, ArgsPtr: CurInitExpr, Loc,
7442 ConvertedArgs&: ConstructorArgs))
7443 return ExprError();
7444
7445 // C++0x [class.copy]p32:
7446 // When certain criteria are met, an implementation is allowed to
7447 // omit the copy/move construction of a class object, even if the
7448 // copy/move constructor and/or destructor for the object have
7449 // side effects. [...]
7450 // - when a temporary class object that has not been bound to a
7451 // reference (12.2) would be copied/moved to a class object
7452 // with the same cv-unqualified type, the copy/move operation
7453 // can be omitted by constructing the temporary object
7454 // directly into the target of the omitted copy/move
7455 //
7456 // Note that the other three bullets are handled elsewhere. Copy
7457 // elision for return statements and throw expressions are handled as part
7458 // of constructor initialization, while copy elision for exception handlers
7459 // is handled by the run-time.
7460 //
7461 // FIXME: If the function parameter is not the same type as the temporary, we
7462 // should still be able to elide the copy, but we don't have a way to
7463 // represent in the AST how much should be elided in this case.
7464 bool Elidable =
7465 CurInitExpr->isTemporaryObject(Ctx&: S.Context, TempTy: Class) &&
7466 S.Context.hasSameUnqualifiedType(
7467 T1: Best->Function->getParamDecl(i: 0)->getType().getNonReferenceType(),
7468 T2: CurInitExpr->getType());
7469
7470 // Actually perform the constructor call.
7471 CurInit = S.BuildCXXConstructExpr(
7472 ConstructLoc: Loc, DeclInitType: T, FoundDecl: Best->FoundDecl, Constructor, Elidable, Exprs: ConstructorArgs,
7473 HadMultipleCandidates,
7474 /*ListInit*/ IsListInitialization: false,
7475 /*StdInitListInit*/ IsStdInitListInitialization: false,
7476 /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
7477
7478 // If we're supposed to bind temporaries, do so.
7479 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
7480 CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>());
7481 return CurInit;
7482}
7483
7484/// Check whether elidable copy construction for binding a reference to
7485/// a temporary would have succeeded if we were building in C++98 mode, for
7486/// -Wc++98-compat.
7487static void CheckCXX98CompatAccessibleCopy(Sema &S,
7488 const InitializedEntity &Entity,
7489 Expr *CurInitExpr) {
7490 assert(S.getLangOpts().CPlusPlus11);
7491
7492 auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl();
7493 if (!Record)
7494 return;
7495
7496 SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInitExpr);
7497 if (S.Diags.isIgnored(DiagID: diag::warn_cxx98_compat_temp_copy, Loc))
7498 return;
7499
7500 // Find constructors which would have been considered.
7501 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7502 DeclContext::lookup_result Ctors = S.LookupConstructors(Class: Record);
7503
7504 // Perform overload resolution.
7505 OverloadCandidateSet::iterator Best;
7506 OverloadingResult OR = ResolveConstructorOverload(
7507 S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: CurInitExpr->getType(), Ctors, Best,
7508 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
7509 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
7510 /*RequireActualConstructor=*/false,
7511 /*SecondStepOfCopyInit=*/true);
7512
7513 PartialDiagnostic Diag = S.PDiag(DiagID: diag::warn_cxx98_compat_temp_copy)
7514 << OR << (int)Entity.getKind() << CurInitExpr->getType()
7515 << CurInitExpr->getSourceRange();
7516
7517 switch (OR) {
7518 case OR_Success:
7519 S.CheckConstructorAccess(Loc, D: cast<CXXConstructorDecl>(Val: Best->Function),
7520 FoundDecl: Best->FoundDecl, Entity, PDiag: Diag);
7521 // FIXME: Check default arguments as far as that's possible.
7522 break;
7523
7524 case OR_No_Viable_Function:
7525 CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S,
7526 OCD: OCD_AllCandidates, Args: CurInitExpr);
7527 break;
7528
7529 case OR_Ambiguous:
7530 CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S,
7531 OCD: OCD_AmbiguousCandidates, Args: CurInitExpr);
7532 break;
7533
7534 case OR_Deleted:
7535 S.Diag(Loc, PD: Diag);
7536 S.NoteDeletedFunction(FD: Best->Function);
7537 break;
7538 }
7539}
7540
7541void InitializationSequence::PrintInitLocationNote(Sema &S,
7542 const InitializedEntity &Entity) {
7543 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
7544 if (Entity.getDecl()->getLocation().isInvalid())
7545 return;
7546
7547 if (Entity.getDecl()->getDeclName())
7548 S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_named_here)
7549 << Entity.getDecl()->getDeclName();
7550 else
7551 S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_here);
7552 }
7553 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7554 Entity.getMethodDecl())
7555 S.Diag(Loc: Entity.getMethodDecl()->getLocation(),
7556 DiagID: diag::note_method_return_type_change)
7557 << Entity.getMethodDecl()->getDeclName();
7558}
7559
7560/// Returns true if the parameters describe a constructor initialization of
7561/// an explicit temporary object, e.g. "Point(x, y)".
7562static bool isExplicitTemporary(const InitializedEntity &Entity,
7563 const InitializationKind &Kind,
7564 unsigned NumArgs) {
7565 switch (Entity.getKind()) {
7566 case InitializedEntity::EK_Temporary:
7567 case InitializedEntity::EK_CompoundLiteralInit:
7568 case InitializedEntity::EK_RelatedResult:
7569 break;
7570 default:
7571 return false;
7572 }
7573
7574 switch (Kind.getKind()) {
7575 case InitializationKind::IK_DirectList:
7576 return true;
7577 // FIXME: Hack to work around cast weirdness.
7578 case InitializationKind::IK_Direct:
7579 case InitializationKind::IK_Value:
7580 return NumArgs != 1;
7581 default:
7582 return false;
7583 }
7584}
7585
7586static ExprResult
7587PerformConstructorInitialization(Sema &S,
7588 const InitializedEntity &Entity,
7589 const InitializationKind &Kind,
7590 MultiExprArg Args,
7591 const InitializationSequence::Step& Step,
7592 bool &ConstructorInitRequiresZeroInit,
7593 bool IsListInitialization,
7594 bool IsStdInitListInitialization,
7595 SourceLocation LBraceLoc,
7596 SourceLocation RBraceLoc) {
7597 unsigned NumArgs = Args.size();
7598 CXXConstructorDecl *Constructor
7599 = cast<CXXConstructorDecl>(Val: Step.Function.Function);
7600 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7601
7602 // Build a call to the selected constructor.
7603 SmallVector<Expr*, 8> ConstructorArgs;
7604 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7605 ? Kind.getEqualLoc()
7606 : Kind.getLocation();
7607
7608 if (Kind.getKind() == InitializationKind::IK_Default) {
7609 // Force even a trivial, implicit default constructor to be
7610 // semantically checked. We do this explicitly because we don't build
7611 // the definition for completely trivial constructors.
7612 assert(Constructor->getParent() && "No parent class for constructor.");
7613 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7614 Constructor->isTrivial() && !Constructor->isUsed(CheckUsedAttr: false)) {
7615 S.runWithSufficientStackSpace(Loc, Fn: [&] {
7616 S.DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
7617 });
7618 }
7619 }
7620
7621 ExprResult CurInit((Expr *)nullptr);
7622
7623 // C++ [over.match.copy]p1:
7624 // - When initializing a temporary to be bound to the first parameter
7625 // of a constructor that takes a reference to possibly cv-qualified
7626 // T as its first argument, called with a single argument in the
7627 // context of direct-initialization, explicit conversion functions
7628 // are also considered.
7629 bool AllowExplicitConv =
7630 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7631 hasCopyOrMoveCtorParam(Ctx&: S.Context,
7632 Info: getConstructorInfo(ND: Step.Function.FoundDecl));
7633
7634 // A smart pointer constructed from a nullable pointer is nullable.
7635 if (NumArgs == 1 && !Kind.isExplicitCast())
7636 S.diagnoseNullableToNonnullConversion(
7637 DstType: Entity.getType(), SrcType: Args.front()->getType(), Loc: Kind.getLocation());
7638
7639 // Determine the arguments required to actually perform the constructor
7640 // call.
7641 if (S.CompleteConstructorCall(Constructor, DeclInitType: Step.Type, ArgsPtr: Args, Loc,
7642 ConvertedArgs&: ConstructorArgs, AllowExplicit: AllowExplicitConv,
7643 IsListInitialization))
7644 return ExprError();
7645
7646 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7647 // An explicitly-constructed temporary, e.g., X(1, 2).
7648 if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc))
7649 return ExprError();
7650
7651 if (Kind.getKind() == InitializationKind::IK_Value &&
7652 Constructor->isImplicit()) {
7653 auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl();
7654 if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) {
7655 unsigned I = 0;
7656 for (const FieldDecl *FD : RD->fields()) {
7657 if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() &&
7658 !S.isUnevaluatedContext()) {
7659 S.Diag(Loc, DiagID: diag::warn_field_requires_explicit_init)
7660 << /* Var-in-Record */ 0 << FD;
7661 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD;
7662 }
7663 ++I;
7664 }
7665 }
7666 }
7667
7668 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7669 if (!TSInfo)
7670 TSInfo = S.Context.getTrivialTypeSourceInfo(T: Entity.getType(), Loc);
7671 SourceRange ParenOrBraceRange =
7672 (Kind.getKind() == InitializationKind::IK_DirectList)
7673 ? SourceRange(LBraceLoc, RBraceLoc)
7674 : Kind.getParenOrBraceRange();
7675
7676 CXXConstructorDecl *CalleeDecl = Constructor;
7677 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7678 Val: Step.Function.FoundDecl.getDecl())) {
7679 CalleeDecl = S.findInheritingConstructor(Loc, BaseCtor: Constructor, DerivedShadow: Shadow);
7680 }
7681 S.MarkFunctionReferenced(Loc, Func: CalleeDecl);
7682
7683 CurInit = S.CheckForImmediateInvocation(
7684 E: CXXTemporaryObjectExpr::Create(
7685 Ctx: S.Context, Cons: CalleeDecl,
7686 Ty: Entity.getType().getNonLValueExprType(Context: S.Context), TSI: TSInfo,
7687 Args: ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7688 ListInitialization: IsListInitialization, StdInitListInitialization: IsStdInitListInitialization,
7689 ZeroInitialization: ConstructorInitRequiresZeroInit),
7690 Decl: CalleeDecl);
7691 } else {
7692 CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;
7693
7694 if (Entity.getKind() == InitializedEntity::EK_Base) {
7695 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7696 ? CXXConstructionKind::VirtualBase
7697 : CXXConstructionKind::NonVirtualBase;
7698 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7699 ConstructKind = CXXConstructionKind::Delegating;
7700 }
7701
7702 // Only get the parenthesis or brace range if it is a list initialization or
7703 // direct construction.
7704 SourceRange ParenOrBraceRange;
7705 if (IsListInitialization)
7706 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7707 else if (Kind.getKind() == InitializationKind::IK_Direct)
7708 ParenOrBraceRange = Kind.getParenOrBraceRange();
7709
7710 // If the entity allows NRVO, mark the construction as elidable
7711 // unconditionally.
7712 if (Entity.allowsNRVO())
7713 CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type,
7714 FoundDecl: Step.Function.FoundDecl,
7715 Constructor, /*Elidable=*/true,
7716 Exprs: ConstructorArgs,
7717 HadMultipleCandidates,
7718 IsListInitialization,
7719 IsStdInitListInitialization,
7720 RequiresZeroInit: ConstructorInitRequiresZeroInit,
7721 ConstructKind,
7722 ParenRange: ParenOrBraceRange);
7723 else
7724 CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type,
7725 FoundDecl: Step.Function.FoundDecl,
7726 Constructor,
7727 Exprs: ConstructorArgs,
7728 HadMultipleCandidates,
7729 IsListInitialization,
7730 IsStdInitListInitialization,
7731 RequiresZeroInit: ConstructorInitRequiresZeroInit,
7732 ConstructKind,
7733 ParenRange: ParenOrBraceRange);
7734 }
7735 if (CurInit.isInvalid())
7736 return ExprError();
7737
7738 // Only check access if all of that succeeded.
7739 S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Step.Function.FoundDecl, Entity);
7740 if (S.DiagnoseUseOfOverloadedDecl(D: Constructor, Loc))
7741 return ExprError();
7742
7743 if (const ArrayType *AT = S.Context.getAsArrayType(T: Entity.getType()))
7744 if (checkDestructorReference(ElementType: S.Context.getBaseElementType(VAT: AT), Loc, SemaRef&: S))
7745 return ExprError();
7746
7747 if (shouldBindAsTemporary(Entity))
7748 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
7749
7750 return CurInit;
7751}
7752
7753void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
7754 Expr *Init) {
7755 return sema::checkInitLifetime(SemaRef&: *this, Entity, Init);
7756}
7757
7758static void DiagnoseNarrowingInInitList(Sema &S,
7759 const ImplicitConversionSequence &ICS,
7760 QualType PreNarrowingType,
7761 QualType EntityType,
7762 const Expr *PostInit);
7763
7764static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
7765 QualType ToType, Expr *Init);
7766
7767/// Provide warnings when std::move is used on construction.
7768static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
7769 bool IsReturnStmt) {
7770 if (!InitExpr)
7771 return;
7772
7773 if (S.inTemplateInstantiation())
7774 return;
7775
7776 QualType DestType = InitExpr->getType();
7777 if (!DestType->isRecordType())
7778 return;
7779
7780 unsigned DiagID = 0;
7781 if (IsReturnStmt) {
7782 const CXXConstructExpr *CCE =
7783 dyn_cast<CXXConstructExpr>(Val: InitExpr->IgnoreParens());
7784 if (!CCE || CCE->getNumArgs() != 1)
7785 return;
7786
7787 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
7788 return;
7789
7790 InitExpr = CCE->getArg(Arg: 0)->IgnoreImpCasts();
7791 }
7792
7793 // Find the std::move call and get the argument.
7794 const CallExpr *CE = dyn_cast<CallExpr>(Val: InitExpr->IgnoreParens());
7795 if (!CE || !CE->isCallToStdMove())
7796 return;
7797
7798 const Expr *Arg = CE->getArg(Arg: 0)->IgnoreImplicit();
7799
7800 if (IsReturnStmt) {
7801 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts());
7802 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
7803 return;
7804
7805 const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
7806 if (!VD || !VD->hasLocalStorage())
7807 return;
7808
7809 // __block variables are not moved implicitly.
7810 if (VD->hasAttr<BlocksAttr>())
7811 return;
7812
7813 QualType SourceType = VD->getType();
7814 if (!SourceType->isRecordType())
7815 return;
7816
7817 if (!S.Context.hasSameUnqualifiedType(T1: DestType, T2: SourceType)) {
7818 return;
7819 }
7820
7821 // If we're returning a function parameter, copy elision
7822 // is not possible.
7823 if (isa<ParmVarDecl>(Val: VD))
7824 DiagID = diag::warn_redundant_move_on_return;
7825 else
7826 DiagID = diag::warn_pessimizing_move_on_return;
7827 } else {
7828 DiagID = diag::warn_pessimizing_move_on_initialization;
7829 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
7830 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
7831 return;
7832 }
7833
7834 S.Diag(Loc: CE->getBeginLoc(), DiagID);
7835
7836 // Get all the locations for a fix-it. Don't emit the fix-it if any location
7837 // is within a macro.
7838 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
7839 if (CallBegin.isMacroID())
7840 return;
7841 SourceLocation RParen = CE->getRParenLoc();
7842 if (RParen.isMacroID())
7843 return;
7844 SourceLocation LParen;
7845 SourceLocation ArgLoc = Arg->getBeginLoc();
7846
7847 // Special testing for the argument location. Since the fix-it needs the
7848 // location right before the argument, the argument location can be in a
7849 // macro only if it is at the beginning of the macro.
7850 while (ArgLoc.isMacroID() &&
7851 S.getSourceManager().isAtStartOfImmediateMacroExpansion(Loc: ArgLoc)) {
7852 ArgLoc = S.getSourceManager().getImmediateExpansionRange(Loc: ArgLoc).getBegin();
7853 }
7854
7855 if (LParen.isMacroID())
7856 return;
7857
7858 LParen = ArgLoc.getLocWithOffset(Offset: -1);
7859
7860 S.Diag(Loc: CE->getBeginLoc(), DiagID: diag::note_remove_move)
7861 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CallBegin, LParen))
7862 << FixItHint::CreateRemoval(RemoveRange: SourceRange(RParen, RParen));
7863}
7864
7865static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
7866 // Check to see if we are dereferencing a null pointer. If so, this is
7867 // undefined behavior, so warn about it. This only handles the pattern
7868 // "*null", which is a very syntactic check.
7869 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts()))
7870 if (UO->getOpcode() == UO_Deref &&
7871 UO->getSubExpr()->IgnoreParenCasts()->
7872 isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
7873 S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO,
7874 PD: S.PDiag(DiagID: diag::warn_binding_null_to_reference)
7875 << UO->getSubExpr()->getSourceRange());
7876 }
7877}
7878
7879MaterializeTemporaryExpr *
7880Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
7881 bool BoundToLvalueReference) {
7882 auto MTE = new (Context)
7883 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
7884
7885 // Order an ExprWithCleanups for lifetime marks.
7886 //
7887 // TODO: It'll be good to have a single place to check the access of the
7888 // destructor and generate ExprWithCleanups for various uses. Currently these
7889 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
7890 // but there may be a chance to merge them.
7891 Cleanup.setExprNeedsCleanups(false);
7892 if (isInLifetimeExtendingContext())
7893 currentEvaluationContext().ForRangeLifetimeExtendTemps.push_back(Elt: MTE);
7894 return MTE;
7895}
7896
7897ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
7898 // In C++98, we don't want to implicitly create an xvalue. C11 added the
7899 // same rule, but C99 is broken without this behavior and so we treat the
7900 // change as applying to all C language modes.
7901 // FIXME: This means that AST consumers need to deal with "prvalues" that
7902 // denote materialized temporaries. Maybe we should add another ValueKind
7903 // for "xvalue pretending to be a prvalue" for C++98 support.
7904 if (!E->isPRValue() ||
7905 (!getLangOpts().CPlusPlus11 && getLangOpts().CPlusPlus))
7906 return E;
7907
7908 // C++1z [conv.rval]/1: T shall be a complete type.
7909 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
7910 // If so, we should check for a non-abstract class type here too.
7911 QualType T = E->getType();
7912 if (RequireCompleteType(Loc: E->getExprLoc(), T, DiagID: diag::err_incomplete_type))
7913 return ExprError();
7914
7915 return CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: false);
7916}
7917
7918ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
7919 ExprValueKind VK,
7920 CheckedConversionKind CCK) {
7921
7922 CastKind CK = CK_NoOp;
7923
7924 if (VK == VK_PRValue) {
7925 auto PointeeTy = Ty->getPointeeType();
7926 auto ExprPointeeTy = E->getType()->getPointeeType();
7927 if (!PointeeTy.isNull() &&
7928 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
7929 CK = CK_AddressSpaceConversion;
7930 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
7931 CK = CK_AddressSpaceConversion;
7932 }
7933
7934 return ImpCastExprToType(E, Type: Ty, CK, VK, /*BasePath=*/nullptr, CCK);
7935}
7936
7937ExprResult InitializationSequence::Perform(Sema &S,
7938 const InitializedEntity &Entity,
7939 const InitializationKind &Kind,
7940 MultiExprArg Args,
7941 QualType *ResultType) {
7942 if (Failed()) {
7943 Diagnose(S, Entity, Kind, Args);
7944 return ExprError();
7945 }
7946 if (!ZeroInitializationFixit.empty()) {
7947 const Decl *D = Entity.getDecl();
7948 const auto *VD = dyn_cast_or_null<VarDecl>(Val: D);
7949 QualType DestType = Entity.getType();
7950
7951 // The initialization would have succeeded with this fixit. Since the fixit
7952 // is on the error, we need to build a valid AST in this case, so this isn't
7953 // handled in the Failed() branch above.
7954 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
7955 // Use a more useful diagnostic for constexpr variables.
7956 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
7957 << VD
7958 << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc,
7959 Code: ZeroInitializationFixit);
7960 } else {
7961 unsigned DiagID = diag::err_default_init_const;
7962 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
7963 DiagID = diag::ext_default_init_const;
7964
7965 S.Diag(Loc: Kind.getLocation(), DiagID)
7966 << DestType << DestType->isRecordType()
7967 << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc,
7968 Code: ZeroInitializationFixit);
7969 }
7970 }
7971
7972 if (getKind() == DependentSequence) {
7973 // If the declaration is a non-dependent, incomplete array type
7974 // that has an initializer, then its type will be completed once
7975 // the initializer is instantiated.
7976 if (ResultType && !Entity.getType()->isDependentType() &&
7977 Args.size() == 1) {
7978 QualType DeclType = Entity.getType();
7979 if (const IncompleteArrayType *ArrayT
7980 = S.Context.getAsIncompleteArrayType(T: DeclType)) {
7981 // FIXME: We don't currently have the ability to accurately
7982 // compute the length of an initializer list without
7983 // performing full type-checking of the initializer list
7984 // (since we have to determine where braces are implicitly
7985 // introduced and such). So, we fall back to making the array
7986 // type a dependently-sized array type with no specified
7987 // bound.
7988 if (isa<InitListExpr>(Val: (Expr *)Args[0]))
7989 *ResultType = S.Context.getDependentSizedArrayType(
7990 EltTy: ArrayT->getElementType(),
7991 /*NumElts=*/nullptr, ASM: ArrayT->getSizeModifier(),
7992 IndexTypeQuals: ArrayT->getIndexTypeCVRQualifiers());
7993 }
7994 }
7995 if (Kind.getKind() == InitializationKind::IK_Direct &&
7996 !Kind.isExplicitCast()) {
7997 // Rebuild the ParenListExpr.
7998 SourceRange ParenRange = Kind.getParenOrBraceRange();
7999 return S.ActOnParenListExpr(L: ParenRange.getBegin(), R: ParenRange.getEnd(),
8000 Val: Args);
8001 }
8002 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8003 Kind.isExplicitCast() ||
8004 Kind.getKind() == InitializationKind::IK_DirectList);
8005 return ExprResult(Args[0]);
8006 }
8007
8008 // No steps means no initialization.
8009 if (Steps.empty())
8010 return ExprResult((Expr *)nullptr);
8011
8012 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8013 Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) &&
8014 !Entity.isParamOrTemplateParamKind()) {
8015 // Produce a C++98 compatibility warning if we are initializing a reference
8016 // from an initializer list. For parameters, we produce a better warning
8017 // elsewhere.
8018 Expr *Init = Args[0];
8019 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::warn_cxx98_compat_reference_list_init)
8020 << Init->getSourceRange();
8021 }
8022
8023 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8024 isa<PredefinedExpr>(Val: Args[0]) && Entity.getType()->isArrayType()) {
8025 // Produce a Microsoft compatibility warning when initializing from a
8026 // predefined expression since MSVC treats predefined expressions as string
8027 // literals.
8028 Expr *Init = Args[0];
8029 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::ext_init_from_predefined) << Init;
8030 }
8031
8032 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8033 QualType ETy = Entity.getType();
8034 bool HasGlobalAS = ETy.hasAddressSpace() &&
8035 ETy.getAddressSpace() == LangAS::opencl_global;
8036
8037 if (S.getLangOpts().OpenCLVersion >= 200 &&
8038 ETy->isAtomicType() && !HasGlobalAS &&
8039 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8040 S.Diag(Loc: Args[0]->getBeginLoc(), DiagID: diag::err_opencl_atomic_init)
8041 << 1
8042 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8043 return ExprError();
8044 }
8045
8046 QualType DestType = Entity.getType().getNonReferenceType();
8047 // FIXME: Ugly hack around the fact that Entity.getType() is not
8048 // the same as Entity.getDecl()->getType() in cases involving type merging,
8049 // and we want latter when it makes sense.
8050 if (ResultType)
8051 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8052 Entity.getType();
8053
8054 ExprResult CurInit((Expr *)nullptr);
8055 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8056
8057 // HLSL allows vector/matrix initialization to function like list
8058 // initialization, but use the syntax of a C++-like constructor.
8059 bool IsHLSLVectorOrMatrixInit =
8060 S.getLangOpts().HLSL &&
8061 (DestType->isExtVectorType() || DestType->isConstantMatrixType()) &&
8062 isa<InitListExpr>(Val: Args[0]);
8063 (void)IsHLSLVectorOrMatrixInit;
8064
8065 // For initialization steps that start with a single initializer,
8066 // grab the only argument out the Args and place it into the "current"
8067 // initializer.
8068 switch (Steps.front().Kind) {
8069 case SK_ResolveAddressOfOverloadedFunction:
8070 case SK_CastDerivedToBasePRValue:
8071 case SK_CastDerivedToBaseXValue:
8072 case SK_CastDerivedToBaseLValue:
8073 case SK_BindReference:
8074 case SK_BindReferenceToTemporary:
8075 case SK_FinalCopy:
8076 case SK_ExtraneousCopyToTemporary:
8077 case SK_UserConversion:
8078 case SK_QualificationConversionLValue:
8079 case SK_QualificationConversionXValue:
8080 case SK_QualificationConversionPRValue:
8081 case SK_FunctionReferenceConversion:
8082 case SK_AtomicConversion:
8083 case SK_ConversionSequence:
8084 case SK_ConversionSequenceNoNarrowing:
8085 case SK_ListInitialization:
8086 case SK_UnwrapInitList:
8087 case SK_RewrapInitList:
8088 case SK_CAssignment:
8089 case SK_StringInit:
8090 case SK_ObjCObjectConversion:
8091 case SK_ArrayLoopIndex:
8092 case SK_ArrayLoopInit:
8093 case SK_ArrayInit:
8094 case SK_GNUArrayInit:
8095 case SK_ParenthesizedArrayInit:
8096 case SK_PassByIndirectCopyRestore:
8097 case SK_PassByIndirectRestore:
8098 case SK_ProduceObjCObject:
8099 case SK_StdInitializerList:
8100 case SK_OCLSamplerInit:
8101 case SK_OCLZeroOpaqueType:
8102 case SK_HLSLBufferConversion: {
8103 assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit);
8104 CurInit = Args[0];
8105 if (!CurInit.get()) return ExprError();
8106 break;
8107 }
8108
8109 case SK_ConstructorInitialization:
8110 case SK_ConstructorInitializationFromList:
8111 case SK_StdInitializerListConstructorCall:
8112 case SK_ZeroInitialization:
8113 case SK_ParenthesizedListInit:
8114 break;
8115 }
8116
8117 // Promote from an unevaluated context to an unevaluated list context in
8118 // C++11 list-initialization; we need to instantiate entities usable in
8119 // constant expressions here in order to perform narrowing checks =(
8120 EnterExpressionEvaluationContext Evaluated(
8121 S, EnterExpressionEvaluationContext::InitList,
8122 isa_and_nonnull<InitListExpr>(Val: CurInit.get()));
8123
8124 // C++ [class.abstract]p2:
8125 // no objects of an abstract class can be created except as subobjects
8126 // of a class derived from it
8127 auto checkAbstractType = [&](QualType T) -> bool {
8128 if (Entity.getKind() == InitializedEntity::EK_Base ||
8129 Entity.getKind() == InitializedEntity::EK_Delegating)
8130 return false;
8131 return S.RequireNonAbstractType(Loc: Kind.getLocation(), T,
8132 DiagID: diag::err_allocation_of_abstract_type);
8133 };
8134
8135 // Walk through the computed steps for the initialization sequence,
8136 // performing the specified conversions along the way.
8137 bool ConstructorInitRequiresZeroInit = false;
8138 for (step_iterator Step = step_begin(), StepEnd = step_end();
8139 Step != StepEnd; ++Step) {
8140 if (CurInit.isInvalid())
8141 return ExprError();
8142
8143 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8144
8145 switch (Step->Kind) {
8146 case SK_ResolveAddressOfOverloadedFunction:
8147 // Overload resolution determined which function invoke; update the
8148 // initializer to reflect that choice.
8149 S.CheckAddressOfMemberAccess(OvlExpr: CurInit.get(), FoundDecl: Step->Function.FoundDecl);
8150 if (S.DiagnoseUseOfDecl(D: Step->Function.FoundDecl, Locs: Kind.getLocation()))
8151 return ExprError();
8152 CurInit = S.FixOverloadedFunctionReference(CurInit,
8153 FoundDecl: Step->Function.FoundDecl,
8154 Fn: Step->Function.Function);
8155 // We might get back another placeholder expression if we resolved to a
8156 // builtin.
8157 if (!CurInit.isInvalid())
8158 CurInit = S.CheckPlaceholderExpr(E: CurInit.get());
8159 break;
8160
8161 case SK_CastDerivedToBasePRValue:
8162 case SK_CastDerivedToBaseXValue:
8163 case SK_CastDerivedToBaseLValue: {
8164 // We have a derived-to-base cast that produces either an rvalue or an
8165 // lvalue. Perform that cast.
8166
8167 CXXCastPath BasePath;
8168
8169 // Casts to inaccessible base classes are allowed with C-style casts.
8170 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8171 if (S.CheckDerivedToBaseConversion(
8172 Derived: SourceType, Base: Step->Type, Loc: CurInit.get()->getBeginLoc(),
8173 Range: CurInit.get()->getSourceRange(), BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
8174 return ExprError();
8175
8176 ExprValueKind VK =
8177 Step->Kind == SK_CastDerivedToBaseLValue
8178 ? VK_LValue
8179 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8180 : VK_PRValue);
8181 CurInit = ImplicitCastExpr::Create(Context: S.Context, T: Step->Type,
8182 Kind: CK_DerivedToBase, Operand: CurInit.get(),
8183 BasePath: &BasePath, Cat: VK, FPO: FPOptionsOverride());
8184 break;
8185 }
8186
8187 case SK_BindReference:
8188 // Reference binding does not have any corresponding ASTs.
8189
8190 // Check exception specifications
8191 if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType))
8192 return ExprError();
8193
8194 // We don't check for e.g. function pointers here, since address
8195 // availability checks should only occur when the function first decays
8196 // into a pointer or reference.
8197 if (CurInit.get()->getType()->isFunctionProtoType()) {
8198 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CurInit.get()->IgnoreParens())) {
8199 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) {
8200 if (!S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
8201 Loc: DRE->getBeginLoc()))
8202 return ExprError();
8203 }
8204 }
8205 }
8206
8207 CheckForNullPointerDereference(S, E: CurInit.get());
8208 break;
8209
8210 case SK_BindReferenceToTemporary: {
8211 // Make sure the "temporary" is actually an rvalue.
8212 assert(CurInit.get()->isPRValue() && "not a temporary");
8213
8214 // Check exception specifications
8215 if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType))
8216 return ExprError();
8217
8218 QualType MTETy = Step->Type;
8219
8220 // When this is an incomplete array type (such as when this is
8221 // initializing an array of unknown bounds from an init list), use THAT
8222 // type instead so that we propagate the array bounds.
8223 if (MTETy->isIncompleteArrayType() &&
8224 !CurInit.get()->getType()->isIncompleteArrayType() &&
8225 S.Context.hasSameType(
8226 T1: MTETy->getPointeeOrArrayElementType(),
8227 T2: CurInit.get()->getType()->getPointeeOrArrayElementType()))
8228 MTETy = CurInit.get()->getType();
8229
8230 // Materialize the temporary into memory.
8231 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8232 T: MTETy, Temporary: CurInit.get(), BoundToLvalueReference: Entity.getType()->isLValueReferenceType());
8233 CurInit = MTE;
8234
8235 // If we're extending this temporary to automatic storage duration -- we
8236 // need to register its cleanup during the full-expression's cleanups.
8237 if (MTE->getStorageDuration() == SD_Automatic &&
8238 MTE->getType().isDestructedType())
8239 S.Cleanup.setExprNeedsCleanups(true);
8240 break;
8241 }
8242
8243 case SK_FinalCopy:
8244 if (checkAbstractType(Step->Type))
8245 return ExprError();
8246
8247 // If the overall initialization is initializing a temporary, we already
8248 // bound our argument if it was necessary to do so. If not (if we're
8249 // ultimately initializing a non-temporary), our argument needs to be
8250 // bound since it's initializing a function parameter.
8251 // FIXME: This is a mess. Rationalize temporary destruction.
8252 if (!shouldBindAsTemporary(Entity))
8253 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8254 CurInit = CopyObject(S, T: Step->Type, Entity, CurInit,
8255 /*IsExtraneousCopy=*/false);
8256 break;
8257
8258 case SK_ExtraneousCopyToTemporary:
8259 CurInit = CopyObject(S, T: Step->Type, Entity, CurInit,
8260 /*IsExtraneousCopy=*/true);
8261 break;
8262
8263 case SK_UserConversion: {
8264 // We have a user-defined conversion that invokes either a constructor
8265 // or a conversion function.
8266 CastKind CastKind;
8267 FunctionDecl *Fn = Step->Function.Function;
8268 DeclAccessPair FoundFn = Step->Function.FoundDecl;
8269 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8270 bool CreatedObject = false;
8271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
8272 // Build a call to the selected constructor.
8273 SmallVector<Expr*, 8> ConstructorArgs;
8274 SourceLocation Loc = CurInit.get()->getBeginLoc();
8275
8276 // Determine the arguments required to actually perform the constructor
8277 // call.
8278 Expr *Arg = CurInit.get();
8279 if (S.CompleteConstructorCall(Constructor, DeclInitType: Step->Type,
8280 ArgsPtr: MultiExprArg(&Arg, 1), Loc,
8281 ConvertedArgs&: ConstructorArgs))
8282 return ExprError();
8283
8284 // Build an expression that constructs a temporary.
8285 CurInit = S.BuildCXXConstructExpr(
8286 ConstructLoc: Loc, DeclInitType: Step->Type, FoundDecl: FoundFn, Constructor, Exprs: ConstructorArgs,
8287 HadMultipleCandidates,
8288 /*ListInit*/ IsListInitialization: false,
8289 /*StdInitListInit*/ IsStdInitListInitialization: false,
8290 /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
8291 if (CurInit.isInvalid())
8292 return ExprError();
8293
8294 S.CheckConstructorAccess(Loc: Kind.getLocation(), D: Constructor, FoundDecl: FoundFn,
8295 Entity);
8296 if (S.DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: Kind.getLocation()))
8297 return ExprError();
8298
8299 CastKind = CK_ConstructorConversion;
8300 CreatedObject = true;
8301 } else {
8302 // Build a call to the conversion function.
8303 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Val: Fn);
8304 S.CheckMemberOperatorAccess(Loc: Kind.getLocation(), ObjectExpr: CurInit.get(), ArgExpr: nullptr,
8305 FoundDecl: FoundFn);
8306 if (S.DiagnoseUseOfOverloadedDecl(D: Conversion, Loc: Kind.getLocation()))
8307 return ExprError();
8308
8309 CurInit = S.BuildCXXMemberCallExpr(Exp: CurInit.get(), FoundDecl: FoundFn, Method: Conversion,
8310 HadMultipleCandidates);
8311 if (CurInit.isInvalid())
8312 return ExprError();
8313
8314 CastKind = CK_UserDefinedConversion;
8315 CreatedObject = Conversion->getReturnType()->isRecordType();
8316 }
8317
8318 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8319 return ExprError();
8320
8321 CurInit = ImplicitCastExpr::Create(
8322 Context: S.Context, T: CurInit.get()->getType(), Kind: CastKind, Operand: CurInit.get(), BasePath: nullptr,
8323 Cat: CurInit.get()->getValueKind(), FPO: S.CurFPFeatureOverrides());
8324
8325 if (shouldBindAsTemporary(Entity))
8326 // The overall entity is temporary, so this expression should be
8327 // destroyed at the end of its full-expression.
8328 CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>());
8329 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8330 // The object outlasts the full-expression, but we need to prepare for
8331 // a destructor being run on it.
8332 // FIXME: It makes no sense to do this here. This should happen
8333 // regardless of how we initialized the entity.
8334 QualType T = CurInit.get()->getType();
8335 if (auto *Record = T->castAsCXXRecordDecl()) {
8336 CXXDestructorDecl *Destructor = S.LookupDestructor(Class: Record);
8337 S.CheckDestructorAccess(Loc: CurInit.get()->getBeginLoc(), Dtor: Destructor,
8338 PDiag: S.PDiag(DiagID: diag::err_access_dtor_temp) << T);
8339 S.MarkFunctionReferenced(Loc: CurInit.get()->getBeginLoc(), Func: Destructor);
8340 if (S.DiagnoseUseOfDecl(D: Destructor, Locs: CurInit.get()->getBeginLoc()))
8341 return ExprError();
8342 }
8343 }
8344 break;
8345 }
8346
8347 case SK_QualificationConversionLValue:
8348 case SK_QualificationConversionXValue:
8349 case SK_QualificationConversionPRValue: {
8350 // Perform a qualification conversion; these can never go wrong.
8351 ExprValueKind VK =
8352 Step->Kind == SK_QualificationConversionLValue
8353 ? VK_LValue
8354 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8355 : VK_PRValue);
8356 CurInit = S.PerformQualificationConversion(E: CurInit.get(), Ty: Step->Type, VK);
8357 break;
8358 }
8359
8360 case SK_FunctionReferenceConversion:
8361 assert(CurInit.get()->isLValue() &&
8362 "function reference should be lvalue");
8363 CurInit =
8364 S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, CK: CK_NoOp, VK: VK_LValue);
8365 break;
8366
8367 case SK_AtomicConversion: {
8368 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8369 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
8370 CK: CK_NonAtomicToAtomic, VK: VK_PRValue);
8371 break;
8372 }
8373
8374 case SK_ConversionSequence:
8375 case SK_ConversionSequenceNoNarrowing: {
8376 if (const auto *FromPtrType =
8377 CurInit.get()->getType()->getAs<PointerType>()) {
8378 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8379 if (FromPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) &&
8380 !ToPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
8381 // Do not check static casts here because they are checked earlier
8382 // in Sema::ActOnCXXNamedCast()
8383 if (!Kind.isStaticCast()) {
8384 S.Diag(Loc: CurInit.get()->getExprLoc(),
8385 DiagID: diag::warn_noderef_to_dereferenceable_pointer)
8386 << CurInit.get()->getSourceRange();
8387 }
8388 }
8389 }
8390 }
8391 Expr *Init = CurInit.get();
8392 CheckedConversionKind CCK =
8393 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
8394 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
8395 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
8396 : CheckedConversionKind::Implicit;
8397 ExprResult CurInitExprRes = S.PerformImplicitConversion(
8398 From: Init, ToType: Step->Type, ICS: *Step->ICS, Action: getAssignmentAction(Entity), CCK);
8399 if (CurInitExprRes.isInvalid())
8400 return ExprError();
8401
8402 S.DiscardMisalignedMemberAddress(T: Step->Type.getTypePtr(), E: Init);
8403
8404 CurInit = CurInitExprRes;
8405
8406 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
8407 S.getLangOpts().CPlusPlus)
8408 DiagnoseNarrowingInInitList(S, ICS: *Step->ICS, PreNarrowingType: SourceType, EntityType: Entity.getType(),
8409 PostInit: CurInit.get());
8410
8411 break;
8412 }
8413
8414 case SK_ListInitialization: {
8415 if (checkAbstractType(Step->Type))
8416 return ExprError();
8417
8418 InitListExpr *InitList = cast<InitListExpr>(Val: CurInit.get());
8419 // If we're not initializing the top-level entity, we need to create an
8420 // InitializeTemporary entity for our target type.
8421 QualType Ty = Step->Type;
8422 bool IsTemporary = !S.Context.hasSameType(T1: Entity.getType(), T2: Ty);
8423 InitializedEntity InitEntity =
8424 IsTemporary ? InitializedEntity::InitializeTemporary(Type: Ty) : Entity;
8425 InitListChecker PerformInitList(S, InitEntity,
8426 InitList, Ty, /*VerifyOnly=*/false,
8427 /*TreatUnavailableAsInvalid=*/false);
8428 if (PerformInitList.HadError())
8429 return ExprError();
8430
8431 // Hack: We must update *ResultType if available in order to set the
8432 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
8433 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
8434 if (ResultType &&
8435 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
8436 if ((*ResultType)->isRValueReferenceType())
8437 Ty = S.Context.getRValueReferenceType(T: Ty);
8438 else if ((*ResultType)->isLValueReferenceType())
8439 Ty = S.Context.getLValueReferenceType(T: Ty,
8440 SpelledAsLValue: (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
8441 *ResultType = Ty;
8442 }
8443
8444 InitListExpr *StructuredInitList =
8445 PerformInitList.getFullyStructuredList();
8446 CurInit = shouldBindAsTemporary(Entity: InitEntity)
8447 ? S.MaybeBindToTemporary(E: StructuredInitList)
8448 : StructuredInitList;
8449 break;
8450 }
8451
8452 case SK_ConstructorInitializationFromList: {
8453 if (checkAbstractType(Step->Type))
8454 return ExprError();
8455
8456 // When an initializer list is passed for a parameter of type "reference
8457 // to object", we don't get an EK_Temporary entity, but instead an
8458 // EK_Parameter entity with reference type.
8459 // FIXME: This is a hack. What we really should do is create a user
8460 // conversion step for this case, but this makes it considerably more
8461 // complicated. For now, this will do.
8462 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8463 Type: Entity.getType().getNonReferenceType());
8464 bool UseTemporary = Entity.getType()->isReferenceType();
8465 assert(Args.size() == 1 && "expected a single argument for list init");
8466 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
8467 S.Diag(Loc: InitList->getExprLoc(), DiagID: diag::warn_cxx98_compat_ctor_list_init)
8468 << InitList->getSourceRange();
8469 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
8470 CurInit = PerformConstructorInitialization(S, Entity: UseTemporary ? TempEntity :
8471 Entity,
8472 Kind, Args: Arg, Step: *Step,
8473 ConstructorInitRequiresZeroInit,
8474 /*IsListInitialization*/true,
8475 /*IsStdInitListInit*/IsStdInitListInitialization: false,
8476 LBraceLoc: InitList->getLBraceLoc(),
8477 RBraceLoc: InitList->getRBraceLoc());
8478 break;
8479 }
8480
8481 case SK_UnwrapInitList:
8482 CurInit = cast<InitListExpr>(Val: CurInit.get())->getInit(Init: 0);
8483 break;
8484
8485 case SK_RewrapInitList: {
8486 Expr *E = CurInit.get();
8487 InitListExpr *Syntactic = Step->WrappingSyntacticList;
8488 InitListExpr *ILE = new (S.Context)
8489 InitListExpr(S.Context, Syntactic->getLBraceLoc(), E,
8490 Syntactic->getRBraceLoc(), Syntactic->isExplicit());
8491 ILE->setSyntacticForm(Syntactic);
8492 ILE->setType(E->getType());
8493 ILE->setValueKind(E->getValueKind());
8494 CurInit = ILE;
8495 break;
8496 }
8497
8498 case SK_ConstructorInitialization:
8499 case SK_StdInitializerListConstructorCall: {
8500 if (checkAbstractType(Step->Type))
8501 return ExprError();
8502
8503 // When an initializer list is passed for a parameter of type "reference
8504 // to object", we don't get an EK_Temporary entity, but instead an
8505 // EK_Parameter entity with reference type.
8506 // FIXME: This is a hack. What we really should do is create a user
8507 // conversion step for this case, but this makes it considerably more
8508 // complicated. For now, this will do.
8509 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
8510 Type: Entity.getType().getNonReferenceType());
8511 bool UseTemporary = Entity.getType()->isReferenceType();
8512 bool IsStdInitListInit =
8513 Step->Kind == SK_StdInitializerListConstructorCall;
8514 Expr *Source = CurInit.get();
8515 SourceRange Range = Kind.hasParenOrBraceRange()
8516 ? Kind.getParenOrBraceRange()
8517 : SourceRange();
8518 CurInit = PerformConstructorInitialization(
8519 S, Entity: UseTemporary ? TempEntity : Entity, Kind,
8520 Args: Source ? MultiExprArg(Source) : Args, Step: *Step,
8521 ConstructorInitRequiresZeroInit,
8522 /*IsListInitialization*/ IsStdInitListInit,
8523 /*IsStdInitListInitialization*/ IsStdInitListInit,
8524 /*LBraceLoc*/ Range.getBegin(),
8525 /*RBraceLoc*/ Range.getEnd());
8526 break;
8527 }
8528
8529 case SK_ZeroInitialization: {
8530 step_iterator NextStep = Step;
8531 ++NextStep;
8532 if (NextStep != StepEnd &&
8533 (NextStep->Kind == SK_ConstructorInitialization ||
8534 NextStep->Kind == SK_ConstructorInitializationFromList)) {
8535 // The need for zero-initialization is recorded directly into
8536 // the call to the object's constructor within the next step.
8537 ConstructorInitRequiresZeroInit = true;
8538 } else if (Kind.getKind() == InitializationKind::IK_Value &&
8539 S.getLangOpts().CPlusPlus &&
8540 !Kind.isImplicitValueInit()) {
8541 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
8542 if (!TSInfo)
8543 TSInfo = S.Context.getTrivialTypeSourceInfo(T: Step->Type,
8544 Loc: Kind.getRange().getBegin());
8545
8546 CurInit = new (S.Context) CXXScalarValueInitExpr(
8547 Entity.getType().getNonLValueExprType(Context: S.Context), TSInfo,
8548 Kind.getRange().getEnd());
8549 } else {
8550 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
8551 // Note the return value isn't used to return a ExprError() when
8552 // initialization fails . For struct initialization allows all field
8553 // assignments to be checked rather than bailing on the first error.
8554 S.BoundsSafetyCheckInitialization(Entity, Kind,
8555 Action: AssignmentAction::Initializing,
8556 LHSType: Step->Type, RHSExpr: CurInit.get());
8557 }
8558 break;
8559 }
8560
8561 case SK_CAssignment: {
8562 QualType SourceType = CurInit.get()->getType();
8563 Expr *Init = CurInit.get();
8564
8565 // Save off the initial CurInit in case we need to emit a diagnostic
8566 ExprResult InitialCurInit = Init;
8567 ExprResult Result = Init;
8568 AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints(
8569 LHSType: Step->Type, RHS&: Result, Diagnose: true,
8570 DiagnoseCFAudited: Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
8571 if (Result.isInvalid())
8572 return ExprError();
8573 CurInit = Result;
8574
8575 // If this is a call, allow conversion to a transparent union.
8576 ExprResult CurInitExprRes = CurInit;
8577 if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() &&
8578 S.CheckTransparentUnionArgumentConstraints(
8579 ArgType: Step->Type, RHS&: CurInitExprRes) == AssignConvertType::Compatible)
8580 ConvTy = AssignConvertType::Compatible;
8581 if (CurInitExprRes.isInvalid())
8582 return ExprError();
8583 CurInit = CurInitExprRes;
8584
8585 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
8586 CheckC23ConstexprInitConversion(S, FromType: SourceType, ToType: Entity.getType(),
8587 Init: CurInit.get());
8588
8589 // C23 6.7.1p6: If an object or subobject declared with storage-class
8590 // specifier constexpr has pointer, integer, or arithmetic type, any
8591 // explicit initializer value for it shall be null, an integer
8592 // constant expression, or an arithmetic constant expression,
8593 // respectively.
8594 Expr::EvalResult ER;
8595 if (Entity.getType()->getAs<PointerType>() &&
8596 CurInit.get()->EvaluateAsRValue(Result&: ER, Ctx: S.Context) &&
8597 (ER.Val.isLValue() && !ER.Val.isNullPointer())) {
8598 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_c23_constexpr_pointer_not_null);
8599 return ExprError();
8600 }
8601 }
8602
8603 // Note the return value isn't used to return a ExprError() when
8604 // initialization fails. For struct initialization this allows all field
8605 // assignments to be checked rather than bailing on the first error.
8606 S.BoundsSafetyCheckInitialization(Entity, Kind,
8607 Action: getAssignmentAction(Entity, Diagnose: true),
8608 LHSType: Step->Type, RHSExpr: InitialCurInit.get());
8609
8610 bool Complained;
8611 if (S.DiagnoseAssignmentResult(ConvTy, Loc: Kind.getLocation(),
8612 DstType: Step->Type, SrcType: SourceType,
8613 SrcExpr: InitialCurInit.get(),
8614 Action: getAssignmentAction(Entity, Diagnose: true),
8615 Complained: &Complained)) {
8616 PrintInitLocationNote(S, Entity);
8617 return ExprError();
8618 } else if (Complained)
8619 PrintInitLocationNote(S, Entity);
8620 break;
8621 }
8622
8623 case SK_StringInit: {
8624 QualType Ty = Step->Type;
8625 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
8626 CheckStringInit(Str: CurInit.get(), DeclT&: UpdateType ? *ResultType : Ty,
8627 AT: S.Context.getAsArrayType(T: Ty), S, Entity,
8628 CheckC23ConstexprInit: S.getLangOpts().C23 &&
8629 initializingConstexprVariable(Entity));
8630 break;
8631 }
8632
8633 case SK_ObjCObjectConversion:
8634 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
8635 CK: CK_ObjCObjectLValueCast,
8636 VK: CurInit.get()->getValueKind());
8637 break;
8638
8639 case SK_ArrayLoopIndex: {
8640 Expr *Cur = CurInit.get();
8641 Expr *BaseExpr = new (S.Context)
8642 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
8643 Cur->getValueKind(), Cur->getObjectKind(), Cur);
8644 Expr *IndexExpr =
8645 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
8646 CurInit = S.CreateBuiltinArraySubscriptExpr(
8647 Base: BaseExpr, LLoc: Kind.getLocation(), Idx: IndexExpr, RLoc: Kind.getLocation());
8648 ArrayLoopCommonExprs.push_back(Elt: BaseExpr);
8649 break;
8650 }
8651
8652 case SK_ArrayLoopInit: {
8653 assert(!ArrayLoopCommonExprs.empty() &&
8654 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
8655 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
8656 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
8657 CurInit.get());
8658 break;
8659 }
8660
8661 case SK_GNUArrayInit:
8662 // Okay: we checked everything before creating this step. Note that
8663 // this is a GNU extension.
8664 S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_copy)
8665 << Step->Type << CurInit.get()->getType()
8666 << CurInit.get()->getSourceRange();
8667 updateGNUCompoundLiteralRValue(E: CurInit.get());
8668 [[fallthrough]];
8669 case SK_ArrayInit:
8670 // If the destination type is an incomplete array type, update the
8671 // type accordingly.
8672 if (ResultType) {
8673 if (const IncompleteArrayType *IncompleteDest
8674 = S.Context.getAsIncompleteArrayType(T: Step->Type)) {
8675 if (const ConstantArrayType *ConstantSource
8676 = S.Context.getAsConstantArrayType(T: CurInit.get()->getType())) {
8677 *ResultType = S.Context.getConstantArrayType(
8678 EltTy: IncompleteDest->getElementType(), ArySize: ConstantSource->getSize(),
8679 SizeExpr: ConstantSource->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
8680 }
8681 }
8682 }
8683 break;
8684
8685 case SK_ParenthesizedArrayInit:
8686 // Okay: we checked everything before creating this step. Note that
8687 // this is a GNU extension.
8688 S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_parens)
8689 << CurInit.get()->getSourceRange();
8690 break;
8691
8692 case SK_PassByIndirectCopyRestore:
8693 case SK_PassByIndirectRestore:
8694 checkIndirectCopyRestoreSource(S, src: CurInit.get());
8695 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
8696 CurInit.get(), Step->Type,
8697 Step->Kind == SK_PassByIndirectCopyRestore);
8698 break;
8699
8700 case SK_ProduceObjCObject:
8701 CurInit = ImplicitCastExpr::Create(
8702 Context: S.Context, T: Step->Type, Kind: CK_ARCProduceObject, Operand: CurInit.get(), BasePath: nullptr,
8703 Cat: VK_PRValue, FPO: FPOptionsOverride());
8704 break;
8705
8706 case SK_StdInitializerList: {
8707 S.Diag(Loc: CurInit.get()->getExprLoc(),
8708 DiagID: diag::warn_cxx98_compat_initializer_list_init)
8709 << CurInit.get()->getSourceRange();
8710
8711 // Materialize the temporary into memory.
8712 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8713 T: CurInit.get()->getType(), Temporary: CurInit.get(),
8714 /*BoundToLvalueReference=*/false);
8715
8716 // Wrap it in a construction of a std::initializer_list<T>.
8717 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
8718
8719 if (!Step->Type->isDependentType()) {
8720 QualType ElementType;
8721 [[maybe_unused]] bool IsStdInitializerList =
8722 S.isStdInitializerList(Ty: Step->Type, Element: &ElementType);
8723 assert(IsStdInitializerList &&
8724 "StdInitializerList step to non-std::initializer_list");
8725 const auto *Record = Step->Type->castAsCXXRecordDecl();
8726 assert(Record->isCompleteDefinition() &&
8727 "std::initializer_list should have already be "
8728 "complete/instantiated by this point");
8729
8730 auto InvalidType = [&] {
8731 S.Diag(Loc: Record->getLocation(),
8732 DiagID: diag::err_std_initializer_list_malformed)
8733 << Step->Type.getUnqualifiedType();
8734 return ExprError();
8735 };
8736
8737 if (Record->isUnion() || Record->getNumBases() != 0 ||
8738 Record->isPolymorphic())
8739 return InvalidType();
8740
8741 RecordDecl::field_iterator Field = Record->field_begin();
8742 if (Field == Record->field_end())
8743 return InvalidType();
8744
8745 // Start pointer
8746 if (!Field->getType()->isPointerType() ||
8747 !S.Context.hasSameType(T1: Field->getType()->getPointeeType(),
8748 T2: ElementType.withConst()))
8749 return InvalidType();
8750
8751 if (++Field == Record->field_end())
8752 return InvalidType();
8753
8754 // Size or end pointer
8755 if (const auto *PT = Field->getType()->getAs<PointerType>()) {
8756 if (!S.Context.hasSameType(T1: PT->getPointeeType(),
8757 T2: ElementType.withConst()))
8758 return InvalidType();
8759 } else {
8760 if (Field->isBitField() ||
8761 !S.Context.hasSameType(T1: Field->getType(), T2: S.Context.getSizeType()))
8762 return InvalidType();
8763 }
8764
8765 if (++Field != Record->field_end())
8766 return InvalidType();
8767 }
8768
8769 // Bind the result, in case the library has given initializer_list a
8770 // non-trivial destructor.
8771 if (shouldBindAsTemporary(Entity))
8772 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8773 break;
8774 }
8775
8776 case SK_OCLSamplerInit: {
8777 // Sampler initialization have 5 cases:
8778 // 1. function argument passing
8779 // 1a. argument is a file-scope variable
8780 // 1b. argument is a function-scope variable
8781 // 1c. argument is one of caller function's parameters
8782 // 2. variable initialization
8783 // 2a. initializing a file-scope variable
8784 // 2b. initializing a function-scope variable
8785 //
8786 // For file-scope variables, since they cannot be initialized by function
8787 // call of __translate_sampler_initializer in LLVM IR, their references
8788 // need to be replaced by a cast from their literal initializers to
8789 // sampler type. Since sampler variables can only be used in function
8790 // calls as arguments, we only need to replace them when handling the
8791 // argument passing.
8792 assert(Step->Type->isSamplerT() &&
8793 "Sampler initialization on non-sampler type.");
8794 Expr *Init = CurInit.get()->IgnoreParens();
8795 QualType SourceType = Init->getType();
8796 // Case 1
8797 if (Entity.isParameterKind()) {
8798 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
8799 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_argument_required)
8800 << SourceType;
8801 break;
8802 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Init)) {
8803 auto Var = cast<VarDecl>(Val: DRE->getDecl());
8804 // Case 1b and 1c
8805 // No cast from integer to sampler is needed.
8806 if (!Var->hasGlobalStorage()) {
8807 CurInit = ImplicitCastExpr::Create(
8808 Context: S.Context, T: Step->Type, Kind: CK_LValueToRValue, Operand: Init,
8809 /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
8810 break;
8811 }
8812 // Case 1a
8813 // For function call with a file-scope sampler variable as argument,
8814 // get the integer literal.
8815 // Do not diagnose if the file-scope variable does not have initializer
8816 // since this has already been diagnosed when parsing the variable
8817 // declaration.
8818 if (!Var->getInit() || !isa<ImplicitCastExpr>(Val: Var->getInit()))
8819 break;
8820 Init = cast<ImplicitCastExpr>(Val: const_cast<Expr*>(
8821 Var->getInit()))->getSubExpr();
8822 SourceType = Init->getType();
8823 }
8824 } else {
8825 // Case 2
8826 // Check initializer is 32 bit integer constant.
8827 // If the initializer is taken from global variable, do not diagnose since
8828 // this has already been done when parsing the variable declaration.
8829 if (!Init->isConstantInitializer(Ctx&: S.Context))
8830 break;
8831
8832 if (!SourceType->isIntegerType() ||
8833 32 != S.Context.getIntWidth(T: SourceType)) {
8834 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_initializer_not_integer)
8835 << SourceType;
8836 break;
8837 }
8838
8839 Expr::EvalResult EVResult;
8840 Init->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
8841 llvm::APSInt Result = EVResult.Val.getInt();
8842 const uint64_t SamplerValue = Result.getLimitedValue();
8843 // 32-bit value of sampler's initializer is interpreted as
8844 // bit-field with the following structure:
8845 // |unspecified|Filter|Addressing Mode| Normalized Coords|
8846 // |31 6|5 4|3 1| 0|
8847 // This structure corresponds to enum values of sampler properties
8848 // defined in SPIR spec v1.2 and also opencl-c.h
8849 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
8850 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
8851 if (FilterMode != 1 && FilterMode != 2 &&
8852 !S.getOpenCLOptions().isAvailableOption(
8853 Ext: "cl_intel_device_side_avc_motion_estimation", LO: S.getLangOpts()))
8854 S.Diag(Loc: Kind.getLocation(),
8855 DiagID: diag::warn_sampler_initializer_invalid_bits)
8856 << "Filter Mode";
8857 if (AddressingMode > 4)
8858 S.Diag(Loc: Kind.getLocation(),
8859 DiagID: diag::warn_sampler_initializer_invalid_bits)
8860 << "Addressing Mode";
8861 }
8862
8863 // Cases 1a, 2a and 2b
8864 // Insert cast from integer to sampler.
8865 CurInit = S.ImpCastExprToType(E: Init, Type: S.Context.OCLSamplerTy,
8866 CK: CK_IntToOCLSampler);
8867 break;
8868 }
8869 case SK_OCLZeroOpaqueType: {
8870 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
8871 Step->Type->isOCLIntelSubgroupAVCType()) &&
8872 "Wrong type for initialization of OpenCL opaque type.");
8873
8874 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
8875 CK: CK_ZeroToOCLOpaqueType,
8876 VK: CurInit.get()->getValueKind());
8877 break;
8878 }
8879 case SK_ParenthesizedListInit: {
8880 CurInit = nullptr;
8881 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
8882 /*VerifyOnly=*/false, Result: &CurInit);
8883 if (CurInit.get() && ResultType)
8884 *ResultType = CurInit.get()->getType();
8885 if (shouldBindAsTemporary(Entity))
8886 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8887 break;
8888 }
8889 case SK_HLSLBufferConversion: {
8890 CurInit = ImplicitCastExpr::Create(
8891 Context: S.Context, T: Step->Type.getLocalUnqualifiedType(), Kind: CK_LValueToRValue,
8892 Operand: CurInit.get(),
8893 /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
8894 break;
8895 }
8896 }
8897 }
8898
8899 Expr *Init = CurInit.get();
8900 if (!Init)
8901 return ExprError();
8902
8903 // Check whether the initializer has a shorter lifetime than the initialized
8904 // entity, and if not, either lifetime-extend or warn as appropriate.
8905 S.checkInitializerLifetime(Entity, Init);
8906
8907 // Diagnose non-fatal problems with the completed initialization.
8908 if (InitializedEntity::EntityKind EK = Entity.getKind();
8909 (EK == InitializedEntity::EK_Member ||
8910 EK == InitializedEntity::EK_ParenAggInitMember) &&
8911 cast<FieldDecl>(Val: Entity.getDecl())->isBitField())
8912 S.CheckBitFieldInitialization(InitLoc: Kind.getLocation(),
8913 Field: cast<FieldDecl>(Val: Entity.getDecl()), Init);
8914
8915 // Check for std::move on construction.
8916 CheckMoveOnConstruction(S, InitExpr: Init,
8917 IsReturnStmt: Entity.getKind() == InitializedEntity::EK_Result);
8918
8919 return Init;
8920}
8921
8922/// Somewhere within T there is an uninitialized reference subobject.
8923/// Dig it out and diagnose it.
8924static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
8925 QualType T) {
8926 if (T->isReferenceType()) {
8927 S.Diag(Loc, DiagID: diag::err_reference_without_init)
8928 << T.getNonReferenceType();
8929 return true;
8930 }
8931
8932 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
8933 if (!RD || !RD->hasUninitializedReferenceMember())
8934 return false;
8935
8936 for (const auto *FI : RD->fields()) {
8937 if (FI->isUnnamedBitField())
8938 continue;
8939
8940 if (DiagnoseUninitializedReference(S, Loc: FI->getLocation(), T: FI->getType())) {
8941 S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD;
8942 return true;
8943 }
8944 }
8945
8946 for (const auto &BI : RD->bases()) {
8947 if (DiagnoseUninitializedReference(S, Loc: BI.getBeginLoc(), T: BI.getType())) {
8948 S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD;
8949 return true;
8950 }
8951 }
8952
8953 return false;
8954}
8955
8956
8957//===----------------------------------------------------------------------===//
8958// Diagnose initialization failures
8959//===----------------------------------------------------------------------===//
8960
8961/// Emit notes associated with an initialization that failed due to a
8962/// "simple" conversion failure.
8963static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
8964 Expr *op) {
8965 QualType destType = entity.getType();
8966 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
8967 op->getType()->isObjCObjectPointerType()) {
8968
8969 // Emit a possible note about the conversion failing because the
8970 // operand is a message send with a related result type.
8971 S.ObjC().EmitRelatedResultTypeNote(E: op);
8972
8973 // Emit a possible note about a return failing because we're
8974 // expecting a related result type.
8975 if (entity.getKind() == InitializedEntity::EK_Result)
8976 S.ObjC().EmitRelatedResultTypeNoteForReturn(destType);
8977 }
8978 QualType fromType = op->getType();
8979 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
8980 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
8981 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
8982 auto *destDecl = destType->getPointeeCXXRecordDecl();
8983 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
8984 destDecl->getDeclKind() == Decl::CXXRecord &&
8985 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
8986 !fromDecl->hasDefinition() &&
8987 destPointeeType.getQualifiers().compatiblyIncludes(
8988 other: fromPointeeType.getQualifiers(), Ctx: S.getASTContext()))
8989 S.Diag(Loc: fromDecl->getLocation(), DiagID: diag::note_forward_class_conversion)
8990 << S.getASTContext().getCanonicalTagType(TD: fromDecl)
8991 << S.getASTContext().getCanonicalTagType(TD: destDecl);
8992}
8993
8994static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
8995 InitListExpr *InitList) {
8996 QualType DestType = Entity.getType();
8997
8998 QualType E;
8999 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(Ty: DestType, Element: &E)) {
9000 QualType ArrayType = S.Context.getConstantArrayType(
9001 EltTy: E.withConst(),
9002 ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()),
9003 InitList->getNumInits()),
9004 SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0);
9005 InitializedEntity HiddenArray =
9006 InitializedEntity::InitializeTemporary(Type: ArrayType);
9007 return diagnoseListInit(S, Entity: HiddenArray, InitList);
9008 }
9009
9010 if (DestType->isReferenceType()) {
9011 // A list-initialization failure for a reference means that we tried to
9012 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9013 // inner initialization failed.
9014 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9015 diagnoseListInit(S, Entity: InitializedEntity::InitializeTemporary(Type: T), InitList);
9016 SourceLocation Loc = InitList->getBeginLoc();
9017 if (auto *D = Entity.getDecl())
9018 Loc = D->getLocation();
9019 S.Diag(Loc, DiagID: diag::note_in_reference_temporary_list_initializer) << T;
9020 return;
9021 }
9022
9023 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9024 /*VerifyOnly=*/false,
9025 /*TreatUnavailableAsInvalid=*/false);
9026 assert(DiagnoseInitList.HadError() &&
9027 "Inconsistent init list check result.");
9028}
9029
9030bool InitializationSequence::Diagnose(Sema &S,
9031 const InitializedEntity &Entity,
9032 const InitializationKind &Kind,
9033 ArrayRef<Expr *> Args) {
9034 if (!Failed())
9035 return false;
9036
9037 QualType DestType = Entity.getType();
9038
9039 // When we want to diagnose only one element of a braced-init-list,
9040 // we need to factor it out.
9041 Expr *OnlyArg;
9042 if (Args.size() == 1) {
9043 auto *List = dyn_cast<InitListExpr>(Val: Args[0]);
9044 if (List && List->getNumInits() == 1)
9045 OnlyArg = List->getInit(Init: 0);
9046 else
9047 OnlyArg = Args[0];
9048
9049 if (OnlyArg->getType() == S.Context.OverloadTy) {
9050 DeclAccessPair Found;
9051 if (FunctionDecl *FD = S.ResolveAddressOfOverloadedFunction(
9052 AddressOfExpr: OnlyArg, TargetType: DestType.getNonReferenceType(), /*Complain=*/false,
9053 Found)) {
9054 if (Expr *Resolved =
9055 S.FixOverloadedFunctionReference(E: OnlyArg, FoundDecl: Found, Fn: FD).get())
9056 OnlyArg = Resolved;
9057 }
9058 }
9059 }
9060 else
9061 OnlyArg = nullptr;
9062
9063 switch (Failure) {
9064 case FK_TooManyInitsForReference:
9065 // FIXME: Customize for the initialized entity?
9066 if (Args.empty()) {
9067 // Dig out the reference subobject which is uninitialized and diagnose it.
9068 // If this is value-initialization, this could be nested some way within
9069 // the target type.
9070 assert(Kind.getKind() == InitializationKind::IK_Value ||
9071 DestType->isReferenceType());
9072 bool Diagnosed =
9073 DiagnoseUninitializedReference(S, Loc: Kind.getLocation(), T: DestType);
9074 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9075 (void)Diagnosed;
9076 } else // FIXME: diagnostic below could be better!
9077 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_has_multiple_inits)
9078 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9079 break;
9080 case FK_ParenthesizedListInitForReference:
9081 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens)
9082 << 1 << Entity.getType() << Args[0]->getSourceRange();
9083 break;
9084
9085 case FK_ArrayNeedsInitList:
9086 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 0;
9087 break;
9088 case FK_ArrayNeedsInitListOrStringLiteral:
9089 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 1;
9090 break;
9091 case FK_ArrayNeedsInitListOrWideStringLiteral:
9092 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 2;
9093 break;
9094 case FK_NarrowStringIntoWideCharArray:
9095 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_narrow_string_into_wchar);
9096 break;
9097 case FK_WideStringIntoCharArray:
9098 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_wide_string_into_char);
9099 break;
9100 case FK_IncompatWideStringIntoWideChar:
9101 S.Diag(Loc: Kind.getLocation(),
9102 DiagID: diag::err_array_init_incompat_wide_string_into_wchar);
9103 break;
9104 case FK_PlainStringIntoUTF8Char:
9105 S.Diag(Loc: Kind.getLocation(),
9106 DiagID: diag::err_array_init_plain_string_into_char8_t);
9107 S.Diag(Loc: Args.front()->getBeginLoc(),
9108 DiagID: diag::note_array_init_plain_string_into_char8_t)
9109 << FixItHint::CreateInsertion(InsertionLoc: Args.front()->getBeginLoc(), Code: "u8");
9110 break;
9111 case FK_UTF8StringIntoPlainChar:
9112 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_utf8_string_into_char)
9113 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9114 break;
9115 case FK_ArrayTypeMismatch:
9116 case FK_NonConstantArrayInit:
9117 S.Diag(Loc: Kind.getLocation(),
9118 DiagID: (Failure == FK_ArrayTypeMismatch
9119 ? diag::err_array_init_different_type
9120 : diag::err_array_init_non_constant_array))
9121 << DestType.getNonReferenceType()
9122 << OnlyArg->getType()
9123 << Args[0]->getSourceRange();
9124 break;
9125
9126 case FK_VariableLengthArrayHasInitializer:
9127 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_variable_object_no_init)
9128 << Args[0]->getSourceRange();
9129 break;
9130
9131 case FK_AddressOfOverloadFailed: {
9132 DeclAccessPair Found;
9133 S.ResolveAddressOfOverloadedFunction(AddressOfExpr: OnlyArg,
9134 TargetType: DestType.getNonReferenceType(),
9135 Complain: true,
9136 Found);
9137 break;
9138 }
9139
9140 case FK_AddressOfUnaddressableFunction: {
9141 auto *FD = cast<FunctionDecl>(Val: cast<DeclRefExpr>(Val: OnlyArg)->getDecl());
9142 S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
9143 Loc: OnlyArg->getBeginLoc());
9144 break;
9145 }
9146
9147 case FK_ReferenceInitOverloadFailed:
9148 case FK_UserConversionOverloadFailed:
9149 switch (FailedOverloadResult) {
9150 case OR_Ambiguous:
9151
9152 FailedCandidateSet.NoteCandidates(
9153 PA: PartialDiagnosticAt(
9154 Kind.getLocation(),
9155 Failure == FK_UserConversionOverloadFailed
9156 ? (S.PDiag(DiagID: diag::err_typecheck_ambiguous_condition)
9157 << OnlyArg->getType() << DestType
9158 << Args[0]->getSourceRange())
9159 : (S.PDiag(DiagID: diag::err_ref_init_ambiguous)
9160 << DestType << OnlyArg->getType()
9161 << Args[0]->getSourceRange())),
9162 S, OCD: OCD_AmbiguousCandidates, Args);
9163 break;
9164
9165 case OR_No_Viable_Function: {
9166 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args);
9167 if (!S.RequireCompleteType(Loc: Kind.getLocation(),
9168 T: DestType.getNonReferenceType(),
9169 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
9170 Args: OnlyArg->getType(), Args: Args[0]->getSourceRange()))
9171 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_nonviable_condition)
9172 << (Entity.getKind() == InitializedEntity::EK_Result)
9173 << OnlyArg->getType() << Args[0]->getSourceRange()
9174 << DestType.getNonReferenceType();
9175
9176 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9177 break;
9178 }
9179 case OR_Deleted: {
9180 OverloadCandidateSet::iterator Best;
9181 OverloadingResult Ovl
9182 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9183
9184 StringLiteral *Msg = Best->Function->getDeletedMessage();
9185 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_deleted_function)
9186 << OnlyArg->getType() << DestType.getNonReferenceType()
9187 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9188 << Args[0]->getSourceRange();
9189 if (Ovl == OR_Deleted) {
9190 S.NoteDeletedFunction(FD: Best->Function);
9191 } else {
9192 llvm_unreachable("Inconsistent overload resolution?");
9193 }
9194 break;
9195 }
9196
9197 case OR_Success:
9198 llvm_unreachable("Conversion did not fail!");
9199 }
9200 break;
9201
9202 case FK_NonConstLValueReferenceBindingToTemporary:
9203 if (isa<InitListExpr>(Val: Args[0])) {
9204 S.Diag(Loc: Kind.getLocation(),
9205 DiagID: diag::err_lvalue_reference_bind_to_initlist)
9206 << DestType.getNonReferenceType().isVolatileQualified()
9207 << DestType.getNonReferenceType()
9208 << Args[0]->getSourceRange();
9209 break;
9210 }
9211 [[fallthrough]];
9212
9213 case FK_NonConstLValueReferenceBindingToUnrelated:
9214 S.Diag(Loc: Kind.getLocation(),
9215 DiagID: Failure == FK_NonConstLValueReferenceBindingToTemporary
9216 ? diag::err_lvalue_reference_bind_to_temporary
9217 : diag::err_lvalue_reference_bind_to_unrelated)
9218 << DestType.getNonReferenceType().isVolatileQualified()
9219 << DestType.getNonReferenceType()
9220 << OnlyArg->getType()
9221 << Args[0]->getSourceRange();
9222 break;
9223
9224 case FK_NonConstLValueReferenceBindingToBitfield: {
9225 // We don't necessarily have an unambiguous source bit-field.
9226 FieldDecl *BitField = Args[0]->getSourceBitField();
9227 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_bitfield)
9228 << DestType.isVolatileQualified()
9229 << (BitField ? BitField->getDeclName() : DeclarationName())
9230 << (BitField != nullptr)
9231 << Args[0]->getSourceRange();
9232 if (BitField)
9233 S.Diag(Loc: BitField->getLocation(), DiagID: diag::note_bitfield_decl);
9234 break;
9235 }
9236
9237 case FK_NonConstLValueReferenceBindingToVectorElement:
9238 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_vector_element)
9239 << DestType.isVolatileQualified()
9240 << Args[0]->getSourceRange();
9241 break;
9242
9243 case FK_NonConstLValueReferenceBindingToMatrixElement:
9244 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_matrix_element)
9245 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9246 break;
9247
9248 case FK_RValueReferenceBindingToLValue:
9249 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_lvalue_to_rvalue_ref)
9250 << DestType.getNonReferenceType() << OnlyArg->getType()
9251 << Args[0]->getSourceRange();
9252 break;
9253
9254 case FK_ReferenceAddrspaceMismatchTemporary:
9255 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_temporary_addrspace)
9256 << DestType << Args[0]->getSourceRange();
9257 break;
9258
9259 case FK_ReferenceInitDropsQualifiers: {
9260 QualType SourceType = OnlyArg->getType();
9261 QualType NonRefType = DestType.getNonReferenceType();
9262 Qualifiers DroppedQualifiers =
9263 SourceType.getQualifiers() - NonRefType.getQualifiers();
9264
9265 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9266 other: SourceType.getQualifiers(), Ctx: S.getASTContext()))
9267 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals)
9268 << NonRefType << SourceType << 1 /*addr space*/
9269 << Args[0]->getSourceRange();
9270 else if (DroppedQualifiers.hasQualifiers())
9271 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals)
9272 << NonRefType << SourceType << 0 /*cv quals*/
9273 << Qualifiers::fromCVRMask(CVR: DroppedQualifiers.getCVRQualifiers())
9274 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9275 else
9276 // FIXME: Consider decomposing the type and explaining which qualifiers
9277 // were dropped where, or on which level a 'const' is missing, etc.
9278 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals)
9279 << NonRefType << SourceType << 2 /*incompatible quals*/
9280 << Args[0]->getSourceRange();
9281 break;
9282 }
9283
9284 case FK_ReferenceInitFailed:
9285 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_failed)
9286 << DestType.getNonReferenceType()
9287 << DestType.getNonReferenceType()->isIncompleteType()
9288 << OnlyArg->isLValue()
9289 << OnlyArg->getType()
9290 << Args[0]->getSourceRange();
9291 emitBadConversionNotes(S, entity: Entity, op: Args[0]);
9292 break;
9293
9294 case FK_ConversionFailed: {
9295 QualType FromType = OnlyArg->getType();
9296 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op
9297 // type, although this is almost always an error and we advise against it.
9298 if (FromType == S.Context.AMDGPUFeaturePredicateTy &&
9299 DestType == S.Context.getLogicalOperationType()) {
9300 S.Diag(Loc: OnlyArg->getExprLoc(),
9301 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
9302 << OnlyArg << DestType;
9303 break;
9304 }
9305 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::err_init_conversion_failed)
9306 << (int)Entity.getKind()
9307 << DestType
9308 << OnlyArg->isLValue()
9309 << FromType
9310 << Args[0]->getSourceRange();
9311 S.HandleFunctionTypeMismatch(PDiag, FromType, ToType: DestType);
9312 S.Diag(Loc: Kind.getLocation(), PD: PDiag);
9313 emitBadConversionNotes(S, entity: Entity, op: Args[0]);
9314 break;
9315 }
9316
9317 case FK_ConversionFromPropertyFailed:
9318 // No-op. This error has already been reported.
9319 break;
9320
9321 case FK_TooManyInitsForScalar: {
9322 SourceRange R;
9323
9324 auto *InitList = dyn_cast<InitListExpr>(Val: Args[0]);
9325 if (InitList && InitList->getNumInits() >= 1) {
9326 R = SourceRange(InitList->getInit(Init: 0)->getEndLoc(), InitList->getEndLoc());
9327 } else {
9328 assert(Args.size() > 1 && "Expected multiple initializers!");
9329 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9330 }
9331
9332 R.setBegin(S.getLocForEndOfToken(Loc: R.getBegin()));
9333 if (Kind.isCStyleOrFunctionalCast())
9334 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_builtin_func_cast_more_than_one_arg)
9335 << R;
9336 else
9337 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers)
9338 << /*scalar=*/3 << R;
9339 break;
9340 }
9341
9342 case FK_ParenthesizedListInitForScalar:
9343 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens)
9344 << 0 << Entity.getType() << Args[0]->getSourceRange();
9345 break;
9346
9347 case FK_ReferenceBindingToInitList:
9348 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_init_list)
9349 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9350 break;
9351
9352 case FK_InitListBadDestinationType:
9353 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_init_list_bad_dest_type)
9354 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9355 break;
9356
9357 case FK_ListConstructorOverloadFailed:
9358 case FK_ConstructorOverloadFailed: {
9359 SourceRange ArgsRange;
9360 if (Args.size())
9361 ArgsRange =
9362 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9363
9364 if (Failure == FK_ListConstructorOverloadFailed) {
9365 assert(Args.size() == 1 &&
9366 "List construction from other than 1 argument.");
9367 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9368 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9369 }
9370
9371 // FIXME: Using "DestType" for the entity we're printing is probably
9372 // bad.
9373 switch (FailedOverloadResult) {
9374 case OR_Ambiguous:
9375 FailedCandidateSet.NoteCandidates(
9376 PA: PartialDiagnosticAt(Kind.getLocation(),
9377 S.PDiag(DiagID: diag::err_ovl_ambiguous_init)
9378 << DestType << ArgsRange),
9379 S, OCD: OCD_AmbiguousCandidates, Args);
9380 break;
9381
9382 case OR_No_Viable_Function:
9383 if (Kind.getKind() == InitializationKind::IK_Default &&
9384 (Entity.getKind() == InitializedEntity::EK_Base ||
9385 Entity.getKind() == InitializedEntity::EK_Member ||
9386 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9387 isa<CXXConstructorDecl>(Val: S.CurContext)) {
9388 // This is implicit default initialization of a member or
9389 // base within a constructor. If no viable function was
9390 // found, notify the user that they need to explicitly
9391 // initialize this base/member.
9392 CXXConstructorDecl *Constructor
9393 = cast<CXXConstructorDecl>(Val: S.CurContext);
9394 const CXXRecordDecl *InheritedFrom = nullptr;
9395 if (auto Inherited = Constructor->getInheritedConstructor())
9396 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9397 if (Entity.getKind() == InitializedEntity::EK_Base) {
9398 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor)
9399 << (InheritedFrom ? 2
9400 : Constructor->isImplicit() ? 1
9401 : 0)
9402 << S.Context.getCanonicalTagType(TD: Constructor->getParent())
9403 << /*base=*/0 << Entity.getType() << InheritedFrom;
9404
9405 auto *BaseDecl =
9406 Entity.getBaseSpecifier()->getType()->castAsRecordDecl();
9407 S.Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_previous_decl)
9408 << S.Context.getCanonicalTagType(TD: BaseDecl);
9409 } else {
9410 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor)
9411 << (InheritedFrom ? 2
9412 : Constructor->isImplicit() ? 1
9413 : 0)
9414 << S.Context.getCanonicalTagType(TD: Constructor->getParent())
9415 << /*member=*/1 << Entity.getName() << InheritedFrom;
9416 S.Diag(Loc: Entity.getDecl()->getLocation(),
9417 DiagID: diag::note_member_declared_at);
9418
9419 if (const auto *Record = Entity.getType()->getAs<RecordType>())
9420 S.Diag(Loc: Record->getDecl()->getLocation(), DiagID: diag::note_previous_decl)
9421 << S.Context.getCanonicalTagType(TD: Record->getDecl());
9422 }
9423 break;
9424 }
9425
9426 FailedCandidateSet.NoteCandidates(
9427 PA: PartialDiagnosticAt(
9428 Kind.getLocation(),
9429 S.PDiag(DiagID: diag::err_ovl_no_viable_function_in_init)
9430 << DestType << ArgsRange),
9431 S, OCD: OCD_AllCandidates, Args);
9432 break;
9433
9434 case OR_Deleted: {
9435 OverloadCandidateSet::iterator Best;
9436 OverloadingResult Ovl
9437 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9438 if (Ovl != OR_Deleted) {
9439 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init)
9440 << DestType << ArgsRange;
9441 llvm_unreachable("Inconsistent overload resolution?");
9442 break;
9443 }
9444
9445 // If this is a defaulted or implicitly-declared function, then
9446 // it was implicitly deleted. Make it clear that the deletion was
9447 // implicit.
9448 if (S.isImplicitlyDeleted(FD: Best->Function))
9449 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_special_init)
9450 << cast<CXXMethodDecl>(Val: Best->Function)->getSpecialMemberKind()
9451 << DestType << ArgsRange;
9452 else {
9453 StringLiteral *Msg = Best->Function->getDeletedMessage();
9454 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init)
9455 << DestType << (Msg != nullptr)
9456 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
9457 }
9458
9459 // If it's a default constructed member, but it's not in the
9460 // constructor's initializer list, explicitly note where the member is
9461 // declared so the user can see which member is erroneously initialized
9462 // with a deleted default constructor.
9463 if (Kind.getKind() == InitializationKind::IK_Default &&
9464 (Entity.getKind() == InitializedEntity::EK_Member ||
9465 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember)) {
9466 S.Diag(Loc: Entity.getDecl()->getLocation(),
9467 DiagID: diag::note_default_constructed_field)
9468 << Entity.getDecl();
9469 }
9470 S.NoteDeletedFunction(FD: Best->Function);
9471 break;
9472 }
9473
9474 case OR_Success:
9475 llvm_unreachable("Conversion did not fail!");
9476 }
9477 }
9478 break;
9479
9480 case FK_DefaultInitOfConst:
9481 if (Entity.getKind() == InitializedEntity::EK_Member &&
9482 isa<CXXConstructorDecl>(Val: S.CurContext)) {
9483 // This is implicit default-initialization of a const member in
9484 // a constructor. Complain that it needs to be explicitly
9485 // initialized.
9486 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: S.CurContext);
9487 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_uninitialized_member_in_ctor)
9488 << (Constructor->getInheritedConstructor() ? 2
9489 : Constructor->isImplicit() ? 1
9490 : 0)
9491 << S.Context.getCanonicalTagType(TD: Constructor->getParent())
9492 << /*const=*/1 << Entity.getName();
9493 S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_previous_decl)
9494 << Entity.getName();
9495 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: Entity.getDecl());
9496 VD && VD->isConstexpr()) {
9497 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
9498 << VD;
9499 } else {
9500 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_default_init_const)
9501 << DestType << DestType->isRecordType();
9502 }
9503 break;
9504
9505 case FK_Incomplete:
9506 S.RequireCompleteType(Loc: Kind.getLocation(), T: FailedIncompleteType,
9507 DiagID: diag::err_init_incomplete_type);
9508 break;
9509
9510 case FK_ListInitializationFailed: {
9511 // Run the init list checker again to emit diagnostics.
9512 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9513 diagnoseListInit(S, Entity, InitList);
9514 break;
9515 }
9516
9517 case FK_PlaceholderType: {
9518 // FIXME: Already diagnosed!
9519 break;
9520 }
9521
9522 case InitializationSequence::FK_HLSLInitListFlatteningFailed: {
9523 // Unlike C/C++ list initialization, there is no fallback if it fails. This
9524 // allows us to diagnose the failure when it happens in the
9525 // TryListInitialization call instead of delaying the diagnosis, which is
9526 // beneficial because the flattening is also expensive.
9527 break;
9528 }
9529
9530 case FK_ExplicitConstructor: {
9531 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_selected_explicit_constructor)
9532 << Args[0]->getSourceRange();
9533 OverloadCandidateSet::iterator Best;
9534 OverloadingResult Ovl
9535 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9536 (void)Ovl;
9537 assert(Ovl == OR_Success && "Inconsistent overload resolution");
9538 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
9539 S.Diag(Loc: CtorDecl->getLocation(),
9540 DiagID: diag::note_explicit_ctor_deduction_guide_here) << false;
9541 break;
9542 }
9543
9544 case FK_ParenthesizedListInitFailed:
9545 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
9546 /*VerifyOnly=*/false);
9547 break;
9548
9549 case FK_DesignatedInitForNonAggregate:
9550 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9551 S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_designated_init_for_non_aggregate)
9552 << Entity.getType() << InitList->getSourceRange();
9553 break;
9554 }
9555
9556 PrintInitLocationNote(S, Entity);
9557 return true;
9558}
9559
9560void InitializationSequence::dump(raw_ostream &OS) const {
9561 switch (SequenceKind) {
9562 case FailedSequence: {
9563 OS << "Failed sequence: ";
9564 switch (Failure) {
9565 case FK_TooManyInitsForReference:
9566 OS << "too many initializers for reference";
9567 break;
9568
9569 case FK_ParenthesizedListInitForReference:
9570 OS << "parenthesized list init for reference";
9571 break;
9572
9573 case FK_ArrayNeedsInitList:
9574 OS << "array requires initializer list";
9575 break;
9576
9577 case FK_AddressOfUnaddressableFunction:
9578 OS << "address of unaddressable function was taken";
9579 break;
9580
9581 case FK_ArrayNeedsInitListOrStringLiteral:
9582 OS << "array requires initializer list or string literal";
9583 break;
9584
9585 case FK_ArrayNeedsInitListOrWideStringLiteral:
9586 OS << "array requires initializer list or wide string literal";
9587 break;
9588
9589 case FK_NarrowStringIntoWideCharArray:
9590 OS << "narrow string into wide char array";
9591 break;
9592
9593 case FK_WideStringIntoCharArray:
9594 OS << "wide string into char array";
9595 break;
9596
9597 case FK_IncompatWideStringIntoWideChar:
9598 OS << "incompatible wide string into wide char array";
9599 break;
9600
9601 case FK_PlainStringIntoUTF8Char:
9602 OS << "plain string literal into char8_t array";
9603 break;
9604
9605 case FK_UTF8StringIntoPlainChar:
9606 OS << "u8 string literal into char array";
9607 break;
9608
9609 case FK_ArrayTypeMismatch:
9610 OS << "array type mismatch";
9611 break;
9612
9613 case FK_NonConstantArrayInit:
9614 OS << "non-constant array initializer";
9615 break;
9616
9617 case FK_AddressOfOverloadFailed:
9618 OS << "address of overloaded function failed";
9619 break;
9620
9621 case FK_ReferenceInitOverloadFailed:
9622 OS << "overload resolution for reference initialization failed";
9623 break;
9624
9625 case FK_NonConstLValueReferenceBindingToTemporary:
9626 OS << "non-const lvalue reference bound to temporary";
9627 break;
9628
9629 case FK_NonConstLValueReferenceBindingToBitfield:
9630 OS << "non-const lvalue reference bound to bit-field";
9631 break;
9632
9633 case FK_NonConstLValueReferenceBindingToVectorElement:
9634 OS << "non-const lvalue reference bound to vector element";
9635 break;
9636
9637 case FK_NonConstLValueReferenceBindingToMatrixElement:
9638 OS << "non-const lvalue reference bound to matrix element";
9639 break;
9640
9641 case FK_NonConstLValueReferenceBindingToUnrelated:
9642 OS << "non-const lvalue reference bound to unrelated type";
9643 break;
9644
9645 case FK_RValueReferenceBindingToLValue:
9646 OS << "rvalue reference bound to an lvalue";
9647 break;
9648
9649 case FK_ReferenceInitDropsQualifiers:
9650 OS << "reference initialization drops qualifiers";
9651 break;
9652
9653 case FK_ReferenceAddrspaceMismatchTemporary:
9654 OS << "reference with mismatching address space bound to temporary";
9655 break;
9656
9657 case FK_ReferenceInitFailed:
9658 OS << "reference initialization failed";
9659 break;
9660
9661 case FK_ConversionFailed:
9662 OS << "conversion failed";
9663 break;
9664
9665 case FK_ConversionFromPropertyFailed:
9666 OS << "conversion from property failed";
9667 break;
9668
9669 case FK_TooManyInitsForScalar:
9670 OS << "too many initializers for scalar";
9671 break;
9672
9673 case FK_ParenthesizedListInitForScalar:
9674 OS << "parenthesized list init for reference";
9675 break;
9676
9677 case FK_ReferenceBindingToInitList:
9678 OS << "referencing binding to initializer list";
9679 break;
9680
9681 case FK_InitListBadDestinationType:
9682 OS << "initializer list for non-aggregate, non-scalar type";
9683 break;
9684
9685 case FK_UserConversionOverloadFailed:
9686 OS << "overloading failed for user-defined conversion";
9687 break;
9688
9689 case FK_ConstructorOverloadFailed:
9690 OS << "constructor overloading failed";
9691 break;
9692
9693 case FK_DefaultInitOfConst:
9694 OS << "default initialization of a const variable";
9695 break;
9696
9697 case FK_Incomplete:
9698 OS << "initialization of incomplete type";
9699 break;
9700
9701 case FK_ListInitializationFailed:
9702 OS << "list initialization checker failure";
9703 break;
9704
9705 case FK_VariableLengthArrayHasInitializer:
9706 OS << "variable length array has an initializer";
9707 break;
9708
9709 case FK_PlaceholderType:
9710 OS << "initializer expression isn't contextually valid";
9711 break;
9712
9713 case FK_ListConstructorOverloadFailed:
9714 OS << "list constructor overloading failed";
9715 break;
9716
9717 case FK_ExplicitConstructor:
9718 OS << "list copy initialization chose explicit constructor";
9719 break;
9720
9721 case FK_ParenthesizedListInitFailed:
9722 OS << "parenthesized list initialization failed";
9723 break;
9724
9725 case FK_DesignatedInitForNonAggregate:
9726 OS << "designated initializer for non-aggregate type";
9727 break;
9728
9729 case FK_HLSLInitListFlatteningFailed:
9730 OS << "HLSL initialization list flattening failed";
9731 break;
9732 }
9733 OS << '\n';
9734 return;
9735 }
9736
9737 case DependentSequence:
9738 OS << "Dependent sequence\n";
9739 return;
9740
9741 case NormalSequence:
9742 OS << "Normal sequence: ";
9743 break;
9744 }
9745
9746 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
9747 if (S != step_begin()) {
9748 OS << " -> ";
9749 }
9750
9751 switch (S->Kind) {
9752 case SK_ResolveAddressOfOverloadedFunction:
9753 OS << "resolve address of overloaded function";
9754 break;
9755
9756 case SK_CastDerivedToBasePRValue:
9757 OS << "derived-to-base (prvalue)";
9758 break;
9759
9760 case SK_CastDerivedToBaseXValue:
9761 OS << "derived-to-base (xvalue)";
9762 break;
9763
9764 case SK_CastDerivedToBaseLValue:
9765 OS << "derived-to-base (lvalue)";
9766 break;
9767
9768 case SK_BindReference:
9769 OS << "bind reference to lvalue";
9770 break;
9771
9772 case SK_BindReferenceToTemporary:
9773 OS << "bind reference to a temporary";
9774 break;
9775
9776 case SK_FinalCopy:
9777 OS << "final copy in class direct-initialization";
9778 break;
9779
9780 case SK_ExtraneousCopyToTemporary:
9781 OS << "extraneous C++03 copy to temporary";
9782 break;
9783
9784 case SK_UserConversion:
9785 OS << "user-defined conversion via " << *S->Function.Function;
9786 break;
9787
9788 case SK_QualificationConversionPRValue:
9789 OS << "qualification conversion (prvalue)";
9790 break;
9791
9792 case SK_QualificationConversionXValue:
9793 OS << "qualification conversion (xvalue)";
9794 break;
9795
9796 case SK_QualificationConversionLValue:
9797 OS << "qualification conversion (lvalue)";
9798 break;
9799
9800 case SK_FunctionReferenceConversion:
9801 OS << "function reference conversion";
9802 break;
9803
9804 case SK_AtomicConversion:
9805 OS << "non-atomic-to-atomic conversion";
9806 break;
9807
9808 case SK_ConversionSequence:
9809 OS << "implicit conversion sequence (";
9810 S->ICS->dump(); // FIXME: use OS
9811 OS << ")";
9812 break;
9813
9814 case SK_ConversionSequenceNoNarrowing:
9815 OS << "implicit conversion sequence with narrowing prohibited (";
9816 S->ICS->dump(); // FIXME: use OS
9817 OS << ")";
9818 break;
9819
9820 case SK_ListInitialization:
9821 OS << "list aggregate initialization";
9822 break;
9823
9824 case SK_UnwrapInitList:
9825 OS << "unwrap reference initializer list";
9826 break;
9827
9828 case SK_RewrapInitList:
9829 OS << "rewrap reference initializer list";
9830 break;
9831
9832 case SK_ConstructorInitialization:
9833 OS << "constructor initialization";
9834 break;
9835
9836 case SK_ConstructorInitializationFromList:
9837 OS << "list initialization via constructor";
9838 break;
9839
9840 case SK_ZeroInitialization:
9841 OS << "zero initialization";
9842 break;
9843
9844 case SK_CAssignment:
9845 OS << "C assignment";
9846 break;
9847
9848 case SK_StringInit:
9849 OS << "string initialization";
9850 break;
9851
9852 case SK_ObjCObjectConversion:
9853 OS << "Objective-C object conversion";
9854 break;
9855
9856 case SK_ArrayLoopIndex:
9857 OS << "indexing for array initialization loop";
9858 break;
9859
9860 case SK_ArrayLoopInit:
9861 OS << "array initialization loop";
9862 break;
9863
9864 case SK_ArrayInit:
9865 OS << "array initialization";
9866 break;
9867
9868 case SK_GNUArrayInit:
9869 OS << "array initialization (GNU extension)";
9870 break;
9871
9872 case SK_ParenthesizedArrayInit:
9873 OS << "parenthesized array initialization";
9874 break;
9875
9876 case SK_PassByIndirectCopyRestore:
9877 OS << "pass by indirect copy and restore";
9878 break;
9879
9880 case SK_PassByIndirectRestore:
9881 OS << "pass by indirect restore";
9882 break;
9883
9884 case SK_ProduceObjCObject:
9885 OS << "Objective-C object retension";
9886 break;
9887
9888 case SK_StdInitializerList:
9889 OS << "std::initializer_list from initializer list";
9890 break;
9891
9892 case SK_StdInitializerListConstructorCall:
9893 OS << "list initialization from std::initializer_list";
9894 break;
9895
9896 case SK_OCLSamplerInit:
9897 OS << "OpenCL sampler_t from integer constant";
9898 break;
9899
9900 case SK_OCLZeroOpaqueType:
9901 OS << "OpenCL opaque type from zero";
9902 break;
9903
9904 case SK_ParenthesizedListInit:
9905 OS << "initialization from a parenthesized list of values";
9906 break;
9907
9908 case SK_HLSLBufferConversion:
9909 OS << "HLSL buffer conversion";
9910 break;
9911 }
9912
9913 OS << " [" << S->Type << ']';
9914 }
9915
9916 OS << '\n';
9917}
9918
9919void InitializationSequence::dump() const {
9920 dump(OS&: llvm::errs());
9921}
9922
9923static void DiagnoseNarrowingInInitList(Sema &S,
9924 const ImplicitConversionSequence &ICS,
9925 QualType PreNarrowingType,
9926 QualType EntityType,
9927 const Expr *PostInit) {
9928 const StandardConversionSequence *SCS = nullptr;
9929 switch (ICS.getKind()) {
9930 case ImplicitConversionSequence::StandardConversion:
9931 SCS = &ICS.Standard;
9932 break;
9933 case ImplicitConversionSequence::UserDefinedConversion:
9934 SCS = &ICS.UserDefined.After;
9935 break;
9936 case ImplicitConversionSequence::AmbiguousConversion:
9937 case ImplicitConversionSequence::StaticObjectArgumentConversion:
9938 case ImplicitConversionSequence::EllipsisConversion:
9939 case ImplicitConversionSequence::BadConversion:
9940 return;
9941 }
9942
9943 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
9944 unsigned ConstRefDiagID, unsigned WarnDiagID) {
9945 unsigned DiagID;
9946 auto &L = S.getLangOpts();
9947 if (L.CPlusPlus11 && !L.HLSL &&
9948 (!L.MicrosoftExt || L.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)))
9949 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
9950 else
9951 DiagID = WarnDiagID;
9952 return S.Diag(Loc: PostInit->getBeginLoc(), DiagID)
9953 << PostInit->getSourceRange();
9954 };
9955
9956 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
9957 APValue ConstantValue;
9958 QualType ConstantType;
9959 switch (SCS->getNarrowingKind(Context&: S.Context, Converted: PostInit, ConstantValue,
9960 ConstantType)) {
9961 case NK_Not_Narrowing:
9962 case NK_Dependent_Narrowing:
9963 // No narrowing occurred.
9964 return;
9965
9966 case NK_Type_Narrowing: {
9967 // This was a floating-to-integer conversion, which is always considered a
9968 // narrowing conversion even if the value is a constant and can be
9969 // represented exactly as an integer.
9970 QualType T = EntityType.getNonReferenceType();
9971 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
9972 diag::ext_init_list_type_narrowing_const_reference,
9973 diag::warn_init_list_type_narrowing)
9974 << PreNarrowingType.getLocalUnqualifiedType()
9975 << T.getLocalUnqualifiedType();
9976 break;
9977 }
9978
9979 case NK_Constant_Narrowing: {
9980 // A constant value was narrowed.
9981 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9982 diag::ext_init_list_constant_narrowing,
9983 diag::ext_init_list_constant_narrowing_const_reference,
9984 diag::warn_init_list_constant_narrowing)
9985 << ConstantValue.getAsString(Ctx: S.getASTContext(), Ty: ConstantType)
9986 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
9987 break;
9988 }
9989
9990 case NK_Variable_Narrowing: {
9991 // A variable's value may have been narrowed.
9992 MakeDiag(EntityType.getNonReferenceType() != EntityType,
9993 diag::ext_init_list_variable_narrowing,
9994 diag::ext_init_list_variable_narrowing_const_reference,
9995 diag::warn_init_list_variable_narrowing)
9996 << PreNarrowingType.getLocalUnqualifiedType()
9997 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
9998 break;
9999 }
10000 }
10001
10002 SmallString<128> StaticCast;
10003 llvm::raw_svector_ostream OS(StaticCast);
10004 OS << "static_cast<";
10005 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10006 // It's important to use the typedef's name if there is one so that the
10007 // fixit doesn't break code using types like int64_t.
10008 //
10009 // FIXME: This will break if the typedef requires qualification. But
10010 // getQualifiedNameAsString() includes non-machine-parsable components.
10011 OS << *TT->getDecl();
10012 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10013 OS << BT->getName(Policy: S.getLangOpts());
10014 else {
10015 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10016 // with a broken cast.
10017 return;
10018 }
10019 OS << ">(";
10020 S.Diag(Loc: PostInit->getBeginLoc(), DiagID: diag::note_init_list_narrowing_silence)
10021 << PostInit->getSourceRange()
10022 << FixItHint::CreateInsertion(InsertionLoc: PostInit->getBeginLoc(), Code: OS.str())
10023 << FixItHint::CreateInsertion(
10024 InsertionLoc: S.getLocForEndOfToken(Loc: PostInit->getEndLoc()), Code: ")");
10025}
10026
10027static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
10028 QualType ToType, Expr *Init) {
10029 assert(S.getLangOpts().C23);
10030 ImplicitConversionSequence ICS = S.TryImplicitConversion(
10031 From: Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10032 AllowExplicit: Sema::AllowedExplicit::None,
10033 /*InOverloadResolution*/ false,
10034 /*CStyle*/ false,
10035 /*AllowObjCWritebackConversion=*/false);
10036
10037 if (!ICS.isStandard())
10038 return;
10039
10040 APValue Value;
10041 QualType PreNarrowingType;
10042 // Reuse C++ narrowing check.
10043 switch (ICS.Standard.getNarrowingKind(
10044 Context&: S.Context, Converted: Init, ConstantValue&: Value, ConstantType&: PreNarrowingType,
10045 /*IgnoreFloatToIntegralConversion*/ false)) {
10046 // The value doesn't fit.
10047 case NK_Constant_Narrowing:
10048 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_not_representable)
10049 << Value.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType;
10050 return;
10051
10052 // Conversion to a narrower type.
10053 case NK_Type_Narrowing:
10054 S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_type_mismatch)
10055 << ToType << FromType;
10056 return;
10057
10058 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10059 // not really interested in these cases.
10060 case NK_Dependent_Narrowing:
10061 case NK_Variable_Narrowing:
10062 case NK_Not_Narrowing:
10063 return;
10064 }
10065 llvm_unreachable("unhandled case in switch");
10066}
10067
10068static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
10069 Sema &SemaRef, QualType &TT) {
10070 assert(SemaRef.getLangOpts().C23);
10071 // character that string literal contains fits into TT - target type.
10072 const ArrayType *AT = SemaRef.Context.getAsArrayType(T: TT);
10073 QualType CharType = AT->getElementType();
10074 uint32_t BitWidth = SemaRef.Context.getTypeSize(T: CharType);
10075 bool isUnsigned = CharType->isUnsignedIntegerType();
10076 llvm::APSInt Value(BitWidth, isUnsigned);
10077 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10078 int64_t C = SE->getCodeUnitS(I, BitWidth: SemaRef.Context.getCharWidth());
10079 Value = C;
10080 if (Value != C) {
10081 SemaRef.Diag(Loc: SemaRef.getLocationOfStringLiteralByte(SL: SE, ByteNo: I),
10082 DiagID: diag::err_c23_constexpr_init_not_representable)
10083 << C << CharType;
10084 return;
10085 }
10086 }
10087}
10088
10089//===----------------------------------------------------------------------===//
10090// Initialization helper functions
10091//===----------------------------------------------------------------------===//
10092bool
10093Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10094 ExprResult Init) {
10095 if (Init.isInvalid())
10096 return false;
10097
10098 Expr *InitE = Init.get();
10099 assert(InitE && "No initialization expression");
10100
10101 InitializationKind Kind =
10102 InitializationKind::CreateCopy(InitLoc: InitE->getBeginLoc(), EqualLoc: SourceLocation());
10103 InitializationSequence Seq(*this, Entity, Kind, InitE);
10104 return !Seq.Failed();
10105}
10106
10107ExprResult
10108Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10109 SourceLocation EqualLoc,
10110 ExprResult Init,
10111 bool TopLevelOfInitList,
10112 bool AllowExplicit) {
10113 if (Init.isInvalid())
10114 return ExprError();
10115
10116 Expr *InitE = Init.get();
10117 assert(InitE && "No initialization expression?");
10118
10119 if (EqualLoc.isInvalid())
10120 EqualLoc = InitE->getBeginLoc();
10121
10122 if (Entity.getType().getDesugaredType(Context) ==
10123 Context.AMDGPUFeaturePredicateTy &&
10124 Entity.getDecl()) {
10125 Diag(Loc: EqualLoc, DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
10126 << Entity.getDecl();
10127 return ExprError();
10128 }
10129
10130 InitializationKind Kind = InitializationKind::CreateCopy(
10131 InitLoc: InitE->getBeginLoc(), EqualLoc, AllowExplicitConvs: AllowExplicit);
10132 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10133
10134 // Prevent infinite recursion when performing parameter copy-initialization.
10135 const bool ShouldTrackCopy =
10136 Entity.isParameterKind() && Seq.isConstructorInitialization();
10137 if (ShouldTrackCopy) {
10138 if (llvm::is_contained(Range&: CurrentParameterCopyTypes, Element: Entity.getType())) {
10139 Seq.SetOverloadFailure(
10140 Failure: InitializationSequence::FK_ConstructorOverloadFailed,
10141 Result: OR_No_Viable_Function);
10142
10143 // Try to give a meaningful diagnostic note for the problematic
10144 // constructor.
10145 const auto LastStep = Seq.step_end() - 1;
10146 assert(LastStep->Kind ==
10147 InitializationSequence::SK_ConstructorInitialization);
10148 const FunctionDecl *Function = LastStep->Function.Function;
10149 auto Candidate =
10150 llvm::find_if(Range&: Seq.getFailedCandidateSet(),
10151 P: [Function](const OverloadCandidate &Candidate) -> bool {
10152 return Candidate.Viable &&
10153 Candidate.Function == Function &&
10154 Candidate.Conversions.size() > 0;
10155 });
10156 if (Candidate != Seq.getFailedCandidateSet().end() &&
10157 Function->getNumParams() > 0) {
10158 Candidate->Viable = false;
10159 Candidate->FailureKind = ovl_fail_bad_conversion;
10160 Candidate->Conversions[0].setBad(Failure: BadConversionSequence::no_conversion,
10161 FromExpr: InitE,
10162 ToType: Function->getParamDecl(i: 0)->getType());
10163 }
10164 }
10165 CurrentParameterCopyTypes.push_back(Elt: Entity.getType());
10166 }
10167
10168 ExprResult Result = Seq.Perform(S&: *this, Entity, Kind, Args: InitE);
10169
10170 if (ShouldTrackCopy)
10171 CurrentParameterCopyTypes.pop_back();
10172
10173 return Result;
10174}
10175
10176/// Determine whether RD is, or is derived from, a specialization of CTD.
10177static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10178 ClassTemplateDecl *CTD) {
10179 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10180 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Candidate);
10181 return !CTSD || !declaresSameEntity(D1: CTSD->getSpecializedTemplate(), D2: CTD);
10182 };
10183 return !(NotSpecialization(RD) && RD->forallBases(BaseMatches: NotSpecialization));
10184}
10185
10186QualType Sema::DeduceTemplateSpecializationFromInitializer(
10187 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10188 const InitializationKind &Kind, MultiExprArg Inits) {
10189 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10190 Val: TSInfo->getType()->getContainedDeducedType());
10191 assert(DeducedTST && "not a deduced template specialization type");
10192
10193 auto TemplateName = DeducedTST->getTemplateName();
10194 if (TemplateName.isDependent())
10195 return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType();
10196
10197 // We can only perform deduction for class templates or alias templates.
10198 auto *Template =
10199 dyn_cast_or_null<ClassTemplateDecl>(Val: TemplateName.getAsTemplateDecl());
10200 TemplateDecl *LookupTemplateDecl = Template;
10201 if (!Template) {
10202 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10203 Val: TemplateName.getAsTemplateDecl())) {
10204 DiagCompat(Loc: Kind.getLocation(), CompatDiagId: diag_compat::ctad_for_alias_templates);
10205 LookupTemplateDecl = AliasTemplate;
10206 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10207 ->getUnderlyingType()
10208 .getCanonicalType();
10209 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10210 // of the form
10211 // [typename] [nested-name-specifier] [template] simple-template-id
10212 if (const auto *TST =
10213 UnderlyingType->getAs<TemplateSpecializationType>()) {
10214 Template = dyn_cast_or_null<ClassTemplateDecl>(
10215 Val: TST->getTemplateName().getAsTemplateDecl());
10216 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10217 // Cases where template arguments in the RHS of the alias are not
10218 // dependent. e.g.
10219 // using AliasFoo = Foo<bool>;
10220 if (const auto *CTSD =
10221 llvm::dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl()))
10222 Template = CTSD->getSpecializedTemplate();
10223 }
10224 }
10225 }
10226 if (!Template) {
10227 Diag(Loc: Kind.getLocation(),
10228 DiagID: diag::err_deduced_non_class_or_alias_template_specialization_type)
10229 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName) << TemplateName;
10230 if (auto *TD = TemplateName.getAsTemplateDecl())
10231 NoteTemplateLocation(Decl: *TD);
10232 return QualType();
10233 }
10234
10235 // Can't deduce from dependent arguments.
10236 if (Expr::hasAnyTypeDependentArguments(Exprs: Inits)) {
10237 Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(),
10238 DiagID: diag::warn_cxx14_compat_class_template_argument_deduction)
10239 << TSInfo->getTypeLoc().getSourceRange() << 0;
10240 return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType();
10241 }
10242
10243 // FIXME: Perform "exact type" matching first, per CWG discussion?
10244 // Or implement this via an implied 'T(T) -> T' deduction guide?
10245
10246 // Look up deduction guides, including those synthesized from constructors.
10247 //
10248 // C++1z [over.match.class.deduct]p1:
10249 // A set of functions and function templates is formed comprising:
10250 // - For each constructor of the class template designated by the
10251 // template-name, a function template [...]
10252 // - For each deduction-guide, a function or function template [...]
10253 DeclarationNameInfo NameInfo(
10254 Context.DeclarationNames.getCXXDeductionGuideName(TD: LookupTemplateDecl),
10255 TSInfo->getTypeLoc().getEndLoc());
10256 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10257 LookupQualifiedName(R&: Guides, LookupCtx: LookupTemplateDecl->getDeclContext());
10258
10259 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10260 // clear on this, but they're not found by name so access does not apply.
10261 Guides.suppressDiagnostics();
10262
10263 // Figure out if this is list-initialization.
10264 InitListExpr *ListInit =
10265 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10266 ? dyn_cast<InitListExpr>(Val: Inits[0])
10267 : nullptr;
10268
10269 // C++1z [over.match.class.deduct]p1:
10270 // Initialization and overload resolution are performed as described in
10271 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10272 // (as appropriate for the type of initialization performed) for an object
10273 // of a hypothetical class type, where the selected functions and function
10274 // templates are considered to be the constructors of that class type
10275 //
10276 // Since we know we're initializing a class type of a type unrelated to that
10277 // of the initializer, this reduces to something fairly reasonable.
10278 OverloadCandidateSet Candidates(Kind.getLocation(),
10279 OverloadCandidateSet::CSK_Normal);
10280 OverloadCandidateSet::iterator Best;
10281
10282 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10283
10284 // Return true if the candidate is added successfully, false otherwise.
10285 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10286 CXXDeductionGuideDecl *GD,
10287 DeclAccessPair FoundDecl,
10288 bool OnlyListConstructors,
10289 bool AllowAggregateDeductionCandidate) {
10290 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10291 // For copy-initialization, the candidate functions are all the
10292 // converting constructors (12.3.1) of that class.
10293 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10294 // The converting constructors of T are candidate functions.
10295 if (!AllowExplicit) {
10296 // Overload resolution checks whether the deduction guide is declared
10297 // explicit for us.
10298
10299 // When looking for a converting constructor, deduction guides that
10300 // could never be called with one argument are not interesting to
10301 // check or note.
10302 if (GD->getMinRequiredArguments() > 1 ||
10303 (GD->getNumParams() == 0 && !GD->isVariadic()))
10304 return;
10305 }
10306
10307 // C++ [over.match.list]p1.1: (first phase list initialization)
10308 // Initially, the candidate functions are the initializer-list
10309 // constructors of the class T
10310 if (OnlyListConstructors && !isInitListConstructor(Ctor: GD))
10311 return;
10312
10313 if (!AllowAggregateDeductionCandidate &&
10314 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10315 return;
10316
10317 // C++ [over.match.list]p1.2: (second phase list initialization)
10318 // the candidate functions are all the constructors of the class T
10319 // C++ [over.match.ctor]p1: (all other cases)
10320 // the candidate functions are all the constructors of the class of
10321 // the object being initialized
10322
10323 // C++ [over.best.ics]p4:
10324 // When [...] the constructor [...] is a candidate by
10325 // - [over.match.copy] (in all cases)
10326 if (TD) {
10327
10328 // As template candidates are not deduced immediately,
10329 // persist the array in the overload set.
10330 MutableArrayRef<Expr *> TmpInits =
10331 Candidates.getPersistentArgsArray(N: Inits.size());
10332
10333 for (auto [I, E] : llvm::enumerate(First&: Inits)) {
10334 if (auto *DI = dyn_cast<DesignatedInitExpr>(Val: E))
10335 TmpInits[I] = DI->getInit();
10336 else
10337 TmpInits[I] = E;
10338 }
10339
10340 AddTemplateOverloadCandidate(
10341 FunctionTemplate: TD, FoundDecl, /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, Args: TmpInits, CandidateSet&: Candidates,
10342 /*SuppressUserConversions=*/false,
10343 /*PartialOverloading=*/false, AllowExplicit, IsADLCandidate: ADLCallKind::NotADL,
10344 /*PO=*/{}, AggregateCandidateDeduction: AllowAggregateDeductionCandidate);
10345 } else {
10346 AddOverloadCandidate(Function: GD, FoundDecl, Args: Inits, CandidateSet&: Candidates,
10347 /*SuppressUserConversions=*/false,
10348 /*PartialOverloading=*/false, AllowExplicit);
10349 }
10350 };
10351
10352 bool FoundDeductionGuide = false;
10353
10354 auto TryToResolveOverload =
10355 [&](bool OnlyListConstructors) -> OverloadingResult {
10356 Candidates.clear(CSK: OverloadCandidateSet::CSK_Normal);
10357 bool HasAnyDeductionGuide = false;
10358
10359 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10360 auto *Pattern = Template;
10361 while (Pattern->getInstantiatedFromMemberTemplate()) {
10362 if (Pattern->isMemberSpecialization())
10363 break;
10364 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10365 }
10366
10367 auto *RD = cast<CXXRecordDecl>(Val: Pattern->getTemplatedDecl());
10368 if (!(RD->getDefinition() && RD->isAggregate()))
10369 return;
10370 QualType Ty = Context.getCanonicalTagType(TD: RD);
10371 SmallVector<QualType, 8> ElementTypes;
10372
10373 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10374 if (!CheckInitList.HadError()) {
10375 // C++ [over.match.class.deduct]p1.8:
10376 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10377 // rvalue reference to the declared type of e_i and
10378 // C++ [over.match.class.deduct]p1.9:
10379 // if e_i is of array type and x_i is a string-literal, T_i is an
10380 // lvalue reference to the const-qualified declared type of e_i and
10381 // C++ [over.match.class.deduct]p1.10:
10382 // otherwise, T_i is the declared type of e_i
10383 for (int I = 0, E = ListInit->getNumInits();
10384 I < E && !isa<PackExpansionType>(Val: ElementTypes[I]); ++I)
10385 if (ElementTypes[I]->isArrayType()) {
10386 if (isa<InitListExpr, DesignatedInitExpr>(Val: ListInit->getInit(Init: I)))
10387 ElementTypes[I] = Context.getRValueReferenceType(T: ElementTypes[I]);
10388 else if (isa<StringLiteral>(
10389 Val: ListInit->getInit(Init: I)->IgnoreParenImpCasts()))
10390 ElementTypes[I] =
10391 Context.getLValueReferenceType(T: ElementTypes[I].withConst());
10392 }
10393
10394 if (CXXDeductionGuideDecl *GD =
10395 DeclareAggregateDeductionGuideFromInitList(
10396 Template: LookupTemplateDecl, ParamTypes: ElementTypes,
10397 Loc: TSInfo->getTypeLoc().getEndLoc())) {
10398 auto *TD = GD->getDescribedFunctionTemplate();
10399 addDeductionCandidate(TD, GD, DeclAccessPair::make(D: TD, AS: AS_public),
10400 OnlyListConstructors,
10401 /*AllowAggregateDeductionCandidate=*/true);
10402 HasAnyDeductionGuide = true;
10403 }
10404 }
10405 };
10406
10407 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10408 NamedDecl *D = (*I)->getUnderlyingDecl();
10409 if (D->isInvalidDecl())
10410 continue;
10411
10412 auto *TD = dyn_cast<FunctionTemplateDecl>(Val: D);
10413 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10414 Val: TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(Val: D));
10415 if (!GD)
10416 continue;
10417
10418 if (!GD->isImplicit())
10419 HasAnyDeductionGuide = true;
10420
10421 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10422 /*AllowAggregateDeductionCandidate=*/false);
10423 }
10424
10425 // C++ [over.match.class.deduct]p1.4:
10426 // if C is defined and its definition satisfies the conditions for an
10427 // aggregate class ([dcl.init.aggr]) with the assumption that any
10428 // dependent base class has no virtual functions and no virtual base
10429 // classes, and the initializer is a non-empty braced-init-list or
10430 // parenthesized expression-list, and there are no deduction-guides for
10431 // C, the set contains an additional function template, called the
10432 // aggregate deduction candidate, defined as follows.
10433 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10434 if (ListInit && ListInit->getNumInits()) {
10435 SynthesizeAggrGuide(ListInit);
10436 } else if (Inits.size()) { // parenthesized expression-list
10437 // Inits are expressions inside the parentheses. We don't have
10438 // the parentheses source locations, use the begin/end of Inits as the
10439 // best heuristic.
10440 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10441 Inits, Inits.back()->getEndLoc(),
10442 /*isExplicit=*/false);
10443 SynthesizeAggrGuide(&TempListInit);
10444 }
10445 }
10446
10447 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10448
10449 return Candidates.BestViableFunction(S&: *this, Loc: Kind.getLocation(), Best);
10450 };
10451
10452 OverloadingResult Result = OR_No_Viable_Function;
10453
10454 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10455 // try initializer-list constructors.
10456 if (ListInit) {
10457 bool TryListConstructors = true;
10458
10459 // Try list constructors unless the list is empty and the class has one or
10460 // more default constructors, in which case those constructors win.
10461 if (!ListInit->getNumInits()) {
10462 for (NamedDecl *D : Guides) {
10463 auto *FD = dyn_cast<FunctionDecl>(Val: D->getUnderlyingDecl());
10464 if (FD && FD->getMinRequiredArguments() == 0) {
10465 TryListConstructors = false;
10466 break;
10467 }
10468 }
10469 } else if (ListInit->getNumInits() == 1) {
10470 // C++ [over.match.class.deduct]:
10471 // As an exception, the first phase in [over.match.list] (considering
10472 // initializer-list constructors) is omitted if the initializer list
10473 // consists of a single expression of type cv U, where U is a
10474 // specialization of C or a class derived from a specialization of C.
10475 Expr *E = ListInit->getInit(Init: 0);
10476 auto *RD = E->getType()->getAsCXXRecordDecl();
10477 if (!isa<InitListExpr>(Val: E) && RD &&
10478 isCompleteType(Loc: Kind.getLocation(), T: E->getType()) &&
10479 isOrIsDerivedFromSpecializationOf(RD, CTD: Template))
10480 TryListConstructors = false;
10481 }
10482
10483 if (TryListConstructors)
10484 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10485 // Then unwrap the initializer list and try again considering all
10486 // constructors.
10487 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10488 }
10489
10490 // If list-initialization fails, or if we're doing any other kind of
10491 // initialization, we (eventually) consider constructors.
10492 if (Result == OR_No_Viable_Function)
10493 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10494
10495 switch (Result) {
10496 case OR_Ambiguous:
10497 // FIXME: For list-initialization candidates, it'd usually be better to
10498 // list why they were not viable when given the initializer list itself as
10499 // an argument.
10500 Candidates.NoteCandidates(
10501 PA: PartialDiagnosticAt(
10502 Kind.getLocation(),
10503 PDiag(DiagID: diag::err_deduced_class_template_ctor_ambiguous)
10504 << TemplateName),
10505 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Inits);
10506 return QualType();
10507
10508 case OR_No_Viable_Function: {
10509 CXXRecordDecl *Primary =
10510 cast<ClassTemplateDecl>(Val: Template)->getTemplatedDecl();
10511 bool Complete = isCompleteType(Loc: Kind.getLocation(),
10512 T: Context.getCanonicalTagType(TD: Primary));
10513 Candidates.NoteCandidates(
10514 PA: PartialDiagnosticAt(
10515 Kind.getLocation(),
10516 PDiag(DiagID: Complete ? diag::err_deduced_class_template_ctor_no_viable
10517 : diag::err_deduced_class_template_incomplete)
10518 << TemplateName << !Guides.empty()),
10519 S&: *this, OCD: OCD_AllCandidates, Args: Inits);
10520 return QualType();
10521 }
10522
10523 case OR_Deleted: {
10524 // FIXME: There are no tests for this diagnostic, and it doesn't seem
10525 // like we ever get here; attempts to trigger this seem to yield a
10526 // generic c'all to deleted function' diagnostic instead.
10527 Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_deleted)
10528 << TemplateName;
10529 NoteDeletedFunction(FD: Best->Function);
10530 return QualType();
10531 }
10532
10533 case OR_Success:
10534 // C++ [over.match.list]p1:
10535 // In copy-list-initialization, if an explicit constructor is chosen, the
10536 // initialization is ill-formed.
10537 if (Kind.isCopyInit() && ListInit &&
10538 cast<CXXDeductionGuideDecl>(Val: Best->Function)->isExplicit()) {
10539 bool IsDeductionGuide = !Best->Function->isImplicit();
10540 Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_explicit)
10541 << TemplateName << IsDeductionGuide;
10542 Diag(Loc: Best->Function->getLocation(),
10543 DiagID: diag::note_explicit_ctor_deduction_guide_here)
10544 << IsDeductionGuide;
10545 return QualType();
10546 }
10547
10548 // Make sure we didn't select an unusable deduction guide, and mark it
10549 // as referenced.
10550 DiagnoseUseOfDecl(D: Best->Function, Locs: Kind.getLocation());
10551 MarkFunctionReferenced(Loc: Kind.getLocation(), Func: Best->Function);
10552 break;
10553 }
10554
10555 // C++ [dcl.type.class.deduct]p1:
10556 // The placeholder is replaced by the return type of the function selected
10557 // by overload resolution for class template deduction.
10558 QualType DeducedType =
10559 SubstAutoTypeSourceInfo(TypeWithAuto: TSInfo, Replacement: Best->Function->getReturnType())
10560 ->getType();
10561 Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(),
10562 DiagID: diag::warn_cxx14_compat_class_template_argument_deduction)
10563 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10564
10565 // Warn if CTAD was used on a type that does not have any user-defined
10566 // deduction guides.
10567 if (!FoundDeductionGuide) {
10568 Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(),
10569 DiagID: diag::warn_ctad_maybe_unsupported)
10570 << TemplateName;
10571 Diag(Loc: Template->getLocation(), DiagID: diag::note_suppress_ctad_maybe_unsupported);
10572 }
10573
10574 return DeducedType;
10575}
10576