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