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