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

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of clang/lib/Sema/SemaInit.cpp