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 "clang/AST/ASTContext.h"
14#include "clang/AST/DeclObjC.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/AST/ExprOpenMP.h"
19#include "clang/AST/IgnoreExpr.h"
20#include "clang/AST/TypeLoc.h"
21#include "clang/Basic/CharInfo.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Specifiers.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/Designator.h"
26#include "clang/Sema/EnterExpressionEvaluationContext.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Ownership.h"
30#include "clang/Sema/SemaInternal.h"
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/PointerIntPair.h"
34#include "llvm/ADT/STLForwardCompat.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/SmallVector.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
40
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// Sema Initialization Checking
45//===----------------------------------------------------------------------===//
46
47/// Check whether T is compatible with a wide character type (wchar_t,
48/// char16_t or char32_t).
49static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
50 if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: T))
51 return true;
52 if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
53 return Context.typesAreCompatible(T1: Context.Char16Ty, T2: T) ||
54 Context.typesAreCompatible(T1: Context.Char32Ty, T2: T);
55 }
56 return false;
57}
58
59enum StringInitFailureKind {
60 SIF_None,
61 SIF_NarrowStringIntoWideChar,
62 SIF_WideStringIntoChar,
63 SIF_IncompatWideStringIntoWideChar,
64 SIF_UTF8StringIntoPlainChar,
65 SIF_PlainStringIntoUTF8Char,
66 SIF_Other
67};
68
69/// Check whether the array of type AT can be initialized by the Init
70/// expression by means of string initialization. Returns SIF_None if so,
71/// otherwise returns a StringInitFailureKind that describes why the
72/// initialization would not work.
73static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
74 ASTContext &Context) {
75 if (!isa<ConstantArrayType>(Val: AT) && !isa<IncompleteArrayType>(Val: AT))
76 return SIF_Other;
77
78 // See if this is a string literal or @encode.
79 Init = Init->IgnoreParens();
80
81 // Handle @encode, which is a narrow string.
82 if (isa<ObjCEncodeExpr>(Val: Init) && AT->getElementType()->isCharType())
83 return SIF_None;
84
85 // Otherwise we can only handle string literals.
86 StringLiteral *SL = dyn_cast<StringLiteral>(Val: Init);
87 if (!SL)
88 return SIF_Other;
89
90 const QualType ElemTy =
91 Context.getCanonicalType(T: AT->getElementType()).getUnqualifiedType();
92
93 auto IsCharOrUnsignedChar = [](const QualType &T) {
94 const BuiltinType *BT = dyn_cast<BuiltinType>(Val: T.getTypePtr());
95 return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
96 };
97
98 switch (SL->getKind()) {
99 case StringLiteralKind::UTF8:
100 // char8_t array can be initialized with a UTF-8 string.
101 // - C++20 [dcl.init.string] (DR)
102 // Additionally, an array of char or unsigned char may be initialized
103 // by a UTF-8 string literal.
104 if (ElemTy->isChar8Type() ||
105 (Context.getLangOpts().Char8 &&
106 IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
107 return SIF_None;
108 [[fallthrough]];
109 case StringLiteralKind::Ordinary:
110 // char array can be initialized with a narrow string.
111 // Only allow char x[] = "foo"; not char x[] = L"foo";
112 if (ElemTy->isCharType())
113 return (SL->getKind() == StringLiteralKind::UTF8 &&
114 Context.getLangOpts().Char8)
115 ? SIF_UTF8StringIntoPlainChar
116 : SIF_None;
117 if (ElemTy->isChar8Type())
118 return SIF_PlainStringIntoUTF8Char;
119 if (IsWideCharCompatible(T: ElemTy, Context))
120 return SIF_NarrowStringIntoWideChar;
121 return SIF_Other;
122 // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
123 // "An array with element type compatible with a qualified or unqualified
124 // version of wchar_t, char16_t, or char32_t may be initialized by a wide
125 // string literal with the corresponding encoding prefix (L, u, or U,
126 // respectively), optionally enclosed in braces.
127 case StringLiteralKind::UTF16:
128 if (Context.typesAreCompatible(T1: Context.Char16Ty, T2: ElemTy))
129 return SIF_None;
130 if (ElemTy->isCharType() || ElemTy->isChar8Type())
131 return SIF_WideStringIntoChar;
132 if (IsWideCharCompatible(T: ElemTy, Context))
133 return SIF_IncompatWideStringIntoWideChar;
134 return SIF_Other;
135 case StringLiteralKind::UTF32:
136 if (Context.typesAreCompatible(T1: Context.Char32Ty, T2: ElemTy))
137 return SIF_None;
138 if (ElemTy->isCharType() || ElemTy->isChar8Type())
139 return SIF_WideStringIntoChar;
140 if (IsWideCharCompatible(T: ElemTy, Context))
141 return SIF_IncompatWideStringIntoWideChar;
142 return SIF_Other;
143 case StringLiteralKind::Wide:
144 if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: ElemTy))
145 return SIF_None;
146 if (ElemTy->isCharType() || ElemTy->isChar8Type())
147 return SIF_WideStringIntoChar;
148 if (IsWideCharCompatible(T: ElemTy, Context))
149 return SIF_IncompatWideStringIntoWideChar;
150 return SIF_Other;
151 case StringLiteralKind::Unevaluated:
152 assert(false && "Unevaluated string literal in initialization");
153 break;
154 }
155
156 llvm_unreachable("missed a StringLiteral kind?");
157}
158
159static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
160 ASTContext &Context) {
161 const ArrayType *arrayType = Context.getAsArrayType(T: declType);
162 if (!arrayType)
163 return SIF_Other;
164 return IsStringInit(Init: init, AT: arrayType, Context);
165}
166
167bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
168 return ::IsStringInit(Init, AT, Context) == SIF_None;
169}
170
171/// Update the type of a string literal, including any surrounding parentheses,
172/// to match the type of the object which it is initializing.
173static void updateStringLiteralType(Expr *E, QualType Ty) {
174 while (true) {
175 E->setType(Ty);
176 E->setValueKind(VK_PRValue);
177 if (isa<StringLiteral>(Val: E) || isa<ObjCEncodeExpr>(Val: E))
178 break;
179 E = IgnoreParensSingleStep(E);
180 }
181}
182
183/// Fix a compound literal initializing an array so it's correctly marked
184/// as an rvalue.
185static void updateGNUCompoundLiteralRValue(Expr *E) {
186 while (true) {
187 E->setValueKind(VK_PRValue);
188 if (isa<CompoundLiteralExpr>(Val: E))
189 break;
190 E = IgnoreParensSingleStep(E);
191 }
192}
193
194static bool initializingConstexprVariable(const InitializedEntity &Entity) {
195 Decl *D = Entity.getDecl();
196 const InitializedEntity *Parent = &Entity;
197
198 while (Parent) {
199 D = Parent->getDecl();
200 Parent = Parent->getParent();
201 }
202
203 if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); VD && VD->isConstexpr())
204 return true;
205
206 return false;
207}
208
209static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
210 Sema &SemaRef, QualType &TT);
211
212static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
213 Sema &S, bool CheckC23ConstexprInit = false) {
214 // Get the length of the string as parsed.
215 auto *ConstantArrayTy =
216 cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
217 uint64_t StrLength = ConstantArrayTy->getZExtSize();
218
219 if (CheckC23ConstexprInit)
220 if (const StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens()))
221 CheckC23ConstexprInitStringLiteral(SE: SL, SemaRef&: S, TT&: DeclT);
222
223 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
224 // C99 6.7.8p14. We have an array of character type with unknown size
225 // being initialized to a string literal.
226 llvm::APInt ConstVal(32, StrLength);
227 // Return a new array type (C99 6.7.8p22).
228 DeclT = S.Context.getConstantArrayType(
229 EltTy: IAT->getElementType(), ArySize: ConstVal, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
230 updateStringLiteralType(E: Str, Ty: DeclT);
231 return;
232 }
233
234 const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: AT);
235
236 // We have an array of character type with known size. However,
237 // the size may be smaller or larger than the string we are initializing.
238 // FIXME: Avoid truncation for 64-bit length strings.
239 if (S.getLangOpts().CPlusPlus) {
240 if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) {
241 // For Pascal strings it's OK to strip off the terminating null character,
242 // so the example below is valid:
243 //
244 // unsigned char a[2] = "\pa";
245 if (SL->isPascal())
246 StrLength--;
247 }
248
249 // [dcl.init.string]p2
250 if (StrLength > CAT->getZExtSize())
251 S.Diag(Str->getBeginLoc(),
252 diag::err_initializer_string_for_char_array_too_long)
253 << CAT->getZExtSize() << StrLength << Str->getSourceRange();
254 } else {
255 // C99 6.7.8p14.
256 if (StrLength - 1 > CAT->getZExtSize())
257 S.Diag(Str->getBeginLoc(),
258 diag::ext_initializer_string_for_char_array_too_long)
259 << Str->getSourceRange();
260 }
261
262 // Set the type to the actual size that we are initializing. If we have
263 // something like:
264 // char x[1] = "foo";
265 // then this will set the string literal's type to char[1].
266 updateStringLiteralType(E: Str, Ty: DeclT);
267}
268
269//===----------------------------------------------------------------------===//
270// Semantic checking for initializer lists.
271//===----------------------------------------------------------------------===//
272
273namespace {
274
275/// Semantic checking for initializer lists.
276///
277/// The InitListChecker class contains a set of routines that each
278/// handle the initialization of a certain kind of entity, e.g.,
279/// arrays, vectors, struct/union types, scalars, etc. The
280/// InitListChecker itself performs a recursive walk of the subobject
281/// structure of the type to be initialized, while stepping through
282/// the initializer list one element at a time. The IList and Index
283/// parameters to each of the Check* routines contain the active
284/// (syntactic) initializer list and the index into that initializer
285/// list that represents the current initializer. Each routine is
286/// responsible for moving that Index forward as it consumes elements.
287///
288/// Each Check* routine also has a StructuredList/StructuredIndex
289/// arguments, which contains the current "structured" (semantic)
290/// initializer list and the index into that initializer list where we
291/// are copying initializers as we map them over to the semantic
292/// list. Once we have completed our recursive walk of the subobject
293/// structure, we will have constructed a full semantic initializer
294/// list.
295///
296/// C99 designators cause changes in the initializer list traversal,
297/// because they make the initialization "jump" into a specific
298/// subobject and then continue the initialization from that
299/// point. CheckDesignatedInitializer() recursively steps into the
300/// designated subobject and manages backing out the recursion to
301/// initialize the subobjects after the one designated.
302///
303/// If an initializer list contains any designators, we build a placeholder
304/// structured list even in 'verify only' mode, so that we can track which
305/// elements need 'empty' initializtion.
306class InitListChecker {
307 Sema &SemaRef;
308 bool hadError = false;
309 bool VerifyOnly; // No diagnostics.
310 bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
311 bool InOverloadResolution;
312 InitListExpr *FullyStructuredList = nullptr;
313 NoInitExpr *DummyExpr = nullptr;
314 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
315
316 NoInitExpr *getDummyInit() {
317 if (!DummyExpr)
318 DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
319 return DummyExpr;
320 }
321
322 void CheckImplicitInitList(const InitializedEntity &Entity,
323 InitListExpr *ParentIList, QualType T,
324 unsigned &Index, InitListExpr *StructuredList,
325 unsigned &StructuredIndex);
326 void CheckExplicitInitList(const InitializedEntity &Entity,
327 InitListExpr *IList, QualType &T,
328 InitListExpr *StructuredList,
329 bool TopLevelObject = false);
330 void CheckListElementTypes(const InitializedEntity &Entity,
331 InitListExpr *IList, QualType &DeclType,
332 bool SubobjectIsDesignatorContext,
333 unsigned &Index,
334 InitListExpr *StructuredList,
335 unsigned &StructuredIndex,
336 bool TopLevelObject = false);
337 void CheckSubElementType(const InitializedEntity &Entity,
338 InitListExpr *IList, QualType ElemType,
339 unsigned &Index,
340 InitListExpr *StructuredList,
341 unsigned &StructuredIndex,
342 bool DirectlyDesignated = false);
343 void CheckComplexType(const InitializedEntity &Entity,
344 InitListExpr *IList, QualType DeclType,
345 unsigned &Index,
346 InitListExpr *StructuredList,
347 unsigned &StructuredIndex);
348 void CheckScalarType(const InitializedEntity &Entity,
349 InitListExpr *IList, QualType DeclType,
350 unsigned &Index,
351 InitListExpr *StructuredList,
352 unsigned &StructuredIndex);
353 void CheckReferenceType(const InitializedEntity &Entity,
354 InitListExpr *IList, QualType DeclType,
355 unsigned &Index,
356 InitListExpr *StructuredList,
357 unsigned &StructuredIndex);
358 void CheckVectorType(const InitializedEntity &Entity,
359 InitListExpr *IList, QualType DeclType, unsigned &Index,
360 InitListExpr *StructuredList,
361 unsigned &StructuredIndex);
362 void CheckStructUnionTypes(const InitializedEntity &Entity,
363 InitListExpr *IList, QualType DeclType,
364 CXXRecordDecl::base_class_const_range Bases,
365 RecordDecl::field_iterator Field,
366 bool SubobjectIsDesignatorContext, unsigned &Index,
367 InitListExpr *StructuredList,
368 unsigned &StructuredIndex,
369 bool TopLevelObject = false);
370 void CheckArrayType(const InitializedEntity &Entity,
371 InitListExpr *IList, QualType &DeclType,
372 llvm::APSInt elementIndex,
373 bool SubobjectIsDesignatorContext, unsigned &Index,
374 InitListExpr *StructuredList,
375 unsigned &StructuredIndex);
376 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
377 InitListExpr *IList, DesignatedInitExpr *DIE,
378 unsigned DesigIdx,
379 QualType &CurrentObjectType,
380 RecordDecl::field_iterator *NextField,
381 llvm::APSInt *NextElementIndex,
382 unsigned &Index,
383 InitListExpr *StructuredList,
384 unsigned &StructuredIndex,
385 bool FinishSubobjectInit,
386 bool TopLevelObject);
387 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
388 QualType CurrentObjectType,
389 InitListExpr *StructuredList,
390 unsigned StructuredIndex,
391 SourceRange InitRange,
392 bool IsFullyOverwritten = false);
393 void UpdateStructuredListElement(InitListExpr *StructuredList,
394 unsigned &StructuredIndex,
395 Expr *expr);
396 InitListExpr *createInitListExpr(QualType CurrentObjectType,
397 SourceRange InitRange,
398 unsigned ExpectedNumInits);
399 int numArrayElements(QualType DeclType);
400 int numStructUnionElements(QualType DeclType);
401 static RecordDecl *getRecordDecl(QualType DeclType);
402
403 ExprResult PerformEmptyInit(SourceLocation Loc,
404 const InitializedEntity &Entity);
405
406 /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
407 void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
408 bool UnionOverride = false,
409 bool FullyOverwritten = true) {
410 // Overriding an initializer via a designator is valid with C99 designated
411 // initializers, but ill-formed with C++20 designated initializers.
412 unsigned DiagID =
413 SemaRef.getLangOpts().CPlusPlus
414 ? (UnionOverride ? diag::ext_initializer_union_overrides
415 : diag::ext_initializer_overrides)
416 : diag::warn_initializer_overrides;
417
418 if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
419 // In overload resolution, we have to strictly enforce the rules, and so
420 // don't allow any overriding of prior initializers. This matters for a
421 // case such as:
422 //
423 // union U { int a, b; };
424 // struct S { int a, b; };
425 // void f(U), f(S);
426 //
427 // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
428 // consistency, we disallow all overriding of prior initializers in
429 // overload resolution, not only overriding of union members.
430 hadError = true;
431 } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
432 // If we'll be keeping around the old initializer but overwriting part of
433 // the object it initialized, and that object is not trivially
434 // destructible, this can leak. Don't allow that, not even as an
435 // extension.
436 //
437 // FIXME: It might be reasonable to allow this in cases where the part of
438 // the initializer that we're overriding has trivial destruction.
439 DiagID = diag::err_initializer_overrides_destructed;
440 } else if (!OldInit->getSourceRange().isValid()) {
441 // We need to check on source range validity because the previous
442 // initializer does not have to be an explicit initializer. e.g.,
443 //
444 // struct P { int a, b; };
445 // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
446 //
447 // There is an overwrite taking place because the first braced initializer
448 // list "{ .a = 2 }" already provides value for .p.b (which is zero).
449 //
450 // Such overwrites are harmless, so we don't diagnose them. (Note that in
451 // C++, this cannot be reached unless we've already seen and diagnosed a
452 // different conformance issue, such as a mixture of designated and
453 // non-designated initializers or a multi-level designator.)
454 return;
455 }
456
457 if (!VerifyOnly) {
458 SemaRef.Diag(NewInitRange.getBegin(), DiagID)
459 << NewInitRange << FullyOverwritten << OldInit->getType();
460 SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
461 << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
462 << OldInit->getSourceRange();
463 }
464 }
465
466 // Explanation on the "FillWithNoInit" mode:
467 //
468 // Assume we have the following definitions (Case#1):
469 // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
470 // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
471 //
472 // l.lp.x[1][0..1] should not be filled with implicit initializers because the
473 // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
474 //
475 // But if we have (Case#2):
476 // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
477 //
478 // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
479 // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
480 //
481 // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
482 // in the InitListExpr, the "holes" in Case#1 are filled not with empty
483 // initializers but with special "NoInitExpr" place holders, which tells the
484 // CodeGen not to generate any initializers for these parts.
485 void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
486 const InitializedEntity &ParentEntity,
487 InitListExpr *ILE, bool &RequiresSecondPass,
488 bool FillWithNoInit);
489 void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
490 const InitializedEntity &ParentEntity,
491 InitListExpr *ILE, bool &RequiresSecondPass,
492 bool FillWithNoInit = false);
493 void FillInEmptyInitializations(const InitializedEntity &Entity,
494 InitListExpr *ILE, bool &RequiresSecondPass,
495 InitListExpr *OuterILE, unsigned OuterIndex,
496 bool FillWithNoInit = false);
497 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
498 Expr *InitExpr, FieldDecl *Field,
499 bool TopLevelObject);
500 void CheckEmptyInitializable(const InitializedEntity &Entity,
501 SourceLocation Loc);
502
503public:
504 InitListChecker(
505 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
506 bool VerifyOnly, bool TreatUnavailableAsInvalid,
507 bool InOverloadResolution = false,
508 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
509 InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
510 QualType &T,
511 SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
512 : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
513 /*TreatUnavailableAsInvalid=*/false,
514 /*InOverloadResolution=*/false,
515 &AggrDeductionCandidateParamTypes){};
516
517 bool HadError() { return hadError; }
518
519 // Retrieves the fully-structured initializer list used for
520 // semantic analysis and code generation.
521 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
522};
523
524} // end anonymous namespace
525
526ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
527 const InitializedEntity &Entity) {
528 InitializationKind Kind = InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc,
529 isImplicit: true);
530 MultiExprArg SubInit;
531 Expr *InitExpr;
532 InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
533
534 // C++ [dcl.init.aggr]p7:
535 // If there are fewer initializer-clauses in the list than there are
536 // members in the aggregate, then each member not explicitly initialized
537 // ...
538 bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
539 Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
540 if (EmptyInitList) {
541 // C++1y / DR1070:
542 // shall be initialized [...] from an empty initializer list.
543 //
544 // We apply the resolution of this DR to C++11 but not C++98, since C++98
545 // does not have useful semantics for initialization from an init list.
546 // We treat this as copy-initialization, because aggregate initialization
547 // always performs copy-initialization on its elements.
548 //
549 // Only do this if we're initializing a class type, to avoid filling in
550 // the initializer list where possible.
551 InitExpr = VerifyOnly
552 ? &DummyInitList
553 : new (SemaRef.Context)
554 InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
555 InitExpr->setType(SemaRef.Context.VoidTy);
556 SubInit = InitExpr;
557 Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
558 } else {
559 // C++03:
560 // shall be value-initialized.
561 }
562
563 InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
564 // libstdc++4.6 marks the vector default constructor as explicit in
565 // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
566 // stlport does so too. Look for std::__debug for libstdc++, and for
567 // std:: for stlport. This is effectively a compiler-side implementation of
568 // LWG2193.
569 if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
570 InitializationSequence::FK_ExplicitConstructor) {
571 OverloadCandidateSet::iterator Best;
572 OverloadingResult O =
573 InitSeq.getFailedCandidateSet()
574 .BestViableFunction(S&: SemaRef, Loc: Kind.getLocation(), Best);
575 (void)O;
576 assert(O == OR_Success && "Inconsistent overload resolution");
577 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
578 CXXRecordDecl *R = CtorDecl->getParent();
579
580 if (CtorDecl->getMinRequiredArguments() == 0 &&
581 CtorDecl->isExplicit() && R->getDeclName() &&
582 SemaRef.SourceMgr.isInSystemHeader(Loc: CtorDecl->getLocation())) {
583 bool IsInStd = false;
584 for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
585 ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
586 if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
587 IsInStd = true;
588 }
589
590 if (IsInStd && llvm::StringSwitch<bool>(R->getName())
591 .Cases(S0: "basic_string", S1: "deque", S2: "forward_list", Value: true)
592 .Cases(S0: "list", S1: "map", S2: "multimap", S3: "multiset", Value: true)
593 .Cases(S0: "priority_queue", S1: "queue", S2: "set", S3: "stack", Value: true)
594 .Cases(S0: "unordered_map", S1: "unordered_set", S2: "vector", Value: true)
595 .Default(Value: false)) {
596 InitSeq.InitializeFrom(
597 S&: SemaRef, Entity,
598 Kind: InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, isImplicit: true),
599 Args: MultiExprArg(), /*TopLevelOfInitList=*/false,
600 TreatUnavailableAsInvalid);
601 // Emit a warning for this. System header warnings aren't shown
602 // by default, but people working on system headers should see it.
603 if (!VerifyOnly) {
604 SemaRef.Diag(CtorDecl->getLocation(),
605 diag::warn_invalid_initializer_from_system_header);
606 if (Entity.getKind() == InitializedEntity::EK_Member)
607 SemaRef.Diag(Entity.getDecl()->getLocation(),
608 diag::note_used_in_initialization_here);
609 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
610 SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
611 }
612 }
613 }
614 }
615 if (!InitSeq) {
616 if (!VerifyOnly) {
617 InitSeq.Diagnose(S&: SemaRef, Entity, Kind, Args: SubInit);
618 if (Entity.getKind() == InitializedEntity::EK_Member)
619 SemaRef.Diag(Entity.getDecl()->getLocation(),
620 diag::note_in_omitted_aggregate_initializer)
621 << /*field*/1 << Entity.getDecl();
622 else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
623 bool IsTrailingArrayNewMember =
624 Entity.getParent() &&
625 Entity.getParent()->isVariableLengthArrayNew();
626 SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
627 << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
628 << Entity.getElementIndex();
629 }
630 }
631 hadError = true;
632 return ExprError();
633 }
634
635 return VerifyOnly ? ExprResult()
636 : InitSeq.Perform(S&: SemaRef, Entity, Kind, Args: SubInit);
637}
638
639void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
640 SourceLocation Loc) {
641 // If we're building a fully-structured list, we'll check this at the end
642 // once we know which elements are actually initialized. Otherwise, we know
643 // that there are no designators so we can just check now.
644 if (FullyStructuredList)
645 return;
646 PerformEmptyInit(Loc, Entity);
647}
648
649void InitListChecker::FillInEmptyInitForBase(
650 unsigned Init, const CXXBaseSpecifier &Base,
651 const InitializedEntity &ParentEntity, InitListExpr *ILE,
652 bool &RequiresSecondPass, bool FillWithNoInit) {
653 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
654 Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &ParentEntity);
655
656 if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
657 ExprResult BaseInit = FillWithNoInit
658 ? new (SemaRef.Context) NoInitExpr(Base.getType())
659 : PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: BaseEntity);
660 if (BaseInit.isInvalid()) {
661 hadError = true;
662 return;
663 }
664
665 if (!VerifyOnly) {
666 assert(Init < ILE->getNumInits() && "should have been expanded");
667 ILE->setInit(Init, expr: BaseInit.getAs<Expr>());
668 }
669 } else if (InitListExpr *InnerILE =
670 dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) {
671 FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerILE, RequiresSecondPass,
672 OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
673 } else if (DesignatedInitUpdateExpr *InnerDIUE =
674 dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) {
675 FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerDIUE->getUpdater(),
676 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
677 /*FillWithNoInit =*/true);
678 }
679}
680
681void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
682 const InitializedEntity &ParentEntity,
683 InitListExpr *ILE,
684 bool &RequiresSecondPass,
685 bool FillWithNoInit) {
686 SourceLocation Loc = ILE->getEndLoc();
687 unsigned NumInits = ILE->getNumInits();
688 InitializedEntity MemberEntity
689 = InitializedEntity::InitializeMember(Member: Field, Parent: &ParentEntity);
690
691 if (Init >= NumInits || !ILE->getInit(Init)) {
692 if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
693 if (!RType->getDecl()->isUnion())
694 assert((Init < NumInits || VerifyOnly) &&
695 "This ILE should have been expanded");
696
697 if (FillWithNoInit) {
698 assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
699 Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
700 if (Init < NumInits)
701 ILE->setInit(Init, expr: Filler);
702 else
703 ILE->updateInit(C: SemaRef.Context, Init, expr: Filler);
704 return;
705 }
706 // C++1y [dcl.init.aggr]p7:
707 // If there are fewer initializer-clauses in the list than there are
708 // members in the aggregate, then each member not explicitly initialized
709 // shall be initialized from its brace-or-equal-initializer [...]
710 if (Field->hasInClassInitializer()) {
711 if (VerifyOnly)
712 return;
713
714 ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
715 if (DIE.isInvalid()) {
716 hadError = true;
717 return;
718 }
719 SemaRef.checkInitializerLifetime(Entity: MemberEntity, Init: DIE.get());
720 if (Init < NumInits)
721 ILE->setInit(Init, expr: DIE.get());
722 else {
723 ILE->updateInit(C: SemaRef.Context, Init, expr: DIE.get());
724 RequiresSecondPass = true;
725 }
726 return;
727 }
728
729 if (Field->getType()->isReferenceType()) {
730 if (!VerifyOnly) {
731 // C++ [dcl.init.aggr]p9:
732 // If an incomplete or empty initializer-list leaves a
733 // member of reference type uninitialized, the program is
734 // ill-formed.
735 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
736 << Field->getType()
737 << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
738 ->getSourceRange();
739 SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
740 }
741 hadError = true;
742 return;
743 }
744
745 ExprResult MemberInit = PerformEmptyInit(Loc, Entity: MemberEntity);
746 if (MemberInit.isInvalid()) {
747 hadError = true;
748 return;
749 }
750
751 if (hadError || VerifyOnly) {
752 // Do nothing
753 } else if (Init < NumInits) {
754 ILE->setInit(Init, expr: MemberInit.getAs<Expr>());
755 } else if (!isa<ImplicitValueInitExpr>(Val: MemberInit.get())) {
756 // Empty initialization requires a constructor call, so
757 // extend the initializer list to include the constructor
758 // call and make a note that we'll need to take another pass
759 // through the initializer list.
760 ILE->updateInit(C: SemaRef.Context, Init, expr: MemberInit.getAs<Expr>());
761 RequiresSecondPass = true;
762 }
763 } else if (InitListExpr *InnerILE
764 = dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) {
765 FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerILE,
766 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
767 } else if (DesignatedInitUpdateExpr *InnerDIUE =
768 dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) {
769 FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerDIUE->getUpdater(),
770 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
771 /*FillWithNoInit =*/true);
772 }
773}
774
775/// Recursively replaces NULL values within the given initializer list
776/// with expressions that perform value-initialization of the
777/// appropriate type, and finish off the InitListExpr formation.
778void
779InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
780 InitListExpr *ILE,
781 bool &RequiresSecondPass,
782 InitListExpr *OuterILE,
783 unsigned OuterIndex,
784 bool FillWithNoInit) {
785 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
786 "Should not have void type");
787
788 // We don't need to do any checks when just filling NoInitExprs; that can't
789 // fail.
790 if (FillWithNoInit && VerifyOnly)
791 return;
792
793 // If this is a nested initializer list, we might have changed its contents
794 // (and therefore some of its properties, such as instantiation-dependence)
795 // while filling it in. Inform the outer initializer list so that its state
796 // can be updated to match.
797 // FIXME: We should fully build the inner initializers before constructing
798 // the outer InitListExpr instead of mutating AST nodes after they have
799 // been used as subexpressions of other nodes.
800 struct UpdateOuterILEWithUpdatedInit {
801 InitListExpr *Outer;
802 unsigned OuterIndex;
803 ~UpdateOuterILEWithUpdatedInit() {
804 if (Outer)
805 Outer->setInit(Init: OuterIndex, expr: Outer->getInit(Init: OuterIndex));
806 }
807 } UpdateOuterRAII = {.Outer: OuterILE, .OuterIndex: OuterIndex};
808
809 // A transparent ILE is not performing aggregate initialization and should
810 // not be filled in.
811 if (ILE->isTransparent())
812 return;
813
814 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
815 const RecordDecl *RDecl = RType->getDecl();
816 if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
817 FillInEmptyInitForField(Init: 0, Field: ILE->getInitializedFieldInUnion(),
818 ParentEntity: Entity, ILE, RequiresSecondPass, FillWithNoInit);
819 else if (RDecl->isUnion() && isa<CXXRecordDecl>(Val: RDecl) &&
820 cast<CXXRecordDecl>(Val: RDecl)->hasInClassInitializer()) {
821 for (auto *Field : RDecl->fields()) {
822 if (Field->hasInClassInitializer()) {
823 FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
824 FillWithNoInit);
825 break;
826 }
827 }
828 } else {
829 // The fields beyond ILE->getNumInits() are default initialized, so in
830 // order to leave them uninitialized, the ILE is expanded and the extra
831 // fields are then filled with NoInitExpr.
832 unsigned NumElems = numStructUnionElements(DeclType: ILE->getType());
833 if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
834 ++NumElems;
835 if (!VerifyOnly && ILE->getNumInits() < NumElems)
836 ILE->resizeInits(Context: SemaRef.Context, NumInits: NumElems);
837
838 unsigned Init = 0;
839
840 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
841 for (auto &Base : CXXRD->bases()) {
842 if (hadError)
843 return;
844
845 FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
846 FillWithNoInit);
847 ++Init;
848 }
849 }
850
851 for (auto *Field : RDecl->fields()) {
852 if (Field->isUnnamedBitField())
853 continue;
854
855 if (hadError)
856 return;
857
858 FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
859 FillWithNoInit);
860 if (hadError)
861 return;
862
863 ++Init;
864
865 // Only look at the first initialization of a union.
866 if (RDecl->isUnion())
867 break;
868 }
869 }
870
871 return;
872 }
873
874 QualType ElementType;
875
876 InitializedEntity ElementEntity = Entity;
877 unsigned NumInits = ILE->getNumInits();
878 unsigned NumElements = NumInits;
879 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(T: ILE->getType())) {
880 ElementType = AType->getElementType();
881 if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
882 NumElements = CAType->getZExtSize();
883 // For an array new with an unknown bound, ask for one additional element
884 // in order to populate the array filler.
885 if (Entity.isVariableLengthArrayNew())
886 ++NumElements;
887 ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context,
888 Index: 0, Parent: Entity);
889 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
890 ElementType = VType->getElementType();
891 NumElements = VType->getNumElements();
892 ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context,
893 Index: 0, Parent: Entity);
894 } else
895 ElementType = ILE->getType();
896
897 bool SkipEmptyInitChecks = false;
898 for (unsigned Init = 0; Init != NumElements; ++Init) {
899 if (hadError)
900 return;
901
902 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
903 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
904 ElementEntity.setElementIndex(Init);
905
906 if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
907 return;
908
909 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
910 if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
911 ILE->setInit(Init, expr: ILE->getArrayFiller());
912 else if (!InitExpr && !ILE->hasArrayFiller()) {
913 // In VerifyOnly mode, there's no point performing empty initialization
914 // more than once.
915 if (SkipEmptyInitChecks)
916 continue;
917
918 Expr *Filler = nullptr;
919
920 if (FillWithNoInit)
921 Filler = new (SemaRef.Context) NoInitExpr(ElementType);
922 else {
923 ExprResult ElementInit =
924 PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: ElementEntity);
925 if (ElementInit.isInvalid()) {
926 hadError = true;
927 return;
928 }
929
930 Filler = ElementInit.getAs<Expr>();
931 }
932
933 if (hadError) {
934 // Do nothing
935 } else if (VerifyOnly) {
936 SkipEmptyInitChecks = true;
937 } else if (Init < NumInits) {
938 // For arrays, just set the expression used for value-initialization
939 // of the "holes" in the array.
940 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
941 ILE->setArrayFiller(Filler);
942 else
943 ILE->setInit(Init, expr: Filler);
944 } else {
945 // For arrays, just set the expression used for value-initialization
946 // of the rest of elements and exit.
947 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
948 ILE->setArrayFiller(Filler);
949 return;
950 }
951
952 if (!isa<ImplicitValueInitExpr>(Val: Filler) && !isa<NoInitExpr>(Val: Filler)) {
953 // Empty initialization requires a constructor call, so
954 // extend the initializer list to include the constructor
955 // call and make a note that we'll need to take another pass
956 // through the initializer list.
957 ILE->updateInit(C: SemaRef.Context, Init, expr: Filler);
958 RequiresSecondPass = true;
959 }
960 }
961 } else if (InitListExpr *InnerILE
962 = dyn_cast_or_null<InitListExpr>(Val: InitExpr)) {
963 FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerILE, RequiresSecondPass,
964 OuterILE: ILE, OuterIndex: Init, FillWithNoInit);
965 } else if (DesignatedInitUpdateExpr *InnerDIUE =
966 dyn_cast_or_null<DesignatedInitUpdateExpr>(Val: InitExpr)) {
967 FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerDIUE->getUpdater(),
968 RequiresSecondPass, OuterILE: ILE, OuterIndex: Init,
969 /*FillWithNoInit =*/true);
970 }
971 }
972}
973
974static bool hasAnyDesignatedInits(const InitListExpr *IL) {
975 for (const Stmt *Init : *IL)
976 if (isa_and_nonnull<DesignatedInitExpr>(Val: Init))
977 return true;
978 return false;
979}
980
981InitListChecker::InitListChecker(
982 Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
983 bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
984 SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
985 : SemaRef(S), VerifyOnly(VerifyOnly),
986 TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
987 InOverloadResolution(InOverloadResolution),
988 AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
989 if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
990 FullyStructuredList =
991 createInitListExpr(CurrentObjectType: T, InitRange: IL->getSourceRange(), ExpectedNumInits: IL->getNumInits());
992
993 // FIXME: Check that IL isn't already the semantic form of some other
994 // InitListExpr. If it is, we'd create a broken AST.
995 if (!VerifyOnly)
996 FullyStructuredList->setSyntacticForm(IL);
997 }
998
999 CheckExplicitInitList(Entity, IList: IL, T, StructuredList: FullyStructuredList,
1000 /*TopLevelObject=*/true);
1001
1002 if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
1003 bool RequiresSecondPass = false;
1004 FillInEmptyInitializations(Entity, ILE: FullyStructuredList, RequiresSecondPass,
1005 /*OuterILE=*/nullptr, /*OuterIndex=*/0);
1006 if (RequiresSecondPass && !hadError)
1007 FillInEmptyInitializations(Entity, ILE: FullyStructuredList,
1008 RequiresSecondPass, OuterILE: nullptr, OuterIndex: 0);
1009 }
1010 if (hadError && FullyStructuredList)
1011 FullyStructuredList->markError();
1012}
1013
1014int InitListChecker::numArrayElements(QualType DeclType) {
1015 // FIXME: use a proper constant
1016 int maxElements = 0x7FFFFFFF;
1017 if (const ConstantArrayType *CAT =
1018 SemaRef.Context.getAsConstantArrayType(T: DeclType)) {
1019 maxElements = static_cast<int>(CAT->getZExtSize());
1020 }
1021 return maxElements;
1022}
1023
1024int InitListChecker::numStructUnionElements(QualType DeclType) {
1025 RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1026 int InitializableMembers = 0;
1027 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: structDecl))
1028 InitializableMembers += CXXRD->getNumBases();
1029 for (const auto *Field : structDecl->fields())
1030 if (!Field->isUnnamedBitField())
1031 ++InitializableMembers;
1032
1033 if (structDecl->isUnion())
1034 return std::min(a: InitializableMembers, b: 1);
1035 return InitializableMembers - structDecl->hasFlexibleArrayMember();
1036}
1037
1038RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1039 if (const auto *RT = DeclType->getAs<RecordType>())
1040 return RT->getDecl();
1041 if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1042 return Inject->getDecl();
1043 return nullptr;
1044}
1045
1046/// Determine whether Entity is an entity for which it is idiomatic to elide
1047/// the braces in aggregate initialization.
1048static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1049 // Recursive initialization of the one and only field within an aggregate
1050 // class is considered idiomatic. This case arises in particular for
1051 // initialization of std::array, where the C++ standard suggests the idiom of
1052 //
1053 // std::array<T, N> arr = {1, 2, 3};
1054 //
1055 // (where std::array is an aggregate struct containing a single array field.
1056
1057 if (!Entity.getParent())
1058 return false;
1059
1060 // Allows elide brace initialization for aggregates with empty base.
1061 if (Entity.getKind() == InitializedEntity::EK_Base) {
1062 auto *ParentRD =
1063 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1064 CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(Val: ParentRD);
1065 return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1066 }
1067
1068 // Allow brace elision if the only subobject is a field.
1069 if (Entity.getKind() == InitializedEntity::EK_Member) {
1070 auto *ParentRD =
1071 Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1072 if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: ParentRD)) {
1073 if (CXXRD->getNumBases()) {
1074 return false;
1075 }
1076 }
1077 auto FieldIt = ParentRD->field_begin();
1078 assert(FieldIt != ParentRD->field_end() &&
1079 "no fields but have initializer for member?");
1080 return ++FieldIt == ParentRD->field_end();
1081 }
1082
1083 return false;
1084}
1085
1086/// Check whether the range of the initializer \p ParentIList from element
1087/// \p Index onwards can be used to initialize an object of type \p T. Update
1088/// \p Index to indicate how many elements of the list were consumed.
1089///
1090/// This also fills in \p StructuredList, from element \p StructuredIndex
1091/// onwards, with the fully-braced, desugared form of the initialization.
1092void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1093 InitListExpr *ParentIList,
1094 QualType T, unsigned &Index,
1095 InitListExpr *StructuredList,
1096 unsigned &StructuredIndex) {
1097 int maxElements = 0;
1098
1099 if (T->isArrayType())
1100 maxElements = numArrayElements(DeclType: T);
1101 else if (T->isRecordType())
1102 maxElements = numStructUnionElements(DeclType: T);
1103 else if (T->isVectorType())
1104 maxElements = T->castAs<VectorType>()->getNumElements();
1105 else
1106 llvm_unreachable("CheckImplicitInitList(): Illegal type");
1107
1108 if (maxElements == 0) {
1109 if (!VerifyOnly)
1110 SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1111 diag::err_implicit_empty_initializer);
1112 ++Index;
1113 hadError = true;
1114 return;
1115 }
1116
1117 // Build a structured initializer list corresponding to this subobject.
1118 InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1119 IList: ParentIList, Index, CurrentObjectType: T, StructuredList, StructuredIndex,
1120 InitRange: SourceRange(ParentIList->getInit(Init: Index)->getBeginLoc(),
1121 ParentIList->getSourceRange().getEnd()));
1122 unsigned StructuredSubobjectInitIndex = 0;
1123
1124 // Check the element types and build the structural subobject.
1125 unsigned StartIndex = Index;
1126 CheckListElementTypes(Entity, IList: ParentIList, DeclType&: T,
1127 /*SubobjectIsDesignatorContext=*/false, Index,
1128 StructuredList: StructuredSubobjectInitList,
1129 StructuredIndex&: StructuredSubobjectInitIndex);
1130
1131 if (StructuredSubobjectInitList) {
1132 StructuredSubobjectInitList->setType(T);
1133
1134 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1135 // Update the structured sub-object initializer so that it's ending
1136 // range corresponds with the end of the last initializer it used.
1137 if (EndIndex < ParentIList->getNumInits() &&
1138 ParentIList->getInit(Init: EndIndex)) {
1139 SourceLocation EndLoc
1140 = ParentIList->getInit(Init: EndIndex)->getSourceRange().getEnd();
1141 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1142 }
1143
1144 // Complain about missing braces.
1145 if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1146 !ParentIList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) &&
1147 !isIdiomaticBraceElisionEntity(Entity)) {
1148 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1149 diag::warn_missing_braces)
1150 << StructuredSubobjectInitList->getSourceRange()
1151 << FixItHint::CreateInsertion(
1152 StructuredSubobjectInitList->getBeginLoc(), "{")
1153 << FixItHint::CreateInsertion(
1154 SemaRef.getLocForEndOfToken(
1155 StructuredSubobjectInitList->getEndLoc()),
1156 "}");
1157 }
1158
1159 // Warn if this type won't be an aggregate in future versions of C++.
1160 auto *CXXRD = T->getAsCXXRecordDecl();
1161 if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1162 SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1163 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1164 << StructuredSubobjectInitList->getSourceRange() << T;
1165 }
1166 }
1167}
1168
1169/// Warn that \p Entity was of scalar type and was initialized by a
1170/// single-element braced initializer list.
1171static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1172 SourceRange Braces) {
1173 // Don't warn during template instantiation. If the initialization was
1174 // non-dependent, we warned during the initial parse; otherwise, the
1175 // type might not be scalar in some uses of the template.
1176 if (S.inTemplateInstantiation())
1177 return;
1178
1179 unsigned DiagID = 0;
1180
1181 switch (Entity.getKind()) {
1182 case InitializedEntity::EK_VectorElement:
1183 case InitializedEntity::EK_ComplexElement:
1184 case InitializedEntity::EK_ArrayElement:
1185 case InitializedEntity::EK_Parameter:
1186 case InitializedEntity::EK_Parameter_CF_Audited:
1187 case InitializedEntity::EK_TemplateParameter:
1188 case InitializedEntity::EK_Result:
1189 case InitializedEntity::EK_ParenAggInitMember:
1190 // Extra braces here are suspicious.
1191 DiagID = diag::warn_braces_around_init;
1192 break;
1193
1194 case InitializedEntity::EK_Member:
1195 // Warn on aggregate initialization but not on ctor init list or
1196 // default member initializer.
1197 if (Entity.getParent())
1198 DiagID = diag::warn_braces_around_init;
1199 break;
1200
1201 case InitializedEntity::EK_Variable:
1202 case InitializedEntity::EK_LambdaCapture:
1203 // No warning, might be direct-list-initialization.
1204 // FIXME: Should we warn for copy-list-initialization in these cases?
1205 break;
1206
1207 case InitializedEntity::EK_New:
1208 case InitializedEntity::EK_Temporary:
1209 case InitializedEntity::EK_CompoundLiteralInit:
1210 // No warning, braces are part of the syntax of the underlying construct.
1211 break;
1212
1213 case InitializedEntity::EK_RelatedResult:
1214 // No warning, we already warned when initializing the result.
1215 break;
1216
1217 case InitializedEntity::EK_Exception:
1218 case InitializedEntity::EK_Base:
1219 case InitializedEntity::EK_Delegating:
1220 case InitializedEntity::EK_BlockElement:
1221 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1222 case InitializedEntity::EK_Binding:
1223 case InitializedEntity::EK_StmtExprResult:
1224 llvm_unreachable("unexpected braced scalar init");
1225 }
1226
1227 if (DiagID) {
1228 S.Diag(Braces.getBegin(), DiagID)
1229 << Entity.getType()->isSizelessBuiltinType() << Braces
1230 << FixItHint::CreateRemoval(RemoveRange: Braces.getBegin())
1231 << FixItHint::CreateRemoval(RemoveRange: Braces.getEnd());
1232 }
1233}
1234
1235/// Check whether the initializer \p IList (that was written with explicit
1236/// braces) can be used to initialize an object of type \p T.
1237///
1238/// This also fills in \p StructuredList with the fully-braced, desugared
1239/// form of the initialization.
1240void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1241 InitListExpr *IList, QualType &T,
1242 InitListExpr *StructuredList,
1243 bool TopLevelObject) {
1244 unsigned Index = 0, StructuredIndex = 0;
1245 CheckListElementTypes(Entity, IList, DeclType&: T, /*SubobjectIsDesignatorContext=*/true,
1246 Index, StructuredList, StructuredIndex, TopLevelObject);
1247 if (StructuredList) {
1248 QualType ExprTy = T;
1249 if (!ExprTy->isArrayType())
1250 ExprTy = ExprTy.getNonLValueExprType(Context: SemaRef.Context);
1251 if (!VerifyOnly)
1252 IList->setType(ExprTy);
1253 StructuredList->setType(ExprTy);
1254 }
1255 if (hadError)
1256 return;
1257
1258 // Don't complain for incomplete types, since we'll get an error elsewhere.
1259 if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1260 // We have leftover initializers
1261 bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1262 (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1263 hadError = ExtraInitsIsError;
1264 if (VerifyOnly) {
1265 return;
1266 } else if (StructuredIndex == 1 &&
1267 IsStringInit(init: StructuredList->getInit(Init: 0), declType: T, Context&: SemaRef.Context) ==
1268 SIF_None) {
1269 unsigned DK =
1270 ExtraInitsIsError
1271 ? diag::err_excess_initializers_in_char_array_initializer
1272 : diag::ext_excess_initializers_in_char_array_initializer;
1273 SemaRef.Diag(IList->getInit(Init: Index)->getBeginLoc(), DK)
1274 << IList->getInit(Init: Index)->getSourceRange();
1275 } else if (T->isSizelessBuiltinType()) {
1276 unsigned DK = ExtraInitsIsError
1277 ? diag::err_excess_initializers_for_sizeless_type
1278 : diag::ext_excess_initializers_for_sizeless_type;
1279 SemaRef.Diag(IList->getInit(Init: Index)->getBeginLoc(), DK)
1280 << T << IList->getInit(Init: Index)->getSourceRange();
1281 } else {
1282 int initKind = T->isArrayType() ? 0 :
1283 T->isVectorType() ? 1 :
1284 T->isScalarType() ? 2 :
1285 T->isUnionType() ? 3 :
1286 4;
1287
1288 unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1289 : diag::ext_excess_initializers;
1290 SemaRef.Diag(IList->getInit(Init: Index)->getBeginLoc(), DK)
1291 << initKind << IList->getInit(Init: Index)->getSourceRange();
1292 }
1293 }
1294
1295 if (!VerifyOnly) {
1296 if (T->isScalarType() && IList->getNumInits() == 1 &&
1297 !isa<InitListExpr>(Val: IList->getInit(Init: 0)))
1298 warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1299
1300 // Warn if this is a class type that won't be an aggregate in future
1301 // versions of C++.
1302 auto *CXXRD = T->getAsCXXRecordDecl();
1303 if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1304 // Don't warn if there's an equivalent default constructor that would be
1305 // used instead.
1306 bool HasEquivCtor = false;
1307 if (IList->getNumInits() == 0) {
1308 auto *CD = SemaRef.LookupDefaultConstructor(Class: CXXRD);
1309 HasEquivCtor = CD && !CD->isDeleted();
1310 }
1311
1312 if (!HasEquivCtor) {
1313 SemaRef.Diag(IList->getBeginLoc(),
1314 diag::warn_cxx20_compat_aggregate_init_with_ctors)
1315 << IList->getSourceRange() << T;
1316 }
1317 }
1318 }
1319}
1320
1321void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1322 InitListExpr *IList,
1323 QualType &DeclType,
1324 bool SubobjectIsDesignatorContext,
1325 unsigned &Index,
1326 InitListExpr *StructuredList,
1327 unsigned &StructuredIndex,
1328 bool TopLevelObject) {
1329 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1330 // Explicitly braced initializer for complex type can be real+imaginary
1331 // parts.
1332 CheckComplexType(Entity, IList, DeclType, Index,
1333 StructuredList, StructuredIndex);
1334 } else if (DeclType->isScalarType()) {
1335 CheckScalarType(Entity, IList, DeclType, Index,
1336 StructuredList, StructuredIndex);
1337 } else if (DeclType->isVectorType()) {
1338 CheckVectorType(Entity, IList, DeclType, Index,
1339 StructuredList, StructuredIndex);
1340 } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1341 auto Bases =
1342 CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1343 CXXRecordDecl::base_class_const_iterator());
1344 if (DeclType->isRecordType()) {
1345 assert(DeclType->isAggregateType() &&
1346 "non-aggregate records should be handed in CheckSubElementType");
1347 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
1348 Bases = CXXRD->bases();
1349 } else {
1350 Bases = cast<CXXRecordDecl>(Val: RD)->bases();
1351 }
1352 CheckStructUnionTypes(Entity, IList, DeclType, Bases, Field: RD->field_begin(),
1353 SubobjectIsDesignatorContext, Index, StructuredList,
1354 StructuredIndex, TopLevelObject);
1355 } else if (DeclType->isArrayType()) {
1356 llvm::APSInt Zero(
1357 SemaRef.Context.getTypeSize(T: SemaRef.Context.getSizeType()),
1358 false);
1359 CheckArrayType(Entity, IList, DeclType, elementIndex: Zero,
1360 SubobjectIsDesignatorContext, Index,
1361 StructuredList, StructuredIndex);
1362 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1363 // This type is invalid, issue a diagnostic.
1364 ++Index;
1365 if (!VerifyOnly)
1366 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1367 << DeclType;
1368 hadError = true;
1369 } else if (DeclType->isReferenceType()) {
1370 CheckReferenceType(Entity, IList, DeclType, Index,
1371 StructuredList, StructuredIndex);
1372 } else if (DeclType->isObjCObjectType()) {
1373 if (!VerifyOnly)
1374 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1375 hadError = true;
1376 } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1377 DeclType->isSizelessBuiltinType()) {
1378 // Checks for scalar type are sufficient for these types too.
1379 CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1380 StructuredIndex);
1381 } else if (DeclType->isDependentType()) {
1382 // C++ [over.match.class.deduct]p1.5:
1383 // brace elision is not considered for any aggregate element that has a
1384 // dependent non-array type or an array type with a value-dependent bound
1385 ++Index;
1386 assert(AggrDeductionCandidateParamTypes);
1387 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1388 } else {
1389 if (!VerifyOnly)
1390 SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1391 << DeclType;
1392 hadError = true;
1393 }
1394}
1395
1396void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1397 InitListExpr *IList,
1398 QualType ElemType,
1399 unsigned &Index,
1400 InitListExpr *StructuredList,
1401 unsigned &StructuredIndex,
1402 bool DirectlyDesignated) {
1403 Expr *expr = IList->getInit(Init: Index);
1404
1405 if (ElemType->isReferenceType())
1406 return CheckReferenceType(Entity, IList, DeclType: ElemType, Index,
1407 StructuredList, StructuredIndex);
1408
1409 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(Val: expr)) {
1410 if (SubInitList->getNumInits() == 1 &&
1411 IsStringInit(init: SubInitList->getInit(Init: 0), declType: ElemType, Context&: SemaRef.Context) ==
1412 SIF_None) {
1413 // FIXME: It would be more faithful and no less correct to include an
1414 // InitListExpr in the semantic form of the initializer list in this case.
1415 expr = SubInitList->getInit(Init: 0);
1416 }
1417 // Nested aggregate initialization and C++ initialization are handled later.
1418 } else if (isa<ImplicitValueInitExpr>(Val: expr)) {
1419 // This happens during template instantiation when we see an InitListExpr
1420 // that we've already checked once.
1421 assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1422 "found implicit initialization for the wrong type");
1423 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1424 ++Index;
1425 return;
1426 }
1427
1428 if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(Val: expr)) {
1429 // C++ [dcl.init.aggr]p2:
1430 // Each member is copy-initialized from the corresponding
1431 // initializer-clause.
1432
1433 // FIXME: Better EqualLoc?
1434 InitializationKind Kind =
1435 InitializationKind::CreateCopy(InitLoc: expr->getBeginLoc(), EqualLoc: SourceLocation());
1436
1437 // Vector elements can be initialized from other vectors in which case
1438 // we need initialization entity with a type of a vector (and not a vector
1439 // element!) initializing multiple vector elements.
1440 auto TmpEntity =
1441 (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1442 ? InitializedEntity::InitializeTemporary(Type: ElemType)
1443 : Entity;
1444
1445 if (TmpEntity.getType()->isDependentType()) {
1446 // C++ [over.match.class.deduct]p1.5:
1447 // brace elision is not considered for any aggregate element that has a
1448 // dependent non-array type or an array type with a value-dependent
1449 // bound
1450 assert(AggrDeductionCandidateParamTypes);
1451 if (!isa_and_nonnull<ConstantArrayType>(
1452 Val: SemaRef.Context.getAsArrayType(T: ElemType))) {
1453 ++Index;
1454 AggrDeductionCandidateParamTypes->push_back(Elt: ElemType);
1455 return;
1456 }
1457 } else {
1458 InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1459 /*TopLevelOfInitList*/ true);
1460 // C++14 [dcl.init.aggr]p13:
1461 // If the assignment-expression can initialize a member, the member is
1462 // initialized. Otherwise [...] brace elision is assumed
1463 //
1464 // Brace elision is never performed if the element is not an
1465 // assignment-expression.
1466 if (Seq || isa<InitListExpr>(Val: expr)) {
1467 if (!VerifyOnly) {
1468 ExprResult Result = Seq.Perform(S&: SemaRef, Entity: TmpEntity, Kind, Args: expr);
1469 if (Result.isInvalid())
1470 hadError = true;
1471
1472 UpdateStructuredListElement(StructuredList, StructuredIndex,
1473 expr: Result.getAs<Expr>());
1474 } else if (!Seq) {
1475 hadError = true;
1476 } else if (StructuredList) {
1477 UpdateStructuredListElement(StructuredList, StructuredIndex,
1478 getDummyInit());
1479 }
1480 ++Index;
1481 if (AggrDeductionCandidateParamTypes)
1482 AggrDeductionCandidateParamTypes->push_back(Elt: ElemType);
1483 return;
1484 }
1485 }
1486
1487 // Fall through for subaggregate initialization
1488 } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1489 // FIXME: Need to handle atomic aggregate types with implicit init lists.
1490 return CheckScalarType(Entity, IList, DeclType: ElemType, Index,
1491 StructuredList, StructuredIndex);
1492 } else if (const ArrayType *arrayType =
1493 SemaRef.Context.getAsArrayType(T: ElemType)) {
1494 // arrayType can be incomplete if we're initializing a flexible
1495 // array member. There's nothing we can do with the completed
1496 // type here, though.
1497
1498 if (IsStringInit(Init: expr, AT: arrayType, Context&: SemaRef.Context) == SIF_None) {
1499 // FIXME: Should we do this checking in verify-only mode?
1500 if (!VerifyOnly)
1501 CheckStringInit(Str: expr, DeclT&: ElemType, AT: arrayType, S&: SemaRef,
1502 CheckC23ConstexprInit: SemaRef.getLangOpts().C23 &&
1503 initializingConstexprVariable(Entity));
1504 if (StructuredList)
1505 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1506 ++Index;
1507 return;
1508 }
1509
1510 // Fall through for subaggregate initialization.
1511
1512 } else {
1513 assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1514 ElemType->isOpenCLSpecificType()) && "Unexpected type");
1515
1516 // C99 6.7.8p13:
1517 //
1518 // The initializer for a structure or union object that has
1519 // automatic storage duration shall be either an initializer
1520 // list as described below, or a single expression that has
1521 // compatible structure or union type. In the latter case, the
1522 // initial value of the object, including unnamed members, is
1523 // that of the expression.
1524 ExprResult ExprRes = expr;
1525 if (SemaRef.CheckSingleAssignmentConstraints(
1526 LHSType: ElemType, RHS&: ExprRes, Diagnose: !VerifyOnly) != Sema::Incompatible) {
1527 if (ExprRes.isInvalid())
1528 hadError = true;
1529 else {
1530 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(E: ExprRes.get());
1531 if (ExprRes.isInvalid())
1532 hadError = true;
1533 }
1534 UpdateStructuredListElement(StructuredList, StructuredIndex,
1535 expr: ExprRes.getAs<Expr>());
1536 ++Index;
1537 return;
1538 }
1539 ExprRes.get();
1540 // Fall through for subaggregate initialization
1541 }
1542
1543 // C++ [dcl.init.aggr]p12:
1544 //
1545 // [...] Otherwise, if the member is itself a non-empty
1546 // subaggregate, brace elision is assumed and the initializer is
1547 // considered for the initialization of the first member of
1548 // the subaggregate.
1549 // OpenCL vector initializer is handled elsewhere.
1550 if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1551 ElemType->isAggregateType()) {
1552 CheckImplicitInitList(Entity, ParentIList: IList, T: ElemType, Index, StructuredList,
1553 StructuredIndex);
1554 ++StructuredIndex;
1555
1556 // In C++20, brace elision is not permitted for a designated initializer.
1557 if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1558 if (InOverloadResolution)
1559 hadError = true;
1560 if (!VerifyOnly) {
1561 SemaRef.Diag(expr->getBeginLoc(),
1562 diag::ext_designated_init_brace_elision)
1563 << expr->getSourceRange()
1564 << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1565 << FixItHint::CreateInsertion(
1566 SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1567 }
1568 }
1569 } else {
1570 if (!VerifyOnly) {
1571 // We cannot initialize this element, so let PerformCopyInitialization
1572 // produce the appropriate diagnostic. We already checked that this
1573 // initialization will fail.
1574 ExprResult Copy =
1575 SemaRef.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: expr,
1576 /*TopLevelOfInitList=*/true);
1577 (void)Copy;
1578 assert(Copy.isInvalid() &&
1579 "expected non-aggregate initialization to fail");
1580 }
1581 hadError = true;
1582 ++Index;
1583 ++StructuredIndex;
1584 }
1585}
1586
1587void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1588 InitListExpr *IList, QualType DeclType,
1589 unsigned &Index,
1590 InitListExpr *StructuredList,
1591 unsigned &StructuredIndex) {
1592 assert(Index == 0 && "Index in explicit init list must be zero");
1593
1594 // As an extension, clang supports complex initializers, which initialize
1595 // a complex number component-wise. When an explicit initializer list for
1596 // a complex number contains two initializers, this extension kicks in:
1597 // it expects the initializer list to contain two elements convertible to
1598 // the element type of the complex type. The first element initializes
1599 // the real part, and the second element intitializes the imaginary part.
1600
1601 if (IList->getNumInits() < 2)
1602 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1603 StructuredIndex);
1604
1605 // This is an extension in C. (The builtin _Complex type does not exist
1606 // in the C++ standard.)
1607 if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1608 SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1609 << IList->getSourceRange();
1610
1611 // Initialize the complex number.
1612 QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1613 InitializedEntity ElementEntity =
1614 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1615
1616 for (unsigned i = 0; i < 2; ++i) {
1617 ElementEntity.setElementIndex(Index);
1618 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1619 StructuredList, StructuredIndex);
1620 }
1621}
1622
1623void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1624 InitListExpr *IList, QualType DeclType,
1625 unsigned &Index,
1626 InitListExpr *StructuredList,
1627 unsigned &StructuredIndex) {
1628 if (Index >= IList->getNumInits()) {
1629 if (!VerifyOnly) {
1630 if (SemaRef.getLangOpts().CPlusPlus) {
1631 if (DeclType->isSizelessBuiltinType())
1632 SemaRef.Diag(IList->getBeginLoc(),
1633 SemaRef.getLangOpts().CPlusPlus11
1634 ? diag::warn_cxx98_compat_empty_sizeless_initializer
1635 : diag::err_empty_sizeless_initializer)
1636 << DeclType << IList->getSourceRange();
1637 else
1638 SemaRef.Diag(IList->getBeginLoc(),
1639 SemaRef.getLangOpts().CPlusPlus11
1640 ? diag::warn_cxx98_compat_empty_scalar_initializer
1641 : diag::err_empty_scalar_initializer)
1642 << IList->getSourceRange();
1643 }
1644 }
1645 hadError =
1646 SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1647 ++Index;
1648 ++StructuredIndex;
1649 return;
1650 }
1651
1652 Expr *expr = IList->getInit(Init: Index);
1653 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(Val: expr)) {
1654 // FIXME: This is invalid, and accepting it causes overload resolution
1655 // to pick the wrong overload in some corner cases.
1656 if (!VerifyOnly)
1657 SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1658 << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1659
1660 CheckScalarType(Entity, IList: SubIList, DeclType, Index, StructuredList,
1661 StructuredIndex);
1662 return;
1663 } else if (isa<DesignatedInitExpr>(Val: expr)) {
1664 if (!VerifyOnly)
1665 SemaRef.Diag(expr->getBeginLoc(),
1666 diag::err_designator_for_scalar_or_sizeless_init)
1667 << DeclType->isSizelessBuiltinType() << DeclType
1668 << expr->getSourceRange();
1669 hadError = true;
1670 ++Index;
1671 ++StructuredIndex;
1672 return;
1673 }
1674
1675 ExprResult Result;
1676 if (VerifyOnly) {
1677 if (SemaRef.CanPerformCopyInitialization(Entity, Init: expr))
1678 Result = getDummyInit();
1679 else
1680 Result = ExprError();
1681 } else {
1682 Result =
1683 SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr,
1684 /*TopLevelOfInitList=*/true);
1685 }
1686
1687 Expr *ResultExpr = nullptr;
1688
1689 if (Result.isInvalid())
1690 hadError = true; // types weren't compatible.
1691 else {
1692 ResultExpr = Result.getAs<Expr>();
1693
1694 if (ResultExpr != expr && !VerifyOnly) {
1695 // The type was promoted, update initializer list.
1696 // FIXME: Why are we updating the syntactic init list?
1697 IList->setInit(Init: Index, expr: ResultExpr);
1698 }
1699 }
1700 UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr);
1701 ++Index;
1702 if (AggrDeductionCandidateParamTypes)
1703 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1704}
1705
1706void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1707 InitListExpr *IList, QualType DeclType,
1708 unsigned &Index,
1709 InitListExpr *StructuredList,
1710 unsigned &StructuredIndex) {
1711 if (Index >= IList->getNumInits()) {
1712 // FIXME: It would be wonderful if we could point at the actual member. In
1713 // general, it would be useful to pass location information down the stack,
1714 // so that we know the location (or decl) of the "current object" being
1715 // initialized.
1716 if (!VerifyOnly)
1717 SemaRef.Diag(IList->getBeginLoc(),
1718 diag::err_init_reference_member_uninitialized)
1719 << DeclType << IList->getSourceRange();
1720 hadError = true;
1721 ++Index;
1722 ++StructuredIndex;
1723 return;
1724 }
1725
1726 Expr *expr = IList->getInit(Init: Index);
1727 if (isa<InitListExpr>(Val: expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1728 if (!VerifyOnly)
1729 SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1730 << DeclType << IList->getSourceRange();
1731 hadError = true;
1732 ++Index;
1733 ++StructuredIndex;
1734 return;
1735 }
1736
1737 ExprResult Result;
1738 if (VerifyOnly) {
1739 if (SemaRef.CanPerformCopyInitialization(Entity,Init: expr))
1740 Result = getDummyInit();
1741 else
1742 Result = ExprError();
1743 } else {
1744 Result =
1745 SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr,
1746 /*TopLevelOfInitList=*/true);
1747 }
1748
1749 if (Result.isInvalid())
1750 hadError = true;
1751
1752 expr = Result.getAs<Expr>();
1753 // FIXME: Why are we updating the syntactic init list?
1754 if (!VerifyOnly && expr)
1755 IList->setInit(Init: Index, expr);
1756
1757 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1758 ++Index;
1759 if (AggrDeductionCandidateParamTypes)
1760 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1761}
1762
1763void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1764 InitListExpr *IList, QualType DeclType,
1765 unsigned &Index,
1766 InitListExpr *StructuredList,
1767 unsigned &StructuredIndex) {
1768 const VectorType *VT = DeclType->castAs<VectorType>();
1769 unsigned maxElements = VT->getNumElements();
1770 unsigned numEltsInit = 0;
1771 QualType elementType = VT->getElementType();
1772
1773 if (Index >= IList->getNumInits()) {
1774 // Make sure the element type can be value-initialized.
1775 CheckEmptyInitializable(
1776 Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity),
1777 Loc: IList->getEndLoc());
1778 return;
1779 }
1780
1781 if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1782 // If the initializing element is a vector, try to copy-initialize
1783 // instead of breaking it apart (which is doomed to failure anyway).
1784 Expr *Init = IList->getInit(Init: Index);
1785 if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVectorType()) {
1786 ExprResult Result;
1787 if (VerifyOnly) {
1788 if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1789 Result = getDummyInit();
1790 else
1791 Result = ExprError();
1792 } else {
1793 Result =
1794 SemaRef.PerformCopyInitialization(Entity, EqualLoc: Init->getBeginLoc(), Init,
1795 /*TopLevelOfInitList=*/true);
1796 }
1797
1798 Expr *ResultExpr = nullptr;
1799 if (Result.isInvalid())
1800 hadError = true; // types weren't compatible.
1801 else {
1802 ResultExpr = Result.getAs<Expr>();
1803
1804 if (ResultExpr != Init && !VerifyOnly) {
1805 // The type was promoted, update initializer list.
1806 // FIXME: Why are we updating the syntactic init list?
1807 IList->setInit(Init: Index, expr: ResultExpr);
1808 }
1809 }
1810 UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr);
1811 ++Index;
1812 if (AggrDeductionCandidateParamTypes)
1813 AggrDeductionCandidateParamTypes->push_back(Elt: elementType);
1814 return;
1815 }
1816
1817 InitializedEntity ElementEntity =
1818 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1819
1820 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1821 // Don't attempt to go past the end of the init list
1822 if (Index >= IList->getNumInits()) {
1823 CheckEmptyInitializable(Entity: ElementEntity, Loc: IList->getEndLoc());
1824 break;
1825 }
1826
1827 ElementEntity.setElementIndex(Index);
1828 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1829 StructuredList, StructuredIndex);
1830 }
1831
1832 if (VerifyOnly)
1833 return;
1834
1835 bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1836 const VectorType *T = Entity.getType()->castAs<VectorType>();
1837 if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1838 T->getVectorKind() == VectorKind::NeonPoly)) {
1839 // The ability to use vector initializer lists is a GNU vector extension
1840 // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1841 // endian machines it works fine, however on big endian machines it
1842 // exhibits surprising behaviour:
1843 //
1844 // uint32x2_t x = {42, 64};
1845 // return vget_lane_u32(x, 0); // Will return 64.
1846 //
1847 // Because of this, explicitly call out that it is non-portable.
1848 //
1849 SemaRef.Diag(IList->getBeginLoc(),
1850 diag::warn_neon_vector_initializer_non_portable);
1851
1852 const char *typeCode;
1853 unsigned typeSize = SemaRef.Context.getTypeSize(T: elementType);
1854
1855 if (elementType->isFloatingType())
1856 typeCode = "f";
1857 else if (elementType->isSignedIntegerType())
1858 typeCode = "s";
1859 else if (elementType->isUnsignedIntegerType())
1860 typeCode = "u";
1861 else
1862 llvm_unreachable("Invalid element type!");
1863
1864 SemaRef.Diag(IList->getBeginLoc(),
1865 SemaRef.Context.getTypeSize(VT) > 64
1866 ? diag::note_neon_vector_initializer_non_portable_q
1867 : diag::note_neon_vector_initializer_non_portable)
1868 << typeCode << typeSize;
1869 }
1870
1871 return;
1872 }
1873
1874 InitializedEntity ElementEntity =
1875 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
1876
1877 // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1878 for (unsigned i = 0; i < maxElements; ++i) {
1879 // Don't attempt to go past the end of the init list
1880 if (Index >= IList->getNumInits())
1881 break;
1882
1883 ElementEntity.setElementIndex(Index);
1884
1885 QualType IType = IList->getInit(Init: Index)->getType();
1886 if (!IType->isVectorType()) {
1887 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
1888 StructuredList, StructuredIndex);
1889 ++numEltsInit;
1890 } else {
1891 QualType VecType;
1892 const VectorType *IVT = IType->castAs<VectorType>();
1893 unsigned numIElts = IVT->getNumElements();
1894
1895 if (IType->isExtVectorType())
1896 VecType = SemaRef.Context.getExtVectorType(VectorType: elementType, NumElts: numIElts);
1897 else
1898 VecType = SemaRef.Context.getVectorType(VectorType: elementType, NumElts: numIElts,
1899 VecKind: IVT->getVectorKind());
1900 CheckSubElementType(Entity: ElementEntity, IList, ElemType: VecType, Index,
1901 StructuredList, StructuredIndex);
1902 numEltsInit += numIElts;
1903 }
1904 }
1905
1906 // OpenCL and HLSL require all elements to be initialized.
1907 if (numEltsInit != maxElements) {
1908 if (!VerifyOnly)
1909 SemaRef.Diag(IList->getBeginLoc(),
1910 diag::err_vector_incorrect_num_initializers)
1911 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1912 hadError = true;
1913 }
1914}
1915
1916/// Check if the type of a class element has an accessible destructor, and marks
1917/// it referenced. Returns true if we shouldn't form a reference to the
1918/// destructor.
1919///
1920/// Aggregate initialization requires a class element's destructor be
1921/// accessible per 11.6.1 [dcl.init.aggr]:
1922///
1923/// The destructor for each element of class type is potentially invoked
1924/// (15.4 [class.dtor]) from the context where the aggregate initialization
1925/// occurs.
1926static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1927 Sema &SemaRef) {
1928 auto *CXXRD = ElementType->getAsCXXRecordDecl();
1929 if (!CXXRD)
1930 return false;
1931
1932 CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Class: CXXRD);
1933 SemaRef.CheckDestructorAccess(Loc, Destructor,
1934 SemaRef.PDiag(diag::err_access_dtor_temp)
1935 << ElementType);
1936 SemaRef.MarkFunctionReferenced(Loc, Destructor);
1937 return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1938}
1939
1940void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1941 InitListExpr *IList, QualType &DeclType,
1942 llvm::APSInt elementIndex,
1943 bool SubobjectIsDesignatorContext,
1944 unsigned &Index,
1945 InitListExpr *StructuredList,
1946 unsigned &StructuredIndex) {
1947 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(T: DeclType);
1948
1949 if (!VerifyOnly) {
1950 if (checkDestructorReference(ElementType: arrayType->getElementType(),
1951 Loc: IList->getEndLoc(), SemaRef)) {
1952 hadError = true;
1953 return;
1954 }
1955 }
1956
1957 // Check for the special-case of initializing an array with a string.
1958 if (Index < IList->getNumInits()) {
1959 if (IsStringInit(Init: IList->getInit(Init: Index), AT: arrayType, Context&: SemaRef.Context) ==
1960 SIF_None) {
1961 // We place the string literal directly into the resulting
1962 // initializer list. This is the only place where the structure
1963 // of the structured initializer list doesn't match exactly,
1964 // because doing so would involve allocating one character
1965 // constant for each string.
1966 // FIXME: Should we do these checks in verify-only mode too?
1967 if (!VerifyOnly)
1968 CheckStringInit(Str: IList->getInit(Init: Index), DeclT&: DeclType, AT: arrayType, S&: SemaRef,
1969 CheckC23ConstexprInit: SemaRef.getLangOpts().C23 &&
1970 initializingConstexprVariable(Entity));
1971 if (StructuredList) {
1972 UpdateStructuredListElement(StructuredList, StructuredIndex,
1973 expr: IList->getInit(Init: Index));
1974 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: StructuredIndex);
1975 }
1976 ++Index;
1977 if (AggrDeductionCandidateParamTypes)
1978 AggrDeductionCandidateParamTypes->push_back(Elt: DeclType);
1979 return;
1980 }
1981 }
1982 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Val: arrayType)) {
1983 // Check for VLAs; in standard C it would be possible to check this
1984 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1985 // them in all sorts of strange places).
1986 bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1987 if (!VerifyOnly) {
1988 // C23 6.7.10p4: An entity of variable length array type shall not be
1989 // initialized except by an empty initializer.
1990 //
1991 // The C extension warnings are issued from ParseBraceInitializer() and
1992 // do not need to be issued here. However, we continue to issue an error
1993 // in the case there are initializers or we are compiling C++. We allow
1994 // use of VLAs in C++, but it's not clear we want to allow {} to zero
1995 // init a VLA in C++ in all cases (such as with non-trivial constructors).
1996 // FIXME: should we allow this construct in C++ when it makes sense to do
1997 // so?
1998 if (HasErr)
1999 SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
2000 diag::err_variable_object_no_init)
2001 << VAT->getSizeExpr()->getSourceRange();
2002 }
2003 hadError = HasErr;
2004 ++Index;
2005 ++StructuredIndex;
2006 return;
2007 }
2008
2009 // We might know the maximum number of elements in advance.
2010 llvm::APSInt maxElements(elementIndex.getBitWidth(),
2011 elementIndex.isUnsigned());
2012 bool maxElementsKnown = false;
2013 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: arrayType)) {
2014 maxElements = CAT->getSize();
2015 elementIndex = elementIndex.extOrTrunc(width: maxElements.getBitWidth());
2016 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2017 maxElementsKnown = true;
2018 }
2019
2020 QualType elementType = arrayType->getElementType();
2021 while (Index < IList->getNumInits()) {
2022 Expr *Init = IList->getInit(Init: Index);
2023 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) {
2024 // If we're not the subobject that matches up with the '{' for
2025 // the designator, we shouldn't be handling the
2026 // designator. Return immediately.
2027 if (!SubobjectIsDesignatorContext)
2028 return;
2029
2030 // Handle this designated initializer. elementIndex will be
2031 // updated to be the next array element we'll initialize.
2032 if (CheckDesignatedInitializer(Entity, IList, DIE, DesigIdx: 0,
2033 CurrentObjectType&: DeclType, NextField: nullptr, NextElementIndex: &elementIndex, Index,
2034 StructuredList, StructuredIndex, FinishSubobjectInit: true,
2035 TopLevelObject: false)) {
2036 hadError = true;
2037 continue;
2038 }
2039
2040 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2041 maxElements = maxElements.extend(width: elementIndex.getBitWidth());
2042 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2043 elementIndex = elementIndex.extend(width: maxElements.getBitWidth());
2044 elementIndex.setIsUnsigned(maxElements.isUnsigned());
2045
2046 // If the array is of incomplete type, keep track of the number of
2047 // elements in the initializer.
2048 if (!maxElementsKnown && elementIndex > maxElements)
2049 maxElements = elementIndex;
2050
2051 continue;
2052 }
2053
2054 // If we know the maximum number of elements, and we've already
2055 // hit it, stop consuming elements in the initializer list.
2056 if (maxElementsKnown && elementIndex == maxElements)
2057 break;
2058
2059 InitializedEntity ElementEntity =
2060 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: StructuredIndex,
2061 Parent: Entity);
2062 // Check this element.
2063 CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index,
2064 StructuredList, StructuredIndex);
2065 ++elementIndex;
2066
2067 // If the array is of incomplete type, keep track of the number of
2068 // elements in the initializer.
2069 if (!maxElementsKnown && elementIndex > maxElements)
2070 maxElements = elementIndex;
2071 }
2072 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2073 // If this is an incomplete array type, the actual type needs to
2074 // be calculated here.
2075 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2076 if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2077 // Sizing an array implicitly to zero is not allowed by ISO C,
2078 // but is supported by GNU.
2079 SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2080 }
2081
2082 DeclType = SemaRef.Context.getConstantArrayType(
2083 EltTy: elementType, ArySize: maxElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
2084 }
2085 if (!hadError) {
2086 // If there are any members of the array that get value-initialized, check
2087 // that is possible. That happens if we know the bound and don't have
2088 // enough elements, or if we're performing an array new with an unknown
2089 // bound.
2090 if ((maxElementsKnown && elementIndex < maxElements) ||
2091 Entity.isVariableLengthArrayNew())
2092 CheckEmptyInitializable(
2093 Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity),
2094 Loc: IList->getEndLoc());
2095 }
2096}
2097
2098bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2099 Expr *InitExpr,
2100 FieldDecl *Field,
2101 bool TopLevelObject) {
2102 // Handle GNU flexible array initializers.
2103 unsigned FlexArrayDiag;
2104 if (isa<InitListExpr>(Val: InitExpr) &&
2105 cast<InitListExpr>(Val: InitExpr)->getNumInits() == 0) {
2106 // Empty flexible array init always allowed as an extension
2107 FlexArrayDiag = diag::ext_flexible_array_init;
2108 } else if (!TopLevelObject) {
2109 // Disallow flexible array init on non-top-level object
2110 FlexArrayDiag = diag::err_flexible_array_init;
2111 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2112 // Disallow flexible array init on anything which is not a variable.
2113 FlexArrayDiag = diag::err_flexible_array_init;
2114 } else if (cast<VarDecl>(Val: Entity.getDecl())->hasLocalStorage()) {
2115 // Disallow flexible array init on local variables.
2116 FlexArrayDiag = diag::err_flexible_array_init;
2117 } else {
2118 // Allow other cases.
2119 FlexArrayDiag = diag::ext_flexible_array_init;
2120 }
2121
2122 if (!VerifyOnly) {
2123 SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2124 << InitExpr->getBeginLoc();
2125 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2126 << Field;
2127 }
2128
2129 return FlexArrayDiag != diag::ext_flexible_array_init;
2130}
2131
2132void InitListChecker::CheckStructUnionTypes(
2133 const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2134 CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,
2135 bool SubobjectIsDesignatorContext, unsigned &Index,
2136 InitListExpr *StructuredList, unsigned &StructuredIndex,
2137 bool TopLevelObject) {
2138 const RecordDecl *RD = getRecordDecl(DeclType);
2139
2140 // If the record is invalid, some of it's members are invalid. To avoid
2141 // confusion, we forgo checking the initializer for the entire record.
2142 if (RD->isInvalidDecl()) {
2143 // Assume it was supposed to consume a single initializer.
2144 ++Index;
2145 hadError = true;
2146 return;
2147 }
2148
2149 if (RD->isUnion() && IList->getNumInits() == 0) {
2150 if (!VerifyOnly)
2151 for (FieldDecl *FD : RD->fields()) {
2152 QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2153 if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) {
2154 hadError = true;
2155 return;
2156 }
2157 }
2158
2159 // If there's a default initializer, use it.
2160 if (isa<CXXRecordDecl>(Val: RD) &&
2161 cast<CXXRecordDecl>(Val: RD)->hasInClassInitializer()) {
2162 if (!StructuredList)
2163 return;
2164 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2165 Field != FieldEnd; ++Field) {
2166 if (Field->hasInClassInitializer()) {
2167 StructuredList->setInitializedFieldInUnion(*Field);
2168 // FIXME: Actually build a CXXDefaultInitExpr?
2169 return;
2170 }
2171 }
2172 }
2173
2174 // Value-initialize the first member of the union that isn't an unnamed
2175 // bitfield.
2176 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2177 Field != FieldEnd; ++Field) {
2178 if (!Field->isUnnamedBitField()) {
2179 CheckEmptyInitializable(
2180 Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity),
2181 Loc: IList->getEndLoc());
2182 if (StructuredList)
2183 StructuredList->setInitializedFieldInUnion(*Field);
2184 break;
2185 }
2186 }
2187 return;
2188 }
2189
2190 bool InitializedSomething = false;
2191
2192 // If we have any base classes, they are initialized prior to the fields.
2193 for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2194 auto &Base = *I;
2195 Expr *Init = Index < IList->getNumInits() ? IList->getInit(Init: Index) : nullptr;
2196
2197 // Designated inits always initialize fields, so if we see one, all
2198 // remaining base classes have no explicit initializer.
2199 if (Init && isa<DesignatedInitExpr>(Val: Init))
2200 Init = nullptr;
2201
2202 // C++ [over.match.class.deduct]p1.6:
2203 // each non-trailing aggregate element that is a pack expansion is assumed
2204 // to correspond to no elements of the initializer list, and (1.7) a
2205 // trailing aggregate element that is a pack expansion is assumed to
2206 // correspond to all remaining elements of the initializer list (if any).
2207
2208 // C++ [over.match.class.deduct]p1.9:
2209 // ... except that additional parameter packs of the form P_j... are
2210 // inserted into the parameter list in their original aggregate element
2211 // position corresponding to each non-trailing aggregate element of
2212 // type P_j that was skipped because it was a parameter pack, and the
2213 // trailing sequence of parameters corresponding to a trailing
2214 // aggregate element that is a pack expansion (if any) is replaced
2215 // by a single parameter of the form T_n....
2216 if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2217 AggrDeductionCandidateParamTypes->push_back(
2218 Elt: SemaRef.Context.getPackExpansionType(Pattern: Base.getType(), NumExpansions: std::nullopt));
2219
2220 // Trailing pack expansion
2221 if (I + 1 == E && RD->field_empty()) {
2222 if (Index < IList->getNumInits())
2223 Index = IList->getNumInits();
2224 return;
2225 }
2226
2227 continue;
2228 }
2229
2230 SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2231 InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2232 Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity);
2233 if (Init) {
2234 CheckSubElementType(Entity: BaseEntity, IList, ElemType: Base.getType(), Index,
2235 StructuredList, StructuredIndex);
2236 InitializedSomething = true;
2237 } else {
2238 CheckEmptyInitializable(Entity: BaseEntity, Loc: InitLoc);
2239 }
2240
2241 if (!VerifyOnly)
2242 if (checkDestructorReference(ElementType: Base.getType(), Loc: InitLoc, SemaRef)) {
2243 hadError = true;
2244 return;
2245 }
2246 }
2247
2248 // If structDecl is a forward declaration, this loop won't do
2249 // anything except look at designated initializers; That's okay,
2250 // because an error should get printed out elsewhere. It might be
2251 // worthwhile to skip over the rest of the initializer, though.
2252 RecordDecl::field_iterator FieldEnd = RD->field_end();
2253 size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2254 return isa<FieldDecl>(Val: D) || isa<RecordDecl>(Val: D);
2255 });
2256 bool HasDesignatedInit = false;
2257
2258 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2259
2260 while (Index < IList->getNumInits()) {
2261 Expr *Init = IList->getInit(Init: Index);
2262 SourceLocation InitLoc = Init->getBeginLoc();
2263
2264 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) {
2265 // If we're not the subobject that matches up with the '{' for
2266 // the designator, we shouldn't be handling the
2267 // designator. Return immediately.
2268 if (!SubobjectIsDesignatorContext)
2269 return;
2270
2271 HasDesignatedInit = true;
2272
2273 // Handle this designated initializer. Field will be updated to
2274 // the next field that we'll be initializing.
2275 bool DesignatedInitFailed = CheckDesignatedInitializer(
2276 Entity, IList, DIE, DesigIdx: 0, CurrentObjectType&: DeclType, NextField: &Field, NextElementIndex: nullptr, Index,
2277 StructuredList, StructuredIndex, FinishSubobjectInit: true, TopLevelObject);
2278 if (DesignatedInitFailed)
2279 hadError = true;
2280
2281 // Find the field named by the designated initializer.
2282 DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: 0);
2283 if (!VerifyOnly && D->isFieldDesignator()) {
2284 FieldDecl *F = D->getFieldDecl();
2285 InitializedFields.insert(Ptr: F);
2286 if (!DesignatedInitFailed) {
2287 QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2288 if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) {
2289 hadError = true;
2290 return;
2291 }
2292 }
2293 }
2294
2295 InitializedSomething = true;
2296 continue;
2297 }
2298
2299 // Check if this is an initializer of forms:
2300 //
2301 // struct foo f = {};
2302 // struct foo g = {0};
2303 //
2304 // These are okay for randomized structures. [C99 6.7.8p19]
2305 //
2306 // Also, if there is only one element in the structure, we allow something
2307 // like this, because it's really not randomized in the traditional sense.
2308 //
2309 // struct foo h = {bar};
2310 auto IsZeroInitializer = [&](const Expr *I) {
2311 if (IList->getNumInits() == 1) {
2312 if (NumRecordDecls == 1)
2313 return true;
2314 if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2315 return IL->getValue().isZero();
2316 }
2317 return false;
2318 };
2319
2320 // Don't allow non-designated initializers on randomized structures.
2321 if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2322 if (!VerifyOnly)
2323 SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2324 hadError = true;
2325 break;
2326 }
2327
2328 if (Field == FieldEnd) {
2329 // We've run out of fields. We're done.
2330 break;
2331 }
2332
2333 // We've already initialized a member of a union. We can stop entirely.
2334 if (InitializedSomething && RD->isUnion())
2335 return;
2336
2337 // Stop if we've hit a flexible array member.
2338 if (Field->getType()->isIncompleteArrayType())
2339 break;
2340
2341 if (Field->isUnnamedBitField()) {
2342 // Don't initialize unnamed bitfields, e.g. "int : 20;"
2343 ++Field;
2344 continue;
2345 }
2346
2347 // Make sure we can use this declaration.
2348 bool InvalidUse;
2349 if (VerifyOnly)
2350 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2351 else
2352 InvalidUse = SemaRef.DiagnoseUseOfDecl(
2353 D: *Field, Locs: IList->getInit(Init: Index)->getBeginLoc());
2354 if (InvalidUse) {
2355 ++Index;
2356 ++Field;
2357 hadError = true;
2358 continue;
2359 }
2360
2361 if (!VerifyOnly) {
2362 QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2363 if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) {
2364 hadError = true;
2365 return;
2366 }
2367 }
2368
2369 InitializedEntity MemberEntity =
2370 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2371 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2372 StructuredList, StructuredIndex);
2373 InitializedSomething = true;
2374 InitializedFields.insert(Ptr: *Field);
2375
2376 if (RD->isUnion() && StructuredList) {
2377 // Initialize the first field within the union.
2378 StructuredList->setInitializedFieldInUnion(*Field);
2379 }
2380
2381 ++Field;
2382 }
2383
2384 // Emit warnings for missing struct field initializers.
2385 // This check is disabled for designated initializers in C.
2386 // This matches gcc behaviour.
2387 bool IsCDesignatedInitializer =
2388 HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus;
2389 if (!VerifyOnly && InitializedSomething && !RD->isUnion() &&
2390 !IList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) &&
2391 !IsCDesignatedInitializer) {
2392 // It is possible we have one or more unnamed bitfields remaining.
2393 // Find first (if any) named field and emit warning.
2394 for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2395 : Field,
2396 end = RD->field_end();
2397 it != end; ++it) {
2398 if (HasDesignatedInit && InitializedFields.count(Ptr: *it))
2399 continue;
2400
2401 if (!it->isUnnamedBitField() && !it->hasInClassInitializer() &&
2402 !it->getType()->isIncompleteArrayType()) {
2403 auto Diag = HasDesignatedInit
2404 ? diag::warn_missing_designated_field_initializers
2405 : diag::warn_missing_field_initializers;
2406 SemaRef.Diag(IList->getSourceRange().getEnd(), Diag) << *it;
2407 break;
2408 }
2409 }
2410 }
2411
2412 // Check that any remaining fields can be value-initialized if we're not
2413 // building a structured list. (If we are, we'll check this later.)
2414 if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2415 !Field->getType()->isIncompleteArrayType()) {
2416 for (; Field != FieldEnd && !hadError; ++Field) {
2417 if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer())
2418 CheckEmptyInitializable(
2419 Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity),
2420 Loc: IList->getEndLoc());
2421 }
2422 }
2423
2424 // Check that the types of the remaining fields have accessible destructors.
2425 if (!VerifyOnly) {
2426 // If the initializer expression has a designated initializer, check the
2427 // elements for which a designated initializer is not provided too.
2428 RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2429 : Field;
2430 for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2431 QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2432 if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) {
2433 hadError = true;
2434 return;
2435 }
2436 }
2437 }
2438
2439 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2440 Index >= IList->getNumInits())
2441 return;
2442
2443 if (CheckFlexibleArrayInit(Entity, InitExpr: IList->getInit(Init: Index), Field: *Field,
2444 TopLevelObject)) {
2445 hadError = true;
2446 ++Index;
2447 return;
2448 }
2449
2450 InitializedEntity MemberEntity =
2451 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2452
2453 if (isa<InitListExpr>(Val: IList->getInit(Init: Index)) ||
2454 AggrDeductionCandidateParamTypes)
2455 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2456 StructuredList, StructuredIndex);
2457 else
2458 CheckImplicitInitList(Entity: MemberEntity, ParentIList: IList, T: Field->getType(), Index,
2459 StructuredList, StructuredIndex);
2460
2461 if (RD->isUnion() && StructuredList) {
2462 // Initialize the first field within the union.
2463 StructuredList->setInitializedFieldInUnion(*Field);
2464 }
2465}
2466
2467/// Expand a field designator that refers to a member of an
2468/// anonymous struct or union into a series of field designators that
2469/// refers to the field within the appropriate subobject.
2470///
2471static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2472 DesignatedInitExpr *DIE,
2473 unsigned DesigIdx,
2474 IndirectFieldDecl *IndirectField) {
2475 typedef DesignatedInitExpr::Designator Designator;
2476
2477 // Build the replacement designators.
2478 SmallVector<Designator, 4> Replacements;
2479 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2480 PE = IndirectField->chain_end(); PI != PE; ++PI) {
2481 if (PI + 1 == PE)
2482 Replacements.push_back(Elt: Designator::CreateFieldDesignator(
2483 FieldName: (IdentifierInfo *)nullptr, DotLoc: DIE->getDesignator(Idx: DesigIdx)->getDotLoc(),
2484 FieldLoc: DIE->getDesignator(Idx: DesigIdx)->getFieldLoc()));
2485 else
2486 Replacements.push_back(Elt: Designator::CreateFieldDesignator(
2487 FieldName: (IdentifierInfo *)nullptr, DotLoc: SourceLocation(), FieldLoc: SourceLocation()));
2488 assert(isa<FieldDecl>(*PI));
2489 Replacements.back().setFieldDecl(cast<FieldDecl>(Val: *PI));
2490 }
2491
2492 // Expand the current designator into the set of replacement
2493 // designators, so we have a full subobject path down to where the
2494 // member of the anonymous struct/union is actually stored.
2495 DIE->ExpandDesignator(C: SemaRef.Context, Idx: DesigIdx, First: &Replacements[0],
2496 Last: &Replacements[0] + Replacements.size());
2497}
2498
2499static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2500 DesignatedInitExpr *DIE) {
2501 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2502 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2503 for (unsigned I = 0; I < NumIndexExprs; ++I)
2504 IndexExprs[I] = DIE->getSubExpr(Idx: I + 1);
2505 return DesignatedInitExpr::Create(C: SemaRef.Context, Designators: DIE->designators(),
2506 IndexExprs,
2507 EqualOrColonLoc: DIE->getEqualOrColonLoc(),
2508 GNUSyntax: DIE->usesGNUSyntax(), Init: DIE->getInit());
2509}
2510
2511namespace {
2512
2513// Callback to only accept typo corrections that are for field members of
2514// the given struct or union.
2515class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2516 public:
2517 explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2518 : Record(RD) {}
2519
2520 bool ValidateCandidate(const TypoCorrection &candidate) override {
2521 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2522 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2523 }
2524
2525 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2526 return std::make_unique<FieldInitializerValidatorCCC>(args&: *this);
2527 }
2528
2529 private:
2530 const RecordDecl *Record;
2531};
2532
2533} // end anonymous namespace
2534
2535/// Check the well-formedness of a C99 designated initializer.
2536///
2537/// Determines whether the designated initializer @p DIE, which
2538/// resides at the given @p Index within the initializer list @p
2539/// IList, is well-formed for a current object of type @p DeclType
2540/// (C99 6.7.8). The actual subobject that this designator refers to
2541/// within the current subobject is returned in either
2542/// @p NextField or @p NextElementIndex (whichever is appropriate).
2543///
2544/// @param IList The initializer list in which this designated
2545/// initializer occurs.
2546///
2547/// @param DIE The designated initializer expression.
2548///
2549/// @param DesigIdx The index of the current designator.
2550///
2551/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2552/// into which the designation in @p DIE should refer.
2553///
2554/// @param NextField If non-NULL and the first designator in @p DIE is
2555/// a field, this will be set to the field declaration corresponding
2556/// to the field named by the designator. On input, this is expected to be
2557/// the next field that would be initialized in the absence of designation,
2558/// if the complete object being initialized is a struct.
2559///
2560/// @param NextElementIndex If non-NULL and the first designator in @p
2561/// DIE is an array designator or GNU array-range designator, this
2562/// will be set to the last index initialized by this designator.
2563///
2564/// @param Index Index into @p IList where the designated initializer
2565/// @p DIE occurs.
2566///
2567/// @param StructuredList The initializer list expression that
2568/// describes all of the subobject initializers in the order they'll
2569/// actually be initialized.
2570///
2571/// @returns true if there was an error, false otherwise.
2572bool
2573InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2574 InitListExpr *IList,
2575 DesignatedInitExpr *DIE,
2576 unsigned DesigIdx,
2577 QualType &CurrentObjectType,
2578 RecordDecl::field_iterator *NextField,
2579 llvm::APSInt *NextElementIndex,
2580 unsigned &Index,
2581 InitListExpr *StructuredList,
2582 unsigned &StructuredIndex,
2583 bool FinishSubobjectInit,
2584 bool TopLevelObject) {
2585 if (DesigIdx == DIE->size()) {
2586 // C++20 designated initialization can result in direct-list-initialization
2587 // of the designated subobject. This is the only way that we can end up
2588 // performing direct initialization as part of aggregate initialization, so
2589 // it needs special handling.
2590 if (DIE->isDirectInit()) {
2591 Expr *Init = DIE->getInit();
2592 assert(isa<InitListExpr>(Init) &&
2593 "designator result in direct non-list initialization?");
2594 InitializationKind Kind = InitializationKind::CreateDirectList(
2595 DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2596 InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2597 /*TopLevelOfInitList*/ true);
2598 if (StructuredList) {
2599 ExprResult Result = VerifyOnly
2600 ? getDummyInit()
2601 : Seq.Perform(S&: SemaRef, Entity, Kind, Args: Init);
2602 UpdateStructuredListElement(StructuredList, StructuredIndex,
2603 expr: Result.get());
2604 }
2605 ++Index;
2606 if (AggrDeductionCandidateParamTypes)
2607 AggrDeductionCandidateParamTypes->push_back(Elt: CurrentObjectType);
2608 return !Seq;
2609 }
2610
2611 // Check the actual initialization for the designated object type.
2612 bool prevHadError = hadError;
2613
2614 // Temporarily remove the designator expression from the
2615 // initializer list that the child calls see, so that we don't try
2616 // to re-process the designator.
2617 unsigned OldIndex = Index;
2618 IList->setInit(Init: OldIndex, expr: DIE->getInit());
2619
2620 CheckSubElementType(Entity, IList, ElemType: CurrentObjectType, Index, StructuredList,
2621 StructuredIndex, /*DirectlyDesignated=*/true);
2622
2623 // Restore the designated initializer expression in the syntactic
2624 // form of the initializer list.
2625 if (IList->getInit(Init: OldIndex) != DIE->getInit())
2626 DIE->setInit(IList->getInit(Init: OldIndex));
2627 IList->setInit(OldIndex, DIE);
2628
2629 return hadError && !prevHadError;
2630 }
2631
2632 DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: DesigIdx);
2633 bool IsFirstDesignator = (DesigIdx == 0);
2634 if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2635 // Determine the structural initializer list that corresponds to the
2636 // current subobject.
2637 if (IsFirstDesignator)
2638 StructuredList = FullyStructuredList;
2639 else {
2640 Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2641 StructuredList->getInit(Init: StructuredIndex) : nullptr;
2642 if (!ExistingInit && StructuredList->hasArrayFiller())
2643 ExistingInit = StructuredList->getArrayFiller();
2644
2645 if (!ExistingInit)
2646 StructuredList = getStructuredSubobjectInit(
2647 IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2648 InitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2649 else if (InitListExpr *Result = dyn_cast<InitListExpr>(Val: ExistingInit))
2650 StructuredList = Result;
2651 else {
2652 // We are creating an initializer list that initializes the
2653 // subobjects of the current object, but there was already an
2654 // initialization that completely initialized the current
2655 // subobject, e.g., by a compound literal:
2656 //
2657 // struct X { int a, b; };
2658 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2659 //
2660 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2661 // designated initializer re-initializes only its current object
2662 // subobject [0].b.
2663 diagnoseInitOverride(OldInit: ExistingInit,
2664 NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2665 /*UnionOverride=*/false,
2666 /*FullyOverwritten=*/false);
2667
2668 if (!VerifyOnly) {
2669 if (DesignatedInitUpdateExpr *E =
2670 dyn_cast<DesignatedInitUpdateExpr>(Val: ExistingInit))
2671 StructuredList = E->getUpdater();
2672 else {
2673 DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2674 DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2675 ExistingInit, DIE->getEndLoc());
2676 StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2677 StructuredList = DIUE->getUpdater();
2678 }
2679 } else {
2680 // We don't need to track the structured representation of a
2681 // designated init update of an already-fully-initialized object in
2682 // verify-only mode. The only reason we would need the structure is
2683 // to determine where the uninitialized "holes" are, and in this
2684 // case, we know there aren't any and we can't introduce any.
2685 StructuredList = nullptr;
2686 }
2687 }
2688 }
2689 }
2690
2691 if (D->isFieldDesignator()) {
2692 // C99 6.7.8p7:
2693 //
2694 // If a designator has the form
2695 //
2696 // . identifier
2697 //
2698 // then the current object (defined below) shall have
2699 // structure or union type and the identifier shall be the
2700 // name of a member of that type.
2701 RecordDecl *RD = getRecordDecl(DeclType: CurrentObjectType);
2702 if (!RD) {
2703 SourceLocation Loc = D->getDotLoc();
2704 if (Loc.isInvalid())
2705 Loc = D->getFieldLoc();
2706 if (!VerifyOnly)
2707 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2708 << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2709 ++Index;
2710 return true;
2711 }
2712
2713 FieldDecl *KnownField = D->getFieldDecl();
2714 if (!KnownField) {
2715 const IdentifierInfo *FieldName = D->getFieldName();
2716 ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(ClassDecl: RD, MemberOrBase: FieldName);
2717 if (auto *FD = dyn_cast_if_present<FieldDecl>(Val: VD)) {
2718 KnownField = FD;
2719 } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(Val: VD)) {
2720 // In verify mode, don't modify the original.
2721 if (VerifyOnly)
2722 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2723 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IndirectField: IFD);
2724 D = DIE->getDesignator(Idx: DesigIdx);
2725 KnownField = cast<FieldDecl>(Val: *IFD->chain_begin());
2726 }
2727 if (!KnownField) {
2728 if (VerifyOnly) {
2729 ++Index;
2730 return true; // No typo correction when just trying this out.
2731 }
2732
2733 // We found a placeholder variable
2734 if (SemaRef.DiagRedefinedPlaceholderFieldDecl(Loc: DIE->getBeginLoc(), ClassDecl: RD,
2735 Name: FieldName)) {
2736 ++Index;
2737 return true;
2738 }
2739 // Name lookup found something, but it wasn't a field.
2740 if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2741 !Lookup.empty()) {
2742 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2743 << FieldName;
2744 SemaRef.Diag(Lookup.front()->getLocation(),
2745 diag::note_field_designator_found);
2746 ++Index;
2747 return true;
2748 }
2749
2750 // Name lookup didn't find anything.
2751 // Determine whether this was a typo for another field name.
2752 FieldInitializerValidatorCCC CCC(RD);
2753 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2754 DeclarationNameInfo(FieldName, D->getFieldLoc()),
2755 Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2756 Sema::CTK_ErrorRecovery, RD)) {
2757 SemaRef.diagnoseTypo(
2758 Corrected,
2759 SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2760 << FieldName << CurrentObjectType);
2761 KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2762 hadError = true;
2763 } else {
2764 // Typo correction didn't find anything.
2765 SourceLocation Loc = D->getFieldLoc();
2766
2767 // The loc can be invalid with a "null" designator (i.e. an anonymous
2768 // union/struct). Do our best to approximate the location.
2769 if (Loc.isInvalid())
2770 Loc = IList->getBeginLoc();
2771
2772 SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2773 << FieldName << CurrentObjectType << DIE->getSourceRange();
2774 ++Index;
2775 return true;
2776 }
2777 }
2778 }
2779
2780 unsigned NumBases = 0;
2781 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
2782 NumBases = CXXRD->getNumBases();
2783
2784 unsigned FieldIndex = NumBases;
2785
2786 for (auto *FI : RD->fields()) {
2787 if (FI->isUnnamedBitField())
2788 continue;
2789 if (declaresSameEntity(KnownField, FI)) {
2790 KnownField = FI;
2791 break;
2792 }
2793 ++FieldIndex;
2794 }
2795
2796 RecordDecl::field_iterator Field =
2797 RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2798
2799 // All of the fields of a union are located at the same place in
2800 // the initializer list.
2801 if (RD->isUnion()) {
2802 FieldIndex = 0;
2803 if (StructuredList) {
2804 FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2805 if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2806 assert(StructuredList->getNumInits() == 1
2807 && "A union should never have more than one initializer!");
2808
2809 Expr *ExistingInit = StructuredList->getInit(Init: 0);
2810 if (ExistingInit) {
2811 // We're about to throw away an initializer, emit warning.
2812 diagnoseInitOverride(
2813 OldInit: ExistingInit, NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2814 /*UnionOverride=*/true,
2815 /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2816 : true);
2817 }
2818
2819 // remove existing initializer
2820 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: 0);
2821 StructuredList->setInitializedFieldInUnion(nullptr);
2822 }
2823
2824 StructuredList->setInitializedFieldInUnion(*Field);
2825 }
2826 }
2827
2828 // Make sure we can use this declaration.
2829 bool InvalidUse;
2830 if (VerifyOnly)
2831 InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2832 else
2833 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2834 if (InvalidUse) {
2835 ++Index;
2836 return true;
2837 }
2838
2839 // C++20 [dcl.init.list]p3:
2840 // The ordered identifiers in the designators of the designated-
2841 // initializer-list shall form a subsequence of the ordered identifiers
2842 // in the direct non-static data members of T.
2843 //
2844 // Note that this is not a condition on forming the aggregate
2845 // initialization, only on actually performing initialization,
2846 // so it is not checked in VerifyOnly mode.
2847 //
2848 // FIXME: This is the only reordering diagnostic we produce, and it only
2849 // catches cases where we have a top-level field designator that jumps
2850 // backwards. This is the only such case that is reachable in an
2851 // otherwise-valid C++20 program, so is the only case that's required for
2852 // conformance, but for consistency, we should diagnose all the other
2853 // cases where a designator takes us backwards too.
2854 if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2855 NextField &&
2856 (*NextField == RD->field_end() ||
2857 (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2858 // Find the field that we just initialized.
2859 FieldDecl *PrevField = nullptr;
2860 for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2861 if (FI->isUnnamedBitField())
2862 continue;
2863 if (*NextField != RD->field_end() &&
2864 declaresSameEntity(*FI, **NextField))
2865 break;
2866 PrevField = *FI;
2867 }
2868
2869 if (PrevField &&
2870 PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2871 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2872 diag::ext_designated_init_reordered)
2873 << KnownField << PrevField << DIE->getSourceRange();
2874
2875 unsigned OldIndex = StructuredIndex - 1;
2876 if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2877 if (Expr *PrevInit = StructuredList->getInit(Init: OldIndex)) {
2878 SemaRef.Diag(PrevInit->getBeginLoc(),
2879 diag::note_previous_field_init)
2880 << PrevField << PrevInit->getSourceRange();
2881 }
2882 }
2883 }
2884 }
2885
2886
2887 // Update the designator with the field declaration.
2888 if (!VerifyOnly)
2889 D->setFieldDecl(*Field);
2890
2891 // Make sure that our non-designated initializer list has space
2892 // for a subobject corresponding to this field.
2893 if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2894 StructuredList->resizeInits(Context: SemaRef.Context, NumInits: FieldIndex + 1);
2895
2896 // This designator names a flexible array member.
2897 if (Field->getType()->isIncompleteArrayType()) {
2898 bool Invalid = false;
2899 if ((DesigIdx + 1) != DIE->size()) {
2900 // We can't designate an object within the flexible array
2901 // member (because GCC doesn't allow it).
2902 if (!VerifyOnly) {
2903 DesignatedInitExpr::Designator *NextD
2904 = DIE->getDesignator(Idx: DesigIdx + 1);
2905 SemaRef.Diag(NextD->getBeginLoc(),
2906 diag::err_designator_into_flexible_array_member)
2907 << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2908 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2909 << *Field;
2910 }
2911 Invalid = true;
2912 }
2913
2914 if (!hadError && !isa<InitListExpr>(Val: DIE->getInit()) &&
2915 !isa<StringLiteral>(Val: DIE->getInit())) {
2916 // The initializer is not an initializer list.
2917 if (!VerifyOnly) {
2918 SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2919 diag::err_flexible_array_init_needs_braces)
2920 << DIE->getInit()->getSourceRange();
2921 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2922 << *Field;
2923 }
2924 Invalid = true;
2925 }
2926
2927 // Check GNU flexible array initializer.
2928 if (!Invalid && CheckFlexibleArrayInit(Entity, InitExpr: DIE->getInit(), Field: *Field,
2929 TopLevelObject))
2930 Invalid = true;
2931
2932 if (Invalid) {
2933 ++Index;
2934 return true;
2935 }
2936
2937 // Initialize the array.
2938 bool prevHadError = hadError;
2939 unsigned newStructuredIndex = FieldIndex;
2940 unsigned OldIndex = Index;
2941 IList->setInit(Init: Index, expr: DIE->getInit());
2942
2943 InitializedEntity MemberEntity =
2944 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2945 CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index,
2946 StructuredList, StructuredIndex&: newStructuredIndex);
2947
2948 IList->setInit(OldIndex, DIE);
2949 if (hadError && !prevHadError) {
2950 ++Field;
2951 ++FieldIndex;
2952 if (NextField)
2953 *NextField = Field;
2954 StructuredIndex = FieldIndex;
2955 return true;
2956 }
2957 } else {
2958 // Recurse to check later designated subobjects.
2959 QualType FieldType = Field->getType();
2960 unsigned newStructuredIndex = FieldIndex;
2961
2962 InitializedEntity MemberEntity =
2963 InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity);
2964 if (CheckDesignatedInitializer(Entity: MemberEntity, IList, DIE, DesigIdx: DesigIdx + 1,
2965 CurrentObjectType&: FieldType, NextField: nullptr, NextElementIndex: nullptr, Index,
2966 StructuredList, StructuredIndex&: newStructuredIndex,
2967 FinishSubobjectInit, TopLevelObject: false))
2968 return true;
2969 }
2970
2971 // Find the position of the next field to be initialized in this
2972 // subobject.
2973 ++Field;
2974 ++FieldIndex;
2975
2976 // If this the first designator, our caller will continue checking
2977 // the rest of this struct/class/union subobject.
2978 if (IsFirstDesignator) {
2979 if (Field != RD->field_end() && Field->isUnnamedBitField())
2980 ++Field;
2981
2982 if (NextField)
2983 *NextField = Field;
2984
2985 StructuredIndex = FieldIndex;
2986 return false;
2987 }
2988
2989 if (!FinishSubobjectInit)
2990 return false;
2991
2992 // We've already initialized something in the union; we're done.
2993 if (RD->isUnion())
2994 return hadError;
2995
2996 // Check the remaining fields within this class/struct/union subobject.
2997 bool prevHadError = hadError;
2998
2999 auto NoBases =
3000 CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
3001 CXXRecordDecl::base_class_iterator());
3002 CheckStructUnionTypes(Entity, IList, DeclType: CurrentObjectType, Bases: NoBases, Field,
3003 SubobjectIsDesignatorContext: false, Index, StructuredList, StructuredIndex&: FieldIndex);
3004 return hadError && !prevHadError;
3005 }
3006
3007 // C99 6.7.8p6:
3008 //
3009 // If a designator has the form
3010 //
3011 // [ constant-expression ]
3012 //
3013 // then the current object (defined below) shall have array
3014 // type and the expression shall be an integer constant
3015 // expression. If the array is of unknown size, any
3016 // nonnegative value is valid.
3017 //
3018 // Additionally, cope with the GNU extension that permits
3019 // designators of the form
3020 //
3021 // [ constant-expression ... constant-expression ]
3022 const ArrayType *AT = SemaRef.Context.getAsArrayType(T: CurrentObjectType);
3023 if (!AT) {
3024 if (!VerifyOnly)
3025 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
3026 << CurrentObjectType;
3027 ++Index;
3028 return true;
3029 }
3030
3031 Expr *IndexExpr = nullptr;
3032 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3033 if (D->isArrayDesignator()) {
3034 IndexExpr = DIE->getArrayIndex(D: *D);
3035 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3036 DesignatedEndIndex = DesignatedStartIndex;
3037 } else {
3038 assert(D->isArrayRangeDesignator() && "Need array-range designator");
3039
3040 DesignatedStartIndex =
3041 DIE->getArrayRangeStart(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3042 DesignatedEndIndex =
3043 DIE->getArrayRangeEnd(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context);
3044 IndexExpr = DIE->getArrayRangeEnd(D: *D);
3045
3046 // Codegen can't handle evaluating array range designators that have side
3047 // effects, because we replicate the AST value for each initialized element.
3048 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3049 // elements with something that has a side effect, so codegen can emit an
3050 // "error unsupported" error instead of miscompiling the app.
3051 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3052 DIE->getInit()->HasSideEffects(Ctx: SemaRef.Context) && !VerifyOnly)
3053 FullyStructuredList->sawArrayRangeDesignator();
3054 }
3055
3056 if (isa<ConstantArrayType>(Val: AT)) {
3057 llvm::APSInt MaxElements(cast<ConstantArrayType>(Val: AT)->getSize(), false);
3058 DesignatedStartIndex
3059 = DesignatedStartIndex.extOrTrunc(width: MaxElements.getBitWidth());
3060 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3061 DesignatedEndIndex
3062 = DesignatedEndIndex.extOrTrunc(width: MaxElements.getBitWidth());
3063 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3064 if (DesignatedEndIndex >= MaxElements) {
3065 if (!VerifyOnly)
3066 SemaRef.Diag(IndexExpr->getBeginLoc(),
3067 diag::err_array_designator_too_large)
3068 << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3069 << IndexExpr->getSourceRange();
3070 ++Index;
3071 return true;
3072 }
3073 } else {
3074 unsigned DesignatedIndexBitWidth =
3075 ConstantArrayType::getMaxSizeBits(Context: SemaRef.Context);
3076 DesignatedStartIndex =
3077 DesignatedStartIndex.extOrTrunc(width: DesignatedIndexBitWidth);
3078 DesignatedEndIndex =
3079 DesignatedEndIndex.extOrTrunc(width: DesignatedIndexBitWidth);
3080 DesignatedStartIndex.setIsUnsigned(true);
3081 DesignatedEndIndex.setIsUnsigned(true);
3082 }
3083
3084 bool IsStringLiteralInitUpdate =
3085 StructuredList && StructuredList->isStringLiteralInit();
3086 if (IsStringLiteralInitUpdate && VerifyOnly) {
3087 // We're just verifying an update to a string literal init. We don't need
3088 // to split the string up into individual characters to do that.
3089 StructuredList = nullptr;
3090 } else if (IsStringLiteralInitUpdate) {
3091 // We're modifying a string literal init; we have to decompose the string
3092 // so we can modify the individual characters.
3093 ASTContext &Context = SemaRef.Context;
3094 Expr *SubExpr = StructuredList->getInit(Init: 0)->IgnoreParenImpCasts();
3095
3096 // Compute the character type
3097 QualType CharTy = AT->getElementType();
3098
3099 // Compute the type of the integer literals.
3100 QualType PromotedCharTy = CharTy;
3101 if (Context.isPromotableIntegerType(T: CharTy))
3102 PromotedCharTy = Context.getPromotedIntegerType(PromotableType: CharTy);
3103 unsigned PromotedCharTyWidth = Context.getTypeSize(T: PromotedCharTy);
3104
3105 if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: SubExpr)) {
3106 // Get the length of the string.
3107 uint64_t StrLen = SL->getLength();
3108 if (cast<ConstantArrayType>(Val: AT)->getSize().ult(RHS: StrLen))
3109 StrLen = cast<ConstantArrayType>(Val: AT)->getZExtSize();
3110 StructuredList->resizeInits(Context, NumInits: StrLen);
3111
3112 // Build a literal for each character in the string, and put them into
3113 // the init list.
3114 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3115 llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3116 Expr *Init = new (Context) IntegerLiteral(
3117 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3118 if (CharTy != PromotedCharTy)
3119 Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast,
3120 Operand: Init, BasePath: nullptr, Cat: VK_PRValue,
3121 FPO: FPOptionsOverride());
3122 StructuredList->updateInit(C: Context, Init: i, expr: Init);
3123 }
3124 } else {
3125 ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(Val: SubExpr);
3126 std::string Str;
3127 Context.getObjCEncodingForType(T: E->getEncodedType(), S&: Str);
3128
3129 // Get the length of the string.
3130 uint64_t StrLen = Str.size();
3131 if (cast<ConstantArrayType>(Val: AT)->getSize().ult(RHS: StrLen))
3132 StrLen = cast<ConstantArrayType>(Val: AT)->getZExtSize();
3133 StructuredList->resizeInits(Context, NumInits: StrLen);
3134
3135 // Build a literal for each character in the string, and put them into
3136 // the init list.
3137 for (unsigned i = 0, e = StrLen; i != e; ++i) {
3138 llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3139 Expr *Init = new (Context) IntegerLiteral(
3140 Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3141 if (CharTy != PromotedCharTy)
3142 Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast,
3143 Operand: Init, BasePath: nullptr, Cat: VK_PRValue,
3144 FPO: FPOptionsOverride());
3145 StructuredList->updateInit(C: Context, Init: i, expr: Init);
3146 }
3147 }
3148 }
3149
3150 // Make sure that our non-designated initializer list has space
3151 // for a subobject corresponding to this array element.
3152 if (StructuredList &&
3153 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3154 StructuredList->resizeInits(Context: SemaRef.Context,
3155 NumInits: DesignatedEndIndex.getZExtValue() + 1);
3156
3157 // Repeatedly perform subobject initializations in the range
3158 // [DesignatedStartIndex, DesignatedEndIndex].
3159
3160 // Move to the next designator
3161 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3162 unsigned OldIndex = Index;
3163
3164 InitializedEntity ElementEntity =
3165 InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity);
3166
3167 while (DesignatedStartIndex <= DesignatedEndIndex) {
3168 // Recurse to check later designated subobjects.
3169 QualType ElementType = AT->getElementType();
3170 Index = OldIndex;
3171
3172 ElementEntity.setElementIndex(ElementIndex);
3173 if (CheckDesignatedInitializer(
3174 Entity: ElementEntity, IList, DIE, DesigIdx: DesigIdx + 1, CurrentObjectType&: ElementType, NextField: nullptr,
3175 NextElementIndex: nullptr, Index, StructuredList, StructuredIndex&: ElementIndex,
3176 FinishSubobjectInit: FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3177 TopLevelObject: false))
3178 return true;
3179
3180 // Move to the next index in the array that we'll be initializing.
3181 ++DesignatedStartIndex;
3182 ElementIndex = DesignatedStartIndex.getZExtValue();
3183 }
3184
3185 // If this the first designator, our caller will continue checking
3186 // the rest of this array subobject.
3187 if (IsFirstDesignator) {
3188 if (NextElementIndex)
3189 *NextElementIndex = DesignatedStartIndex;
3190 StructuredIndex = ElementIndex;
3191 return false;
3192 }
3193
3194 if (!FinishSubobjectInit)
3195 return false;
3196
3197 // Check the remaining elements within this array subobject.
3198 bool prevHadError = hadError;
3199 CheckArrayType(Entity, IList, DeclType&: CurrentObjectType, elementIndex: DesignatedStartIndex,
3200 /*SubobjectIsDesignatorContext=*/false, Index,
3201 StructuredList, StructuredIndex&: ElementIndex);
3202 return hadError && !prevHadError;
3203}
3204
3205// Get the structured initializer list for a subobject of type
3206// @p CurrentObjectType.
3207InitListExpr *
3208InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3209 QualType CurrentObjectType,
3210 InitListExpr *StructuredList,
3211 unsigned StructuredIndex,
3212 SourceRange InitRange,
3213 bool IsFullyOverwritten) {
3214 if (!StructuredList)
3215 return nullptr;
3216
3217 Expr *ExistingInit = nullptr;
3218 if (StructuredIndex < StructuredList->getNumInits())
3219 ExistingInit = StructuredList->getInit(Init: StructuredIndex);
3220
3221 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(Val: ExistingInit))
3222 // There might have already been initializers for subobjects of the current
3223 // object, but a subsequent initializer list will overwrite the entirety
3224 // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3225 //
3226 // struct P { char x[6]; };
3227 // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3228 //
3229 // The first designated initializer is ignored, and l.x is just "f".
3230 if (!IsFullyOverwritten)
3231 return Result;
3232
3233 if (ExistingInit) {
3234 // We are creating an initializer list that initializes the
3235 // subobjects of the current object, but there was already an
3236 // initialization that completely initialized the current
3237 // subobject:
3238 //
3239 // struct X { int a, b; };
3240 // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3241 //
3242 // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3243 // designated initializer overwrites the [0].b initializer
3244 // from the prior initialization.
3245 //
3246 // When the existing initializer is an expression rather than an
3247 // initializer list, we cannot decompose and update it in this way.
3248 // For example:
3249 //
3250 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3251 //
3252 // This case is handled by CheckDesignatedInitializer.
3253 diagnoseInitOverride(OldInit: ExistingInit, NewInitRange: InitRange);
3254 }
3255
3256 unsigned ExpectedNumInits = 0;
3257 if (Index < IList->getNumInits()) {
3258 if (auto *Init = dyn_cast_or_null<InitListExpr>(Val: IList->getInit(Init: Index)))
3259 ExpectedNumInits = Init->getNumInits();
3260 else
3261 ExpectedNumInits = IList->getNumInits() - Index;
3262 }
3263
3264 InitListExpr *Result =
3265 createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3266
3267 // Link this new initializer list into the structured initializer
3268 // lists.
3269 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3270 return Result;
3271}
3272
3273InitListExpr *
3274InitListChecker::createInitListExpr(QualType CurrentObjectType,
3275 SourceRange InitRange,
3276 unsigned ExpectedNumInits) {
3277 InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3278 SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3279
3280 QualType ResultType = CurrentObjectType;
3281 if (!ResultType->isArrayType())
3282 ResultType = ResultType.getNonLValueExprType(Context: SemaRef.Context);
3283 Result->setType(ResultType);
3284
3285 // Pre-allocate storage for the structured initializer list.
3286 unsigned NumElements = 0;
3287
3288 if (const ArrayType *AType
3289 = SemaRef.Context.getAsArrayType(T: CurrentObjectType)) {
3290 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(Val: AType)) {
3291 NumElements = CAType->getZExtSize();
3292 // Simple heuristic so that we don't allocate a very large
3293 // initializer with many empty entries at the end.
3294 if (NumElements > ExpectedNumInits)
3295 NumElements = 0;
3296 }
3297 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3298 NumElements = VType->getNumElements();
3299 } else if (CurrentObjectType->isRecordType()) {
3300 NumElements = numStructUnionElements(DeclType: CurrentObjectType);
3301 } else if (CurrentObjectType->isDependentType()) {
3302 NumElements = 1;
3303 }
3304
3305 Result->reserveInits(C: SemaRef.Context, NumInits: NumElements);
3306
3307 return Result;
3308}
3309
3310/// Update the initializer at index @p StructuredIndex within the
3311/// structured initializer list to the value @p expr.
3312void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3313 unsigned &StructuredIndex,
3314 Expr *expr) {
3315 // No structured initializer list to update
3316 if (!StructuredList)
3317 return;
3318
3319 if (Expr *PrevInit = StructuredList->updateInit(C: SemaRef.Context,
3320 Init: StructuredIndex, expr)) {
3321 // This initializer overwrites a previous initializer.
3322 // No need to diagnose when `expr` is nullptr because a more relevant
3323 // diagnostic has already been issued and this diagnostic is potentially
3324 // noise.
3325 if (expr)
3326 diagnoseInitOverride(OldInit: PrevInit, NewInitRange: expr->getSourceRange());
3327 }
3328
3329 ++StructuredIndex;
3330}
3331
3332/// Determine whether we can perform aggregate initialization for the purposes
3333/// of overload resolution.
3334bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3335 const InitializedEntity &Entity, InitListExpr *From) {
3336 QualType Type = Entity.getType();
3337 InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3338 /*TreatUnavailableAsInvalid=*/false,
3339 /*InOverloadResolution=*/true);
3340 return !Check.HadError();
3341}
3342
3343/// Check that the given Index expression is a valid array designator
3344/// value. This is essentially just a wrapper around
3345/// VerifyIntegerConstantExpression that also checks for negative values
3346/// and produces a reasonable diagnostic if there is a
3347/// failure. Returns the index expression, possibly with an implicit cast
3348/// added, on success. If everything went okay, Value will receive the
3349/// value of the constant expression.
3350static ExprResult
3351CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3352 SourceLocation Loc = Index->getBeginLoc();
3353
3354 // Make sure this is an integer constant expression.
3355 ExprResult Result =
3356 S.VerifyIntegerConstantExpression(E: Index, Result: &Value, CanFold: Sema::AllowFold);
3357 if (Result.isInvalid())
3358 return Result;
3359
3360 if (Value.isSigned() && Value.isNegative())
3361 return S.Diag(Loc, diag::err_array_designator_negative)
3362 << toString(Value, 10) << Index->getSourceRange();
3363
3364 Value.setIsUnsigned(true);
3365 return Result;
3366}
3367
3368ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3369 SourceLocation EqualOrColonLoc,
3370 bool GNUSyntax,
3371 ExprResult Init) {
3372 typedef DesignatedInitExpr::Designator ASTDesignator;
3373
3374 bool Invalid = false;
3375 SmallVector<ASTDesignator, 32> Designators;
3376 SmallVector<Expr *, 32> InitExpressions;
3377
3378 // Build designators and check array designator expressions.
3379 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3380 const Designator &D = Desig.getDesignator(Idx);
3381
3382 if (D.isFieldDesignator()) {
3383 Designators.push_back(Elt: ASTDesignator::CreateFieldDesignator(
3384 FieldName: D.getFieldDecl(), DotLoc: D.getDotLoc(), FieldLoc: D.getFieldLoc()));
3385 } else if (D.isArrayDesignator()) {
3386 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3387 llvm::APSInt IndexValue;
3388 if (!Index->isTypeDependent() && !Index->isValueDependent())
3389 Index = CheckArrayDesignatorExpr(S&: *this, Index, Value&: IndexValue).get();
3390 if (!Index)
3391 Invalid = true;
3392 else {
3393 Designators.push_back(Elt: ASTDesignator::CreateArrayDesignator(
3394 Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), RBracketLoc: D.getRBracketLoc()));
3395 InitExpressions.push_back(Elt: Index);
3396 }
3397 } else if (D.isArrayRangeDesignator()) {
3398 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3399 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3400 llvm::APSInt StartValue;
3401 llvm::APSInt EndValue;
3402 bool StartDependent = StartIndex->isTypeDependent() ||
3403 StartIndex->isValueDependent();
3404 bool EndDependent = EndIndex->isTypeDependent() ||
3405 EndIndex->isValueDependent();
3406 if (!StartDependent)
3407 StartIndex =
3408 CheckArrayDesignatorExpr(S&: *this, Index: StartIndex, Value&: StartValue).get();
3409 if (!EndDependent)
3410 EndIndex = CheckArrayDesignatorExpr(S&: *this, Index: EndIndex, Value&: EndValue).get();
3411
3412 if (!StartIndex || !EndIndex)
3413 Invalid = true;
3414 else {
3415 // Make sure we're comparing values with the same bit width.
3416 if (StartDependent || EndDependent) {
3417 // Nothing to compute.
3418 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3419 EndValue = EndValue.extend(width: StartValue.getBitWidth());
3420 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3421 StartValue = StartValue.extend(width: EndValue.getBitWidth());
3422
3423 if (!StartDependent && !EndDependent && EndValue < StartValue) {
3424 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3425 << toString(StartValue, 10) << toString(EndValue, 10)
3426 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3427 Invalid = true;
3428 } else {
3429 Designators.push_back(Elt: ASTDesignator::CreateArrayRangeDesignator(
3430 Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), EllipsisLoc: D.getEllipsisLoc(),
3431 RBracketLoc: D.getRBracketLoc()));
3432 InitExpressions.push_back(Elt: StartIndex);
3433 InitExpressions.push_back(Elt: EndIndex);
3434 }
3435 }
3436 }
3437 }
3438
3439 if (Invalid || Init.isInvalid())
3440 return ExprError();
3441
3442 return DesignatedInitExpr::Create(C: Context, Designators, IndexExprs: InitExpressions,
3443 EqualOrColonLoc, GNUSyntax,
3444 Init: Init.getAs<Expr>());
3445}
3446
3447//===----------------------------------------------------------------------===//
3448// Initialization entity
3449//===----------------------------------------------------------------------===//
3450
3451InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3452 const InitializedEntity &Parent)
3453 : Parent(&Parent), Index(Index)
3454{
3455 if (const ArrayType *AT = Context.getAsArrayType(T: Parent.getType())) {
3456 Kind = EK_ArrayElement;
3457 Type = AT->getElementType();
3458 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3459 Kind = EK_VectorElement;
3460 Type = VT->getElementType();
3461 } else {
3462 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3463 assert(CT && "Unexpected type");
3464 Kind = EK_ComplexElement;
3465 Type = CT->getElementType();
3466 }
3467}
3468
3469InitializedEntity
3470InitializedEntity::InitializeBase(ASTContext &Context,
3471 const CXXBaseSpecifier *Base,
3472 bool IsInheritedVirtualBase,
3473 const InitializedEntity *Parent) {
3474 InitializedEntity Result;
3475 Result.Kind = EK_Base;
3476 Result.Parent = Parent;
3477 Result.Base = {Base, IsInheritedVirtualBase};
3478 Result.Type = Base->getType();
3479 return Result;
3480}
3481
3482DeclarationName InitializedEntity::getName() const {
3483 switch (getKind()) {
3484 case EK_Parameter:
3485 case EK_Parameter_CF_Audited: {
3486 ParmVarDecl *D = Parameter.getPointer();
3487 return (D ? D->getDeclName() : DeclarationName());
3488 }
3489
3490 case EK_Variable:
3491 case EK_Member:
3492 case EK_ParenAggInitMember:
3493 case EK_Binding:
3494 case EK_TemplateParameter:
3495 return Variable.VariableOrMember->getDeclName();
3496
3497 case EK_LambdaCapture:
3498 return DeclarationName(Capture.VarID);
3499
3500 case EK_Result:
3501 case EK_StmtExprResult:
3502 case EK_Exception:
3503 case EK_New:
3504 case EK_Temporary:
3505 case EK_Base:
3506 case EK_Delegating:
3507 case EK_ArrayElement:
3508 case EK_VectorElement:
3509 case EK_ComplexElement:
3510 case EK_BlockElement:
3511 case EK_LambdaToBlockConversionBlockElement:
3512 case EK_CompoundLiteralInit:
3513 case EK_RelatedResult:
3514 return DeclarationName();
3515 }
3516
3517 llvm_unreachable("Invalid EntityKind!");
3518}
3519
3520ValueDecl *InitializedEntity::getDecl() const {
3521 switch (getKind()) {
3522 case EK_Variable:
3523 case EK_Member:
3524 case EK_ParenAggInitMember:
3525 case EK_Binding:
3526 case EK_TemplateParameter:
3527 return Variable.VariableOrMember;
3528
3529 case EK_Parameter:
3530 case EK_Parameter_CF_Audited:
3531 return Parameter.getPointer();
3532
3533 case EK_Result:
3534 case EK_StmtExprResult:
3535 case EK_Exception:
3536 case EK_New:
3537 case EK_Temporary:
3538 case EK_Base:
3539 case EK_Delegating:
3540 case EK_ArrayElement:
3541 case EK_VectorElement:
3542 case EK_ComplexElement:
3543 case EK_BlockElement:
3544 case EK_LambdaToBlockConversionBlockElement:
3545 case EK_LambdaCapture:
3546 case EK_CompoundLiteralInit:
3547 case EK_RelatedResult:
3548 return nullptr;
3549 }
3550
3551 llvm_unreachable("Invalid EntityKind!");
3552}
3553
3554bool InitializedEntity::allowsNRVO() const {
3555 switch (getKind()) {
3556 case EK_Result:
3557 case EK_Exception:
3558 return LocAndNRVO.NRVO;
3559
3560 case EK_StmtExprResult:
3561 case EK_Variable:
3562 case EK_Parameter:
3563 case EK_Parameter_CF_Audited:
3564 case EK_TemplateParameter:
3565 case EK_Member:
3566 case EK_ParenAggInitMember:
3567 case EK_Binding:
3568 case EK_New:
3569 case EK_Temporary:
3570 case EK_CompoundLiteralInit:
3571 case EK_Base:
3572 case EK_Delegating:
3573 case EK_ArrayElement:
3574 case EK_VectorElement:
3575 case EK_ComplexElement:
3576 case EK_BlockElement:
3577 case EK_LambdaToBlockConversionBlockElement:
3578 case EK_LambdaCapture:
3579 case EK_RelatedResult:
3580 break;
3581 }
3582
3583 return false;
3584}
3585
3586unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3587 assert(getParent() != this);
3588 unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3589 for (unsigned I = 0; I != Depth; ++I)
3590 OS << "`-";
3591
3592 switch (getKind()) {
3593 case EK_Variable: OS << "Variable"; break;
3594 case EK_Parameter: OS << "Parameter"; break;
3595 case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3596 break;
3597 case EK_TemplateParameter: OS << "TemplateParameter"; break;
3598 case EK_Result: OS << "Result"; break;
3599 case EK_StmtExprResult: OS << "StmtExprResult"; break;
3600 case EK_Exception: OS << "Exception"; break;
3601 case EK_Member:
3602 case EK_ParenAggInitMember:
3603 OS << "Member";
3604 break;
3605 case EK_Binding: OS << "Binding"; break;
3606 case EK_New: OS << "New"; break;
3607 case EK_Temporary: OS << "Temporary"; break;
3608 case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3609 case EK_RelatedResult: OS << "RelatedResult"; break;
3610 case EK_Base: OS << "Base"; break;
3611 case EK_Delegating: OS << "Delegating"; break;
3612 case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3613 case EK_VectorElement: OS << "VectorElement " << Index; break;
3614 case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3615 case EK_BlockElement: OS << "Block"; break;
3616 case EK_LambdaToBlockConversionBlockElement:
3617 OS << "Block (lambda)";
3618 break;
3619 case EK_LambdaCapture:
3620 OS << "LambdaCapture ";
3621 OS << DeclarationName(Capture.VarID);
3622 break;
3623 }
3624
3625 if (auto *D = getDecl()) {
3626 OS << " ";
3627 D->printQualifiedName(OS);
3628 }
3629
3630 OS << " '" << getType() << "'\n";
3631
3632 return Depth + 1;
3633}
3634
3635LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3636 dumpImpl(OS&: llvm::errs());
3637}
3638
3639//===----------------------------------------------------------------------===//
3640// Initialization sequence
3641//===----------------------------------------------------------------------===//
3642
3643void InitializationSequence::Step::Destroy() {
3644 switch (Kind) {
3645 case SK_ResolveAddressOfOverloadedFunction:
3646 case SK_CastDerivedToBasePRValue:
3647 case SK_CastDerivedToBaseXValue:
3648 case SK_CastDerivedToBaseLValue:
3649 case SK_BindReference:
3650 case SK_BindReferenceToTemporary:
3651 case SK_FinalCopy:
3652 case SK_ExtraneousCopyToTemporary:
3653 case SK_UserConversion:
3654 case SK_QualificationConversionPRValue:
3655 case SK_QualificationConversionXValue:
3656 case SK_QualificationConversionLValue:
3657 case SK_FunctionReferenceConversion:
3658 case SK_AtomicConversion:
3659 case SK_ListInitialization:
3660 case SK_UnwrapInitList:
3661 case SK_RewrapInitList:
3662 case SK_ConstructorInitialization:
3663 case SK_ConstructorInitializationFromList:
3664 case SK_ZeroInitialization:
3665 case SK_CAssignment:
3666 case SK_StringInit:
3667 case SK_ObjCObjectConversion:
3668 case SK_ArrayLoopIndex:
3669 case SK_ArrayLoopInit:
3670 case SK_ArrayInit:
3671 case SK_GNUArrayInit:
3672 case SK_ParenthesizedArrayInit:
3673 case SK_PassByIndirectCopyRestore:
3674 case SK_PassByIndirectRestore:
3675 case SK_ProduceObjCObject:
3676 case SK_StdInitializerList:
3677 case SK_StdInitializerListConstructorCall:
3678 case SK_OCLSamplerInit:
3679 case SK_OCLZeroOpaqueType:
3680 case SK_ParenthesizedListInit:
3681 break;
3682
3683 case SK_ConversionSequence:
3684 case SK_ConversionSequenceNoNarrowing:
3685 delete ICS;
3686 }
3687}
3688
3689bool InitializationSequence::isDirectReferenceBinding() const {
3690 // There can be some lvalue adjustments after the SK_BindReference step.
3691 for (const Step &S : llvm::reverse(C: Steps)) {
3692 if (S.Kind == SK_BindReference)
3693 return true;
3694 if (S.Kind == SK_BindReferenceToTemporary)
3695 return false;
3696 }
3697 return false;
3698}
3699
3700bool InitializationSequence::isAmbiguous() const {
3701 if (!Failed())
3702 return false;
3703
3704 switch (getFailureKind()) {
3705 case FK_TooManyInitsForReference:
3706 case FK_ParenthesizedListInitForReference:
3707 case FK_ArrayNeedsInitList:
3708 case FK_ArrayNeedsInitListOrStringLiteral:
3709 case FK_ArrayNeedsInitListOrWideStringLiteral:
3710 case FK_NarrowStringIntoWideCharArray:
3711 case FK_WideStringIntoCharArray:
3712 case FK_IncompatWideStringIntoWideChar:
3713 case FK_PlainStringIntoUTF8Char:
3714 case FK_UTF8StringIntoPlainChar:
3715 case FK_AddressOfOverloadFailed: // FIXME: Could do better
3716 case FK_NonConstLValueReferenceBindingToTemporary:
3717 case FK_NonConstLValueReferenceBindingToBitfield:
3718 case FK_NonConstLValueReferenceBindingToVectorElement:
3719 case FK_NonConstLValueReferenceBindingToMatrixElement:
3720 case FK_NonConstLValueReferenceBindingToUnrelated:
3721 case FK_RValueReferenceBindingToLValue:
3722 case FK_ReferenceAddrspaceMismatchTemporary:
3723 case FK_ReferenceInitDropsQualifiers:
3724 case FK_ReferenceInitFailed:
3725 case FK_ConversionFailed:
3726 case FK_ConversionFromPropertyFailed:
3727 case FK_TooManyInitsForScalar:
3728 case FK_ParenthesizedListInitForScalar:
3729 case FK_ReferenceBindingToInitList:
3730 case FK_InitListBadDestinationType:
3731 case FK_DefaultInitOfConst:
3732 case FK_Incomplete:
3733 case FK_ArrayTypeMismatch:
3734 case FK_NonConstantArrayInit:
3735 case FK_ListInitializationFailed:
3736 case FK_VariableLengthArrayHasInitializer:
3737 case FK_PlaceholderType:
3738 case FK_ExplicitConstructor:
3739 case FK_AddressOfUnaddressableFunction:
3740 case FK_ParenthesizedListInitFailed:
3741 case FK_DesignatedInitForNonAggregate:
3742 return false;
3743
3744 case FK_ReferenceInitOverloadFailed:
3745 case FK_UserConversionOverloadFailed:
3746 case FK_ConstructorOverloadFailed:
3747 case FK_ListConstructorOverloadFailed:
3748 return FailedOverloadResult == OR_Ambiguous;
3749 }
3750
3751 llvm_unreachable("Invalid EntityKind!");
3752}
3753
3754bool InitializationSequence::isConstructorInitialization() const {
3755 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3756}
3757
3758void
3759InitializationSequence
3760::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3761 DeclAccessPair Found,
3762 bool HadMultipleCandidates) {
3763 Step S;
3764 S.Kind = SK_ResolveAddressOfOverloadedFunction;
3765 S.Type = Function->getType();
3766 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3767 S.Function.Function = Function;
3768 S.Function.FoundDecl = Found;
3769 Steps.push_back(Elt: S);
3770}
3771
3772void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3773 ExprValueKind VK) {
3774 Step S;
3775 switch (VK) {
3776 case VK_PRValue:
3777 S.Kind = SK_CastDerivedToBasePRValue;
3778 break;
3779 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3780 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3781 }
3782 S.Type = BaseType;
3783 Steps.push_back(Elt: S);
3784}
3785
3786void InitializationSequence::AddReferenceBindingStep(QualType T,
3787 bool BindingTemporary) {
3788 Step S;
3789 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3790 S.Type = T;
3791 Steps.push_back(Elt: S);
3792}
3793
3794void InitializationSequence::AddFinalCopy(QualType T) {
3795 Step S;
3796 S.Kind = SK_FinalCopy;
3797 S.Type = T;
3798 Steps.push_back(Elt: S);
3799}
3800
3801void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3802 Step S;
3803 S.Kind = SK_ExtraneousCopyToTemporary;
3804 S.Type = T;
3805 Steps.push_back(Elt: S);
3806}
3807
3808void
3809InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3810 DeclAccessPair FoundDecl,
3811 QualType T,
3812 bool HadMultipleCandidates) {
3813 Step S;
3814 S.Kind = SK_UserConversion;
3815 S.Type = T;
3816 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3817 S.Function.Function = Function;
3818 S.Function.FoundDecl = FoundDecl;
3819 Steps.push_back(Elt: S);
3820}
3821
3822void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3823 ExprValueKind VK) {
3824 Step S;
3825 S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3826 switch (VK) {
3827 case VK_PRValue:
3828 S.Kind = SK_QualificationConversionPRValue;
3829 break;
3830 case VK_XValue:
3831 S.Kind = SK_QualificationConversionXValue;
3832 break;
3833 case VK_LValue:
3834 S.Kind = SK_QualificationConversionLValue;
3835 break;
3836 }
3837 S.Type = Ty;
3838 Steps.push_back(Elt: S);
3839}
3840
3841void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3842 Step S;
3843 S.Kind = SK_FunctionReferenceConversion;
3844 S.Type = Ty;
3845 Steps.push_back(Elt: S);
3846}
3847
3848void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3849 Step S;
3850 S.Kind = SK_AtomicConversion;
3851 S.Type = Ty;
3852 Steps.push_back(Elt: S);
3853}
3854
3855void InitializationSequence::AddConversionSequenceStep(
3856 const ImplicitConversionSequence &ICS, QualType T,
3857 bool TopLevelOfInitList) {
3858 Step S;
3859 S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3860 : SK_ConversionSequence;
3861 S.Type = T;
3862 S.ICS = new ImplicitConversionSequence(ICS);
3863 Steps.push_back(Elt: S);
3864}
3865
3866void InitializationSequence::AddListInitializationStep(QualType T) {
3867 Step S;
3868 S.Kind = SK_ListInitialization;
3869 S.Type = T;
3870 Steps.push_back(Elt: S);
3871}
3872
3873void InitializationSequence::AddConstructorInitializationStep(
3874 DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3875 bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3876 Step S;
3877 S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3878 : SK_ConstructorInitializationFromList
3879 : SK_ConstructorInitialization;
3880 S.Type = T;
3881 S.Function.HadMultipleCandidates = HadMultipleCandidates;
3882 S.Function.Function = Constructor;
3883 S.Function.FoundDecl = FoundDecl;
3884 Steps.push_back(Elt: S);
3885}
3886
3887void InitializationSequence::AddZeroInitializationStep(QualType T) {
3888 Step S;
3889 S.Kind = SK_ZeroInitialization;
3890 S.Type = T;
3891 Steps.push_back(Elt: S);
3892}
3893
3894void InitializationSequence::AddCAssignmentStep(QualType T) {
3895 Step S;
3896 S.Kind = SK_CAssignment;
3897 S.Type = T;
3898 Steps.push_back(Elt: S);
3899}
3900
3901void InitializationSequence::AddStringInitStep(QualType T) {
3902 Step S;
3903 S.Kind = SK_StringInit;
3904 S.Type = T;
3905 Steps.push_back(Elt: S);
3906}
3907
3908void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3909 Step S;
3910 S.Kind = SK_ObjCObjectConversion;
3911 S.Type = T;
3912 Steps.push_back(Elt: S);
3913}
3914
3915void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3916 Step S;
3917 S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3918 S.Type = T;
3919 Steps.push_back(Elt: S);
3920}
3921
3922void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3923 Step S;
3924 S.Kind = SK_ArrayLoopIndex;
3925 S.Type = EltT;
3926 Steps.insert(I: Steps.begin(), Elt: S);
3927
3928 S.Kind = SK_ArrayLoopInit;
3929 S.Type = T;
3930 Steps.push_back(Elt: S);
3931}
3932
3933void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3934 Step S;
3935 S.Kind = SK_ParenthesizedArrayInit;
3936 S.Type = T;
3937 Steps.push_back(Elt: S);
3938}
3939
3940void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3941 bool shouldCopy) {
3942 Step s;
3943 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3944 : SK_PassByIndirectRestore);
3945 s.Type = type;
3946 Steps.push_back(Elt: s);
3947}
3948
3949void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3950 Step S;
3951 S.Kind = SK_ProduceObjCObject;
3952 S.Type = T;
3953 Steps.push_back(Elt: S);
3954}
3955
3956void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3957 Step S;
3958 S.Kind = SK_StdInitializerList;
3959 S.Type = T;
3960 Steps.push_back(Elt: S);
3961}
3962
3963void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3964 Step S;
3965 S.Kind = SK_OCLSamplerInit;
3966 S.Type = T;
3967 Steps.push_back(Elt: S);
3968}
3969
3970void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3971 Step S;
3972 S.Kind = SK_OCLZeroOpaqueType;
3973 S.Type = T;
3974 Steps.push_back(Elt: S);
3975}
3976
3977void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
3978 Step S;
3979 S.Kind = SK_ParenthesizedListInit;
3980 S.Type = T;
3981 Steps.push_back(Elt: S);
3982}
3983
3984void InitializationSequence::RewrapReferenceInitList(QualType T,
3985 InitListExpr *Syntactic) {
3986 assert(Syntactic->getNumInits() == 1 &&
3987 "Can only rewrap trivial init lists.");
3988 Step S;
3989 S.Kind = SK_UnwrapInitList;
3990 S.Type = Syntactic->getInit(Init: 0)->getType();
3991 Steps.insert(I: Steps.begin(), Elt: S);
3992
3993 S.Kind = SK_RewrapInitList;
3994 S.Type = T;
3995 S.WrappingSyntacticList = Syntactic;
3996 Steps.push_back(Elt: S);
3997}
3998
3999void InitializationSequence::SetOverloadFailure(FailureKind Failure,
4000 OverloadingResult Result) {
4001 setSequenceKind(FailedSequence);
4002 this->Failure = Failure;
4003 this->FailedOverloadResult = Result;
4004}
4005
4006//===----------------------------------------------------------------------===//
4007// Attempt initialization
4008//===----------------------------------------------------------------------===//
4009
4010/// Tries to add a zero initializer. Returns true if that worked.
4011static bool
4012maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
4013 const InitializedEntity &Entity) {
4014 if (Entity.getKind() != InitializedEntity::EK_Variable)
4015 return false;
4016
4017 VarDecl *VD = cast<VarDecl>(Val: Entity.getDecl());
4018 if (VD->getInit() || VD->getEndLoc().isMacroID())
4019 return false;
4020
4021 QualType VariableTy = VD->getType().getCanonicalType();
4022 SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc());
4023 std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc);
4024 if (!Init.empty()) {
4025 Sequence.AddZeroInitializationStep(T: Entity.getType());
4026 Sequence.SetZeroInitializationFixit(Fixit: Init, L: Loc);
4027 return true;
4028 }
4029 return false;
4030}
4031
4032static void MaybeProduceObjCObject(Sema &S,
4033 InitializationSequence &Sequence,
4034 const InitializedEntity &Entity) {
4035 if (!S.getLangOpts().ObjCAutoRefCount) return;
4036
4037 /// When initializing a parameter, produce the value if it's marked
4038 /// __attribute__((ns_consumed)).
4039 if (Entity.isParameterKind()) {
4040 if (!Entity.isParameterConsumed())
4041 return;
4042
4043 assert(Entity.getType()->isObjCRetainableType() &&
4044 "consuming an object of unretainable type?");
4045 Sequence.AddProduceObjCObjectStep(T: Entity.getType());
4046
4047 /// When initializing a return value, if the return type is a
4048 /// retainable type, then returns need to immediately retain the
4049 /// object. If an autorelease is required, it will be done at the
4050 /// last instant.
4051 } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4052 Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
4053 if (!Entity.getType()->isObjCRetainableType())
4054 return;
4055
4056 Sequence.AddProduceObjCObjectStep(T: Entity.getType());
4057 }
4058}
4059
4060static void TryListInitialization(Sema &S,
4061 const InitializedEntity &Entity,
4062 const InitializationKind &Kind,
4063 InitListExpr *InitList,
4064 InitializationSequence &Sequence,
4065 bool TreatUnavailableAsInvalid);
4066
4067/// When initializing from init list via constructor, handle
4068/// initialization of an object of type std::initializer_list<T>.
4069///
4070/// \return true if we have handled initialization of an object of type
4071/// std::initializer_list<T>, false otherwise.
4072static bool TryInitializerListConstruction(Sema &S,
4073 InitListExpr *List,
4074 QualType DestType,
4075 InitializationSequence &Sequence,
4076 bool TreatUnavailableAsInvalid) {
4077 QualType E;
4078 if (!S.isStdInitializerList(Ty: DestType, Element: &E))
4079 return false;
4080
4081 if (!S.isCompleteType(Loc: List->getExprLoc(), T: E)) {
4082 Sequence.setIncompleteTypeFailure(E);
4083 return true;
4084 }
4085
4086 // Try initializing a temporary array from the init list.
4087 QualType ArrayType = S.Context.getConstantArrayType(
4088 EltTy: E.withConst(),
4089 ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()),
4090 List->getNumInits()),
4091 SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0);
4092 InitializedEntity HiddenArray =
4093 InitializedEntity::InitializeTemporary(Type: ArrayType);
4094 InitializationKind Kind = InitializationKind::CreateDirectList(
4095 List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4096 TryListInitialization(S, Entity: HiddenArray, Kind, InitList: List, Sequence,
4097 TreatUnavailableAsInvalid);
4098 if (Sequence)
4099 Sequence.AddStdInitializerListConstructionStep(T: DestType);
4100 return true;
4101}
4102
4103/// Determine if the constructor has the signature of a copy or move
4104/// constructor for the type T of the class in which it was found. That is,
4105/// determine if its first parameter is of type T or reference to (possibly
4106/// cv-qualified) T.
4107static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
4108 const ConstructorInfo &Info) {
4109 if (Info.Constructor->getNumParams() == 0)
4110 return false;
4111
4112 QualType ParmT =
4113 Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
4114 QualType ClassT =
4115 Ctx.getRecordType(Decl: cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4116
4117 return Ctx.hasSameUnqualifiedType(T1: ParmT, T2: ClassT);
4118}
4119
4120static OverloadingResult ResolveConstructorOverload(
4121 Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4122 OverloadCandidateSet &CandidateSet, QualType DestType,
4123 DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,
4124 bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4125 bool IsListInit, bool RequireActualConstructor,
4126 bool SecondStepOfCopyInit = false) {
4127 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByConstructor);
4128 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4129
4130 for (NamedDecl *D : Ctors) {
4131 auto Info = getConstructorInfo(ND: D);
4132 if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4133 continue;
4134
4135 if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4136 continue;
4137
4138 // C++11 [over.best.ics]p4:
4139 // ... and the constructor or user-defined conversion function is a
4140 // candidate by
4141 // - 13.3.1.3, when the argument is the temporary in the second step
4142 // of a class copy-initialization, or
4143 // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4144 // - the second phase of 13.3.1.7 when the initializer list has exactly
4145 // one element that is itself an initializer list, and the target is
4146 // the first parameter of a constructor of class X, and the conversion
4147 // is to X or reference to (possibly cv-qualified X),
4148 // user-defined conversion sequences are not considered.
4149 bool SuppressUserConversions =
4150 SecondStepOfCopyInit ||
4151 (IsListInit && Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) &&
4152 hasCopyOrMoveCtorParam(Ctx&: S.Context, Info));
4153
4154 if (Info.ConstructorTmpl)
4155 S.AddTemplateOverloadCandidate(
4156 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4157 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args, CandidateSet, SuppressUserConversions,
4158 /*PartialOverloading=*/false, AllowExplicit);
4159 else {
4160 // C++ [over.match.copy]p1:
4161 // - When initializing a temporary to be bound to the first parameter
4162 // of a constructor [for type T] that takes a reference to possibly
4163 // cv-qualified T as its first argument, called with a single
4164 // argument in the context of direct-initialization, explicit
4165 // conversion functions are also considered.
4166 // FIXME: What if a constructor template instantiates to such a signature?
4167 bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4168 Args.size() == 1 &&
4169 hasCopyOrMoveCtorParam(Ctx&: S.Context, Info);
4170 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4171 CandidateSet, SuppressUserConversions,
4172 /*PartialOverloading=*/false, AllowExplicit,
4173 AllowExplicitConv);
4174 }
4175 }
4176
4177 // FIXME: Work around a bug in C++17 guaranteed copy elision.
4178 //
4179 // When initializing an object of class type T by constructor
4180 // ([over.match.ctor]) or by list-initialization ([over.match.list])
4181 // from a single expression of class type U, conversion functions of
4182 // U that convert to the non-reference type cv T are candidates.
4183 // Explicit conversion functions are only candidates during
4184 // direct-initialization.
4185 //
4186 // Note: SecondStepOfCopyInit is only ever true in this case when
4187 // evaluating whether to produce a C++98 compatibility warning.
4188 if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4189 !RequireActualConstructor && !SecondStepOfCopyInit) {
4190 Expr *Initializer = Args[0];
4191 auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4192 if (SourceRD && S.isCompleteType(Loc: DeclLoc, T: Initializer->getType())) {
4193 const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4194 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4195 NamedDecl *D = *I;
4196 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4197 D = D->getUnderlyingDecl();
4198
4199 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
4200 CXXConversionDecl *Conv;
4201 if (ConvTemplate)
4202 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4203 else
4204 Conv = cast<CXXConversionDecl>(Val: D);
4205
4206 if (ConvTemplate)
4207 S.AddTemplateConversionCandidate(
4208 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
4209 CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit,
4210 /*AllowResultConversion*/ false);
4211 else
4212 S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer,
4213 ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit,
4214 AllowExplicit,
4215 /*AllowResultConversion*/ false);
4216 }
4217 }
4218 }
4219
4220 // Perform overload resolution and return the result.
4221 return CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best);
4222}
4223
4224/// Attempt initialization by constructor (C++ [dcl.init]), which
4225/// enumerates the constructors of the initialized entity and performs overload
4226/// resolution to select the best.
4227/// \param DestType The destination class type.
4228/// \param DestArrayType The destination type, which is either DestType or
4229/// a (possibly multidimensional) array of DestType.
4230/// \param IsListInit Is this list-initialization?
4231/// \param IsInitListCopy Is this non-list-initialization resulting from a
4232/// list-initialization from {x} where x is the same
4233/// type as the entity?
4234static void TryConstructorInitialization(Sema &S,
4235 const InitializedEntity &Entity,
4236 const InitializationKind &Kind,
4237 MultiExprArg Args, QualType DestType,
4238 QualType DestArrayType,
4239 InitializationSequence &Sequence,
4240 bool IsListInit = false,
4241 bool IsInitListCopy = false) {
4242 assert(((!IsListInit && !IsInitListCopy) ||
4243 (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4244 "IsListInit/IsInitListCopy must come with a single initializer list "
4245 "argument.");
4246 InitListExpr *ILE =
4247 (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Val: Args[0]) : nullptr;
4248 MultiExprArg UnwrappedArgs =
4249 ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4250
4251 // The type we're constructing needs to be complete.
4252 if (!S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) {
4253 Sequence.setIncompleteTypeFailure(DestType);
4254 return;
4255 }
4256
4257 bool RequireActualConstructor =
4258 !(Entity.getKind() != InitializedEntity::EK_Base &&
4259 Entity.getKind() != InitializedEntity::EK_Delegating &&
4260 Entity.getKind() !=
4261 InitializedEntity::EK_LambdaToBlockConversionBlockElement);
4262
4263 // C++17 [dcl.init]p17:
4264 // - If the initializer expression is a prvalue and the cv-unqualified
4265 // version of the source type is the same class as the class of the
4266 // destination, the initializer expression is used to initialize the
4267 // destination object.
4268 // Per DR (no number yet), this does not apply when initializing a base
4269 // class or delegating to another constructor from a mem-initializer.
4270 // ObjC++: Lambda captured by the block in the lambda to block conversion
4271 // should avoid copy elision.
4272 if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4273 UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4274 S.Context.hasSameUnqualifiedType(T1: UnwrappedArgs[0]->getType(), T2: DestType)) {
4275 // Convert qualifications if necessary.
4276 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
4277 if (ILE)
4278 Sequence.RewrapReferenceInitList(T: DestType, Syntactic: ILE);
4279 return;
4280 }
4281
4282 const RecordType *DestRecordType = DestType->getAs<RecordType>();
4283 assert(DestRecordType && "Constructor initialization requires record type");
4284 CXXRecordDecl *DestRecordDecl
4285 = cast<CXXRecordDecl>(Val: DestRecordType->getDecl());
4286
4287 // Build the candidate set directly in the initialization sequence
4288 // structure, so that it will persist if we fail.
4289 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4290
4291 // Determine whether we are allowed to call explicit constructors or
4292 // explicit conversion operators.
4293 bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4294 bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4295
4296 // - Otherwise, if T is a class type, constructors are considered. The
4297 // applicable constructors are enumerated, and the best one is chosen
4298 // through overload resolution.
4299 DeclContext::lookup_result Ctors = S.LookupConstructors(Class: DestRecordDecl);
4300
4301 OverloadingResult Result = OR_No_Viable_Function;
4302 OverloadCandidateSet::iterator Best;
4303 bool AsInitializerList = false;
4304
4305 // C++11 [over.match.list]p1, per DR1467:
4306 // When objects of non-aggregate type T are list-initialized, such that
4307 // 8.5.4 [dcl.init.list] specifies that overload resolution is performed
4308 // according to the rules in this section, overload resolution selects
4309 // the constructor in two phases:
4310 //
4311 // - Initially, the candidate functions are the initializer-list
4312 // constructors of the class T and the argument list consists of the
4313 // initializer list as a single argument.
4314 if (IsListInit) {
4315 AsInitializerList = true;
4316
4317 // If the initializer list has no elements and T has a default constructor,
4318 // the first phase is omitted.
4319 if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(Class: DestRecordDecl)))
4320 Result = ResolveConstructorOverload(
4321 S, DeclLoc: Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4322 CopyInitializing: CopyInitialization, AllowExplicit,
4323 /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4324 }
4325
4326 // C++11 [over.match.list]p1:
4327 // - If no viable initializer-list constructor is found, overload resolution
4328 // is performed again, where the candidate functions are all the
4329 // constructors of the class T and the argument list consists of the
4330 // elements of the initializer list.
4331 if (Result == OR_No_Viable_Function) {
4332 AsInitializerList = false;
4333 Result = ResolveConstructorOverload(
4334 S, DeclLoc: Kind.getLocation(), Args: UnwrappedArgs, CandidateSet, DestType, Ctors,
4335 Best, CopyInitializing: CopyInitialization, AllowExplicit,
4336 /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4337 }
4338 if (Result) {
4339 Sequence.SetOverloadFailure(
4340 Failure: IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4341 : InitializationSequence::FK_ConstructorOverloadFailed,
4342 Result);
4343
4344 if (Result != OR_Deleted)
4345 return;
4346 }
4347
4348 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4349
4350 // In C++17, ResolveConstructorOverload can select a conversion function
4351 // instead of a constructor.
4352 if (auto *CD = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4353 // Add the user-defined conversion step that calls the conversion function.
4354 QualType ConvType = CD->getConversionType();
4355 assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4356 "should not have selected this conversion function");
4357 Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4358 HadMultipleCandidates);
4359 if (!S.Context.hasSameType(T1: ConvType, T2: DestType))
4360 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
4361 if (IsListInit)
4362 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: ILE);
4363 return;
4364 }
4365
4366 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
4367 if (Result != OR_Deleted) {
4368 // C++11 [dcl.init]p6:
4369 // If a program calls for the default initialization of an object
4370 // of a const-qualified type T, T shall be a class type with a
4371 // user-provided default constructor.
4372 // C++ core issue 253 proposal:
4373 // If the implicit default constructor initializes all subobjects, no
4374 // initializer should be required.
4375 // The 253 proposal is for example needed to process libstdc++ headers
4376 // in 5.x.
4377 if (Kind.getKind() == InitializationKind::IK_Default &&
4378 Entity.getType().isConstQualified()) {
4379 if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4380 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4381 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4382 return;
4383 }
4384 }
4385
4386 // C++11 [over.match.list]p1:
4387 // In copy-list-initialization, if an explicit constructor is chosen, the
4388 // initializer is ill-formed.
4389 if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4390 Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4391 return;
4392 }
4393 }
4394
4395 // [class.copy.elision]p3:
4396 // In some copy-initialization contexts, a two-stage overload resolution
4397 // is performed.
4398 // If the first overload resolution selects a deleted function, we also
4399 // need the initialization sequence to decide whether to perform the second
4400 // overload resolution.
4401 // For deleted functions in other contexts, there is no need to get the
4402 // initialization sequence.
4403 if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4404 return;
4405
4406 // Add the constructor initialization step. Any cv-qualification conversion is
4407 // subsumed by the initialization.
4408 Sequence.AddConstructorInitializationStep(
4409 FoundDecl: Best->FoundDecl, Constructor: CtorDecl, T: DestArrayType, HadMultipleCandidates,
4410 FromInitList: IsListInit | IsInitListCopy, AsInitList: AsInitializerList);
4411}
4412
4413static bool
4414ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4415 Expr *Initializer,
4416 QualType &SourceType,
4417 QualType &UnqualifiedSourceType,
4418 QualType UnqualifiedTargetType,
4419 InitializationSequence &Sequence) {
4420 if (S.Context.getCanonicalType(T: UnqualifiedSourceType) ==
4421 S.Context.OverloadTy) {
4422 DeclAccessPair Found;
4423 bool HadMultipleCandidates = false;
4424 if (FunctionDecl *Fn
4425 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer,
4426 TargetType: UnqualifiedTargetType,
4427 Complain: false, Found,
4428 pHadMultipleCandidates: &HadMultipleCandidates)) {
4429 Sequence.AddAddressOverloadResolutionStep(Function: Fn, Found,
4430 HadMultipleCandidates);
4431 SourceType = Fn->getType();
4432 UnqualifiedSourceType = SourceType.getUnqualifiedType();
4433 } else if (!UnqualifiedTargetType->isRecordType()) {
4434 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4435 return true;
4436 }
4437 }
4438 return false;
4439}
4440
4441static void TryReferenceInitializationCore(Sema &S,
4442 const InitializedEntity &Entity,
4443 const InitializationKind &Kind,
4444 Expr *Initializer,
4445 QualType cv1T1, QualType T1,
4446 Qualifiers T1Quals,
4447 QualType cv2T2, QualType T2,
4448 Qualifiers T2Quals,
4449 InitializationSequence &Sequence,
4450 bool TopLevelOfInitList);
4451
4452static void TryValueInitialization(Sema &S,
4453 const InitializedEntity &Entity,
4454 const InitializationKind &Kind,
4455 InitializationSequence &Sequence,
4456 InitListExpr *InitList = nullptr);
4457
4458/// Attempt list initialization of a reference.
4459static void TryReferenceListInitialization(Sema &S,
4460 const InitializedEntity &Entity,
4461 const InitializationKind &Kind,
4462 InitListExpr *InitList,
4463 InitializationSequence &Sequence,
4464 bool TreatUnavailableAsInvalid) {
4465 // First, catch C++03 where this isn't possible.
4466 if (!S.getLangOpts().CPlusPlus11) {
4467 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4468 return;
4469 }
4470 // Can't reference initialize a compound literal.
4471 if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4472 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4473 return;
4474 }
4475
4476 QualType DestType = Entity.getType();
4477 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4478 Qualifiers T1Quals;
4479 QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals);
4480
4481 // Reference initialization via an initializer list works thus:
4482 // If the initializer list consists of a single element that is
4483 // reference-related to the referenced type, bind directly to that element
4484 // (possibly creating temporaries).
4485 // Otherwise, initialize a temporary with the initializer list and
4486 // bind to that.
4487 if (InitList->getNumInits() == 1) {
4488 Expr *Initializer = InitList->getInit(Init: 0);
4489 QualType cv2T2 = S.getCompletedType(E: Initializer);
4490 Qualifiers T2Quals;
4491 QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals);
4492
4493 // If this fails, creating a temporary wouldn't work either.
4494 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2,
4495 UnqualifiedTargetType: T1, Sequence))
4496 return;
4497
4498 SourceLocation DeclLoc = Initializer->getBeginLoc();
4499 Sema::ReferenceCompareResult RefRelationship
4500 = S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2);
4501 if (RefRelationship >= Sema::Ref_Related) {
4502 // Try to bind the reference here.
4503 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4504 T1Quals, cv2T2, T2, T2Quals, Sequence,
4505 /*TopLevelOfInitList=*/true);
4506 if (Sequence)
4507 Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList);
4508 return;
4509 }
4510
4511 // Update the initializer if we've resolved an overloaded function.
4512 if (Sequence.step_begin() != Sequence.step_end())
4513 Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList);
4514 }
4515 // Perform address space compatibility check.
4516 QualType cv1T1IgnoreAS = cv1T1;
4517 if (T1Quals.hasAddressSpace()) {
4518 Qualifiers T2Quals;
4519 (void)S.Context.getUnqualifiedArrayType(T: InitList->getType(), Quals&: T2Quals);
4520 if (!T1Quals.isAddressSpaceSupersetOf(other: T2Quals)) {
4521 Sequence.SetFailed(
4522 InitializationSequence::FK_ReferenceInitDropsQualifiers);
4523 return;
4524 }
4525 // Ignore address space of reference type at this point and perform address
4526 // space conversion after the reference binding step.
4527 cv1T1IgnoreAS =
4528 S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace());
4529 }
4530 // Not reference-related. Create a temporary and bind to that.
4531 InitializedEntity TempEntity =
4532 InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS);
4533
4534 TryListInitialization(S, Entity: TempEntity, Kind, InitList, Sequence,
4535 TreatUnavailableAsInvalid);
4536 if (Sequence) {
4537 if (DestType->isRValueReferenceType() ||
4538 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4539 if (S.getLangOpts().CPlusPlus20 &&
4540 isa<IncompleteArrayType>(Val: T1->getUnqualifiedDesugaredType()) &&
4541 DestType->isRValueReferenceType()) {
4542 // C++20 [dcl.init.list]p3.10:
4543 // List-initialization of an object or reference of type T is defined as
4544 // follows:
4545 // ..., unless T is “reference to array of unknown bound of U”, in which
4546 // case the type of the prvalue is the type of x in the declaration U
4547 // x[] H, where H is the initializer list.
4548 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: clang::VK_PRValue);
4549 }
4550 Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS,
4551 /*BindingTemporary=*/true);
4552 if (T1Quals.hasAddressSpace())
4553 Sequence.AddQualificationConversionStep(
4554 Ty: cv1T1, VK: DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4555 } else
4556 Sequence.SetFailed(
4557 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4558 }
4559}
4560
4561/// Attempt list initialization (C++0x [dcl.init.list])
4562static void TryListInitialization(Sema &S,
4563 const InitializedEntity &Entity,
4564 const InitializationKind &Kind,
4565 InitListExpr *InitList,
4566 InitializationSequence &Sequence,
4567 bool TreatUnavailableAsInvalid) {
4568 QualType DestType = Entity.getType();
4569
4570 // C++ doesn't allow scalar initialization with more than one argument.
4571 // But C99 complex numbers are scalars and it makes sense there.
4572 if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4573 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4574 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4575 return;
4576 }
4577 if (DestType->isReferenceType()) {
4578 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4579 TreatUnavailableAsInvalid);
4580 return;
4581 }
4582
4583 if (DestType->isRecordType() &&
4584 !S.isCompleteType(Loc: InitList->getBeginLoc(), T: DestType)) {
4585 Sequence.setIncompleteTypeFailure(DestType);
4586 return;
4587 }
4588
4589 // C++20 [dcl.init.list]p3:
4590 // - If the braced-init-list contains a designated-initializer-list, T shall
4591 // be an aggregate class. [...] Aggregate initialization is performed.
4592 //
4593 // We allow arrays here too in order to support array designators.
4594 //
4595 // FIXME: This check should precede the handling of reference initialization.
4596 // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4597 // as a tentative DR resolution.
4598 bool IsDesignatedInit = InitList->hasDesignatedInit();
4599 if (!DestType->isAggregateType() && IsDesignatedInit) {
4600 Sequence.SetFailed(
4601 InitializationSequence::FK_DesignatedInitForNonAggregate);
4602 return;
4603 }
4604
4605 // C++11 [dcl.init.list]p3, per DR1467:
4606 // - If T is a class type and the initializer list has a single element of
4607 // type cv U, where U is T or a class derived from T, the object is
4608 // initialized from that element (by copy-initialization for
4609 // copy-list-initialization, or by direct-initialization for
4610 // direct-list-initialization).
4611 // - Otherwise, if T is a character array and the initializer list has a
4612 // single element that is an appropriately-typed string literal
4613 // (8.5.2 [dcl.init.string]), initialization is performed as described
4614 // in that section.
4615 // - Otherwise, if T is an aggregate, [...] (continue below).
4616 if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4617 !IsDesignatedInit) {
4618 if (DestType->isRecordType()) {
4619 QualType InitType = InitList->getInit(Init: 0)->getType();
4620 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: DestType) ||
4621 S.IsDerivedFrom(Loc: InitList->getBeginLoc(), Derived: InitType, Base: DestType)) {
4622 Expr *InitListAsExpr = InitList;
4623 TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType,
4624 DestArrayType: DestType, Sequence,
4625 /*InitListSyntax*/IsListInit: false,
4626 /*IsInitListCopy*/true);
4627 return;
4628 }
4629 }
4630 if (const ArrayType *DestAT = S.Context.getAsArrayType(T: DestType)) {
4631 Expr *SubInit[1] = {InitList->getInit(Init: 0)};
4632 if (!isa<VariableArrayType>(Val: DestAT) &&
4633 IsStringInit(Init: SubInit[0], AT: DestAT, Context&: S.Context) == SIF_None) {
4634 InitializationKind SubKind =
4635 Kind.getKind() == InitializationKind::IK_DirectList
4636 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
4637 LParenLoc: InitList->getLBraceLoc(),
4638 RParenLoc: InitList->getRBraceLoc())
4639 : Kind;
4640 Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit,
4641 /*TopLevelOfInitList*/ true,
4642 TreatUnavailableAsInvalid);
4643
4644 // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4645 // the element is not an appropriately-typed string literal, in which
4646 // case we should proceed as in C++11 (below).
4647 if (Sequence) {
4648 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
4649 return;
4650 }
4651 }
4652 }
4653 }
4654
4655 // C++11 [dcl.init.list]p3:
4656 // - If T is an aggregate, aggregate initialization is performed.
4657 if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4658 (S.getLangOpts().CPlusPlus11 &&
4659 S.isStdInitializerList(Ty: DestType, Element: nullptr) && !IsDesignatedInit)) {
4660 if (S.getLangOpts().CPlusPlus11) {
4661 // - Otherwise, if the initializer list has no elements and T is a
4662 // class type with a default constructor, the object is
4663 // value-initialized.
4664 if (InitList->getNumInits() == 0) {
4665 CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4666 if (S.LookupDefaultConstructor(Class: RD)) {
4667 TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4668 return;
4669 }
4670 }
4671
4672 // - Otherwise, if T is a specialization of std::initializer_list<E>,
4673 // an initializer_list object constructed [...]
4674 if (TryInitializerListConstruction(S, List: InitList, DestType, Sequence,
4675 TreatUnavailableAsInvalid))
4676 return;
4677
4678 // - Otherwise, if T is a class type, constructors are considered.
4679 Expr *InitListAsExpr = InitList;
4680 TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType,
4681 DestArrayType: DestType, Sequence, /*InitListSyntax*/IsListInit: true);
4682 } else
4683 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4684 return;
4685 }
4686
4687 if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4688 InitList->getNumInits() == 1) {
4689 Expr *E = InitList->getInit(Init: 0);
4690
4691 // - Otherwise, if T is an enumeration with a fixed underlying type,
4692 // the initializer-list has a single element v, and the initialization
4693 // is direct-list-initialization, the object is initialized with the
4694 // value T(v); if a narrowing conversion is required to convert v to
4695 // the underlying type of T, the program is ill-formed.
4696 auto *ET = DestType->getAs<EnumType>();
4697 if (S.getLangOpts().CPlusPlus17 &&
4698 Kind.getKind() == InitializationKind::IK_DirectList &&
4699 ET && ET->getDecl()->isFixed() &&
4700 !S.Context.hasSameUnqualifiedType(T1: E->getType(), T2: DestType) &&
4701 (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4702 E->getType()->isFloatingType())) {
4703 // There are two ways that T(v) can work when T is an enumeration type.
4704 // If there is either an implicit conversion sequence from v to T or
4705 // a conversion function that can convert from v to T, then we use that.
4706 // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4707 // type, it is converted to the enumeration type via its underlying type.
4708 // There is no overlap possible between these two cases (except when the
4709 // source value is already of the destination type), and the first
4710 // case is handled by the general case for single-element lists below.
4711 ImplicitConversionSequence ICS;
4712 ICS.setStandard();
4713 ICS.Standard.setAsIdentityConversion();
4714 if (!E->isPRValue())
4715 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4716 // If E is of a floating-point type, then the conversion is ill-formed
4717 // due to narrowing, but go through the motions in order to produce the
4718 // right diagnostic.
4719 ICS.Standard.Second = E->getType()->isFloatingType()
4720 ? ICK_Floating_Integral
4721 : ICK_Integral_Conversion;
4722 ICS.Standard.setFromType(E->getType());
4723 ICS.Standard.setToType(Idx: 0, T: E->getType());
4724 ICS.Standard.setToType(Idx: 1, T: DestType);
4725 ICS.Standard.setToType(Idx: 2, T: DestType);
4726 Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2),
4727 /*TopLevelOfInitList*/true);
4728 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
4729 return;
4730 }
4731
4732 // - Otherwise, if the initializer list has a single element of type E
4733 // [...references are handled above...], the object or reference is
4734 // initialized from that element (by copy-initialization for
4735 // copy-list-initialization, or by direct-initialization for
4736 // direct-list-initialization); if a narrowing conversion is required
4737 // to convert the element to T, the program is ill-formed.
4738 //
4739 // Per core-24034, this is direct-initialization if we were performing
4740 // direct-list-initialization and copy-initialization otherwise.
4741 // We can't use InitListChecker for this, because it always performs
4742 // copy-initialization. This only matters if we might use an 'explicit'
4743 // conversion operator, or for the special case conversion of nullptr_t to
4744 // bool, so we only need to handle those cases.
4745 //
4746 // FIXME: Why not do this in all cases?
4747 Expr *Init = InitList->getInit(Init: 0);
4748 if (Init->getType()->isRecordType() ||
4749 (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4750 InitializationKind SubKind =
4751 Kind.getKind() == InitializationKind::IK_DirectList
4752 ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(),
4753 LParenLoc: InitList->getLBraceLoc(),
4754 RParenLoc: InitList->getRBraceLoc())
4755 : Kind;
4756 Expr *SubInit[1] = { Init };
4757 Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit,
4758 /*TopLevelOfInitList*/true,
4759 TreatUnavailableAsInvalid);
4760 if (Sequence)
4761 Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList);
4762 return;
4763 }
4764 }
4765
4766 InitListChecker CheckInitList(S, Entity, InitList,
4767 DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4768 if (CheckInitList.HadError()) {
4769 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4770 return;
4771 }
4772
4773 // Add the list initialization step with the built init list.
4774 Sequence.AddListInitializationStep(T: DestType);
4775}
4776
4777/// Try a reference initialization that involves calling a conversion
4778/// function.
4779static OverloadingResult TryRefInitWithConversionFunction(
4780 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4781 Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4782 InitializationSequence &Sequence) {
4783 QualType DestType = Entity.getType();
4784 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4785 QualType T1 = cv1T1.getUnqualifiedType();
4786 QualType cv2T2 = Initializer->getType();
4787 QualType T2 = cv2T2.getUnqualifiedType();
4788
4789 assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4790 "Must have incompatible references when binding via conversion");
4791
4792 // Build the candidate set directly in the initialization sequence
4793 // structure, so that it will persist if we fail.
4794 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4795 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4796
4797 // Determine whether we are allowed to call explicit conversion operators.
4798 // Note that none of [over.match.copy], [over.match.conv], nor
4799 // [over.match.ref] permit an explicit constructor to be chosen when
4800 // initializing a reference, not even for direct-initialization.
4801 bool AllowExplicitCtors = false;
4802 bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4803
4804 const RecordType *T1RecordType = nullptr;
4805 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4806 S.isCompleteType(Loc: Kind.getLocation(), T: T1)) {
4807 // The type we're converting to is a class type. Enumerate its constructors
4808 // to see if there is a suitable conversion.
4809 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(Val: T1RecordType->getDecl());
4810
4811 for (NamedDecl *D : S.LookupConstructors(Class: T1RecordDecl)) {
4812 auto Info = getConstructorInfo(ND: D);
4813 if (!Info.Constructor)
4814 continue;
4815
4816 if (!Info.Constructor->isInvalidDecl() &&
4817 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4818 if (Info.ConstructorTmpl)
4819 S.AddTemplateOverloadCandidate(
4820 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4821 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet,
4822 /*SuppressUserConversions=*/true,
4823 /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors);
4824 else
4825 S.AddOverloadCandidate(
4826 Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4827 /*SuppressUserConversions=*/true,
4828 /*PartialOverloading*/ false, AllowExplicitCtors);
4829 }
4830 }
4831 }
4832 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4833 return OR_No_Viable_Function;
4834
4835 const RecordType *T2RecordType = nullptr;
4836 if ((T2RecordType = T2->getAs<RecordType>()) &&
4837 S.isCompleteType(Loc: Kind.getLocation(), T: T2)) {
4838 // The type we're converting from is a class type, enumerate its conversion
4839 // functions.
4840 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(Val: T2RecordType->getDecl());
4841
4842 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4843 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4844 NamedDecl *D = *I;
4845 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4846 if (isa<UsingShadowDecl>(Val: D))
4847 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4848
4849 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
4850 CXXConversionDecl *Conv;
4851 if (ConvTemplate)
4852 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4853 else
4854 Conv = cast<CXXConversionDecl>(Val: D);
4855
4856 // If the conversion function doesn't return a reference type,
4857 // it can't be considered for this conversion unless we're allowed to
4858 // consider rvalues.
4859 // FIXME: Do we need to make sure that we only consider conversion
4860 // candidates with reference-compatible results? That might be needed to
4861 // break recursion.
4862 if ((AllowRValues ||
4863 Conv->getConversionType()->isLValueReferenceType())) {
4864 if (ConvTemplate)
4865 S.AddTemplateConversionCandidate(
4866 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
4867 CandidateSet,
4868 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs);
4869 else
4870 S.AddConversionCandidate(
4871 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, CandidateSet,
4872 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs);
4873 }
4874 }
4875 }
4876 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4877 return OR_No_Viable_Function;
4878
4879 SourceLocation DeclLoc = Initializer->getBeginLoc();
4880
4881 // Perform overload resolution. If it fails, return the failed result.
4882 OverloadCandidateSet::iterator Best;
4883 if (OverloadingResult Result
4884 = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best))
4885 return Result;
4886
4887 FunctionDecl *Function = Best->Function;
4888 // This is the overload that will be used for this initialization step if we
4889 // use this initialization. Mark it as referenced.
4890 Function->setReferenced();
4891
4892 // Compute the returned type and value kind of the conversion.
4893 QualType cv3T3;
4894 if (isa<CXXConversionDecl>(Val: Function))
4895 cv3T3 = Function->getReturnType();
4896 else
4897 cv3T3 = T1;
4898
4899 ExprValueKind VK = VK_PRValue;
4900 if (cv3T3->isLValueReferenceType())
4901 VK = VK_LValue;
4902 else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4903 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4904 cv3T3 = cv3T3.getNonLValueExprType(Context: S.Context);
4905
4906 // Add the user-defined conversion step.
4907 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4908 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: cv3T3,
4909 HadMultipleCandidates);
4910
4911 // Determine whether we'll need to perform derived-to-base adjustments or
4912 // other conversions.
4913 Sema::ReferenceConversions RefConv;
4914 Sema::ReferenceCompareResult NewRefRelationship =
4915 S.CompareReferenceRelationship(Loc: DeclLoc, T1, T2: cv3T3, Conv: &RefConv);
4916
4917 // Add the final conversion sequence, if necessary.
4918 if (NewRefRelationship == Sema::Ref_Incompatible) {
4919 assert(!isa<CXXConstructorDecl>(Function) &&
4920 "should not have conversion after constructor");
4921
4922 ImplicitConversionSequence ICS;
4923 ICS.setStandard();
4924 ICS.Standard = Best->FinalConversion;
4925 Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2));
4926
4927 // Every implicit conversion results in a prvalue, except for a glvalue
4928 // derived-to-base conversion, which we handle below.
4929 cv3T3 = ICS.Standard.getToType(Idx: 2);
4930 VK = VK_PRValue;
4931 }
4932
4933 // If the converted initializer is a prvalue, its type T4 is adjusted to
4934 // type "cv1 T4" and the temporary materialization conversion is applied.
4935 //
4936 // We adjust the cv-qualifications to match the reference regardless of
4937 // whether we have a prvalue so that the AST records the change. In this
4938 // case, T4 is "cv3 T3".
4939 QualType cv1T4 = S.Context.getQualifiedType(T: cv3T3, Qs: cv1T1.getQualifiers());
4940 if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4941 Sequence.AddQualificationConversionStep(Ty: cv1T4, VK);
4942 Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: VK == VK_PRValue);
4943 VK = IsLValueRef ? VK_LValue : VK_XValue;
4944
4945 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4946 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK);
4947 else if (RefConv & Sema::ReferenceConversions::ObjC)
4948 Sequence.AddObjCObjectConversionStep(T: cv1T1);
4949 else if (RefConv & Sema::ReferenceConversions::Function)
4950 Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1);
4951 else if (RefConv & Sema::ReferenceConversions::Qualification) {
4952 if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1))
4953 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK);
4954 }
4955
4956 return OR_Success;
4957}
4958
4959static void CheckCXX98CompatAccessibleCopy(Sema &S,
4960 const InitializedEntity &Entity,
4961 Expr *CurInitExpr);
4962
4963/// Attempt reference initialization (C++0x [dcl.init.ref])
4964static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,
4965 const InitializationKind &Kind,
4966 Expr *Initializer,
4967 InitializationSequence &Sequence,
4968 bool TopLevelOfInitList) {
4969 QualType DestType = Entity.getType();
4970 QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4971 Qualifiers T1Quals;
4972 QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals);
4973 QualType cv2T2 = S.getCompletedType(E: Initializer);
4974 Qualifiers T2Quals;
4975 QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals);
4976
4977 // If the initializer is the address of an overloaded function, try
4978 // to resolve the overloaded function. If all goes well, T2 is the
4979 // type of the resulting function.
4980 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2,
4981 UnqualifiedTargetType: T1, Sequence))
4982 return;
4983
4984 // Delegate everything else to a subfunction.
4985 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4986 T1Quals, cv2T2, T2, T2Quals, Sequence,
4987 TopLevelOfInitList);
4988}
4989
4990/// Determine whether an expression is a non-referenceable glvalue (one to
4991/// which a reference can never bind). Attempting to bind a reference to
4992/// such a glvalue will always create a temporary.
4993static bool isNonReferenceableGLValue(Expr *E) {
4994 return E->refersToBitField() || E->refersToVectorElement() ||
4995 E->refersToMatrixElement();
4996}
4997
4998/// Reference initialization without resolving overloaded functions.
4999///
5000/// We also can get here in C if we call a builtin which is declared as
5001/// a function with a parameter of reference type (such as __builtin_va_end()).
5002static void TryReferenceInitializationCore(Sema &S,
5003 const InitializedEntity &Entity,
5004 const InitializationKind &Kind,
5005 Expr *Initializer,
5006 QualType cv1T1, QualType T1,
5007 Qualifiers T1Quals,
5008 QualType cv2T2, QualType T2,
5009 Qualifiers T2Quals,
5010 InitializationSequence &Sequence,
5011 bool TopLevelOfInitList) {
5012 QualType DestType = Entity.getType();
5013 SourceLocation DeclLoc = Initializer->getBeginLoc();
5014
5015 // Compute some basic properties of the types and the initializer.
5016 bool isLValueRef = DestType->isLValueReferenceType();
5017 bool isRValueRef = !isLValueRef;
5018 Expr::Classification InitCategory = Initializer->Classify(Ctx&: S.Context);
5019
5020 Sema::ReferenceConversions RefConv;
5021 Sema::ReferenceCompareResult RefRelationship =
5022 S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2, Conv: &RefConv);
5023
5024 // C++0x [dcl.init.ref]p5:
5025 // A reference to type "cv1 T1" is initialized by an expression of type
5026 // "cv2 T2" as follows:
5027 //
5028 // - If the reference is an lvalue reference and the initializer
5029 // expression
5030 // Note the analogous bullet points for rvalue refs to functions. Because
5031 // there are no function rvalues in C++, rvalue refs to functions are treated
5032 // like lvalue refs.
5033 OverloadingResult ConvOvlResult = OR_Success;
5034 bool T1Function = T1->isFunctionType();
5035 if (isLValueRef || T1Function) {
5036 if (InitCategory.isLValue() && !isNonReferenceableGLValue(E: Initializer) &&
5037 (RefRelationship == Sema::Ref_Compatible ||
5038 (Kind.isCStyleOrFunctionalCast() &&
5039 RefRelationship == Sema::Ref_Related))) {
5040 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
5041 // reference-compatible with "cv2 T2," or
5042 if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5043 Sema::ReferenceConversions::ObjC)) {
5044 // If we're converting the pointee, add any qualifiers first;
5045 // these qualifiers must all be top-level, so just convert to "cv1 T2".
5046 if (RefConv & (Sema::ReferenceConversions::Qualification))
5047 Sequence.AddQualificationConversionStep(
5048 Ty: S.Context.getQualifiedType(T: T2, Qs: T1Quals),
5049 VK: Initializer->getValueKind());
5050 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5051 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: VK_LValue);
5052 else
5053 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5054 } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5055 // Perform a (possibly multi-level) qualification conversion.
5056 Sequence.AddQualificationConversionStep(Ty: cv1T1,
5057 VK: Initializer->getValueKind());
5058 } else if (RefConv & Sema::ReferenceConversions::Function) {
5059 Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1);
5060 }
5061
5062 // We only create a temporary here when binding a reference to a
5063 // bit-field or vector element. Those cases are't supposed to be
5064 // handled by this bullet, but the outcome is the same either way.
5065 Sequence.AddReferenceBindingStep(T: cv1T1, BindingTemporary: false);
5066 return;
5067 }
5068
5069 // - has a class type (i.e., T2 is a class type), where T1 is not
5070 // reference-related to T2, and can be implicitly converted to an
5071 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5072 // with "cv3 T3" (this conversion is selected by enumerating the
5073 // applicable conversion functions (13.3.1.6) and choosing the best
5074 // one through overload resolution (13.3)),
5075 // If we have an rvalue ref to function type here, the rhs must be
5076 // an rvalue. DR1287 removed the "implicitly" here.
5077 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5078 (isLValueRef || InitCategory.isRValue())) {
5079 if (S.getLangOpts().CPlusPlus) {
5080 // Try conversion functions only for C++.
5081 ConvOvlResult = TryRefInitWithConversionFunction(
5082 S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5083 /*IsLValueRef*/ isLValueRef, Sequence);
5084 if (ConvOvlResult == OR_Success)
5085 return;
5086 if (ConvOvlResult != OR_No_Viable_Function)
5087 Sequence.SetOverloadFailure(
5088 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5089 Result: ConvOvlResult);
5090 } else {
5091 ConvOvlResult = OR_No_Viable_Function;
5092 }
5093 }
5094 }
5095
5096 // - Otherwise, the reference shall be an lvalue reference to a
5097 // non-volatile const type (i.e., cv1 shall be const), or the reference
5098 // shall be an rvalue reference.
5099 // For address spaces, we interpret this to mean that an addr space
5100 // of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5101 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5102 T1Quals.isAddressSpaceSupersetOf(other: T2Quals))) {
5103 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy)
5104 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5105 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5106 Sequence.SetOverloadFailure(
5107 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5108 Result: ConvOvlResult);
5109 else if (!InitCategory.isLValue())
5110 Sequence.SetFailed(
5111 T1Quals.isAddressSpaceSupersetOf(other: T2Quals)
5112 ? InitializationSequence::
5113 FK_NonConstLValueReferenceBindingToTemporary
5114 : InitializationSequence::FK_ReferenceInitDropsQualifiers);
5115 else {
5116 InitializationSequence::FailureKind FK;
5117 switch (RefRelationship) {
5118 case Sema::Ref_Compatible:
5119 if (Initializer->refersToBitField())
5120 FK = InitializationSequence::
5121 FK_NonConstLValueReferenceBindingToBitfield;
5122 else if (Initializer->refersToVectorElement())
5123 FK = InitializationSequence::
5124 FK_NonConstLValueReferenceBindingToVectorElement;
5125 else if (Initializer->refersToMatrixElement())
5126 FK = InitializationSequence::
5127 FK_NonConstLValueReferenceBindingToMatrixElement;
5128 else
5129 llvm_unreachable("unexpected kind of compatible initializer");
5130 break;
5131 case Sema::Ref_Related:
5132 FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5133 break;
5134 case Sema::Ref_Incompatible:
5135 FK = InitializationSequence::
5136 FK_NonConstLValueReferenceBindingToUnrelated;
5137 break;
5138 }
5139 Sequence.SetFailed(FK);
5140 }
5141 return;
5142 }
5143
5144 // - If the initializer expression
5145 // - is an
5146 // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5147 // [1z] rvalue (but not a bit-field) or
5148 // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5149 //
5150 // Note: functions are handled above and below rather than here...
5151 if (!T1Function &&
5152 (RefRelationship == Sema::Ref_Compatible ||
5153 (Kind.isCStyleOrFunctionalCast() &&
5154 RefRelationship == Sema::Ref_Related)) &&
5155 ((InitCategory.isXValue() && !isNonReferenceableGLValue(E: Initializer)) ||
5156 (InitCategory.isPRValue() &&
5157 (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5158 T2->isArrayType())))) {
5159 ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5160 if (InitCategory.isPRValue() && T2->isRecordType()) {
5161 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5162 // compiler the freedom to perform a copy here or bind to the
5163 // object, while C++0x requires that we bind directly to the
5164 // object. Hence, we always bind to the object without making an
5165 // extra copy. However, in C++03 requires that we check for the
5166 // presence of a suitable copy constructor:
5167 //
5168 // The constructor that would be used to make the copy shall
5169 // be callable whether or not the copy is actually done.
5170 if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5171 Sequence.AddExtraneousCopyToTemporary(T: cv2T2);
5172 else if (S.getLangOpts().CPlusPlus11)
5173 CheckCXX98CompatAccessibleCopy(S, Entity, CurInitExpr: Initializer);
5174 }
5175
5176 // C++1z [dcl.init.ref]/5.2.1.2:
5177 // If the converted initializer is a prvalue, its type T4 is adjusted
5178 // to type "cv1 T4" and the temporary materialization conversion is
5179 // applied.
5180 // Postpone address space conversions to after the temporary materialization
5181 // conversion to allow creating temporaries in the alloca address space.
5182 auto T1QualsIgnoreAS = T1Quals;
5183 auto T2QualsIgnoreAS = T2Quals;
5184 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5185 T1QualsIgnoreAS.removeAddressSpace();
5186 T2QualsIgnoreAS.removeAddressSpace();
5187 }
5188 QualType cv1T4 = S.Context.getQualifiedType(T: cv2T2, Qs: T1QualsIgnoreAS);
5189 if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5190 Sequence.AddQualificationConversionStep(Ty: cv1T4, VK: ValueKind);
5191 Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: ValueKind == VK_PRValue);
5192 ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5193 // Add addr space conversion if required.
5194 if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5195 auto T4Quals = cv1T4.getQualifiers();
5196 T4Quals.addAddressSpace(space: T1Quals.getAddressSpace());
5197 QualType cv1T4WithAS = S.Context.getQualifiedType(T: T2, Qs: T4Quals);
5198 Sequence.AddQualificationConversionStep(Ty: cv1T4WithAS, VK: ValueKind);
5199 cv1T4 = cv1T4WithAS;
5200 }
5201
5202 // In any case, the reference is bound to the resulting glvalue (or to
5203 // an appropriate base class subobject).
5204 if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5205 Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: ValueKind);
5206 else if (RefConv & Sema::ReferenceConversions::ObjC)
5207 Sequence.AddObjCObjectConversionStep(T: cv1T1);
5208 else if (RefConv & Sema::ReferenceConversions::Qualification) {
5209 if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1))
5210 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: ValueKind);
5211 }
5212 return;
5213 }
5214
5215 // - has a class type (i.e., T2 is a class type), where T1 is not
5216 // reference-related to T2, and can be implicitly converted to an
5217 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
5218 // where "cv1 T1" is reference-compatible with "cv3 T3",
5219 //
5220 // DR1287 removes the "implicitly" here.
5221 if (T2->isRecordType()) {
5222 if (RefRelationship == Sema::Ref_Incompatible) {
5223 ConvOvlResult = TryRefInitWithConversionFunction(
5224 S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5225 /*IsLValueRef*/ isLValueRef, Sequence);
5226 if (ConvOvlResult)
5227 Sequence.SetOverloadFailure(
5228 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5229 Result: ConvOvlResult);
5230
5231 return;
5232 }
5233
5234 if (RefRelationship == Sema::Ref_Compatible &&
5235 isRValueRef && InitCategory.isLValue()) {
5236 Sequence.SetFailed(
5237 InitializationSequence::FK_RValueReferenceBindingToLValue);
5238 return;
5239 }
5240
5241 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5242 return;
5243 }
5244
5245 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
5246 // from the initializer expression using the rules for a non-reference
5247 // copy-initialization (8.5). The reference is then bound to the
5248 // temporary. [...]
5249
5250 // Ignore address space of reference type at this point and perform address
5251 // space conversion after the reference binding step.
5252 QualType cv1T1IgnoreAS =
5253 T1Quals.hasAddressSpace()
5254 ? S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace())
5255 : cv1T1;
5256
5257 InitializedEntity TempEntity =
5258 InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS);
5259
5260 // FIXME: Why do we use an implicit conversion here rather than trying
5261 // copy-initialization?
5262 ImplicitConversionSequence ICS
5263 = S.TryImplicitConversion(From: Initializer, ToType: TempEntity.getType(),
5264 /*SuppressUserConversions=*/false,
5265 AllowExplicit: Sema::AllowedExplicit::None,
5266 /*FIXME:InOverloadResolution=*/InOverloadResolution: false,
5267 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5268 /*AllowObjCWritebackConversion=*/false);
5269
5270 if (ICS.isBad()) {
5271 // FIXME: Use the conversion function set stored in ICS to turn
5272 // this into an overloading ambiguity diagnostic. However, we need
5273 // to keep that set as an OverloadCandidateSet rather than as some
5274 // other kind of set.
5275 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5276 Sequence.SetOverloadFailure(
5277 Failure: InitializationSequence::FK_ReferenceInitOverloadFailed,
5278 Result: ConvOvlResult);
5279 else if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy)
5280 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5281 else
5282 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5283 return;
5284 } else {
5285 Sequence.AddConversionSequenceStep(ICS, T: TempEntity.getType(),
5286 TopLevelOfInitList);
5287 }
5288
5289 // [...] If T1 is reference-related to T2, cv1 must be the
5290 // same cv-qualification as, or greater cv-qualification
5291 // than, cv2; otherwise, the program is ill-formed.
5292 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5293 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5294 if (RefRelationship == Sema::Ref_Related &&
5295 ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5296 !T1Quals.isAddressSpaceSupersetOf(other: T2Quals))) {
5297 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5298 return;
5299 }
5300
5301 // [...] If T1 is reference-related to T2 and the reference is an rvalue
5302 // reference, the initializer expression shall not be an lvalue.
5303 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5304 InitCategory.isLValue()) {
5305 Sequence.SetFailed(
5306 InitializationSequence::FK_RValueReferenceBindingToLValue);
5307 return;
5308 }
5309
5310 Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, /*BindingTemporary=*/true);
5311
5312 if (T1Quals.hasAddressSpace()) {
5313 if (!Qualifiers::isAddressSpaceSupersetOf(A: T1Quals.getAddressSpace(),
5314 B: LangAS::Default)) {
5315 Sequence.SetFailed(
5316 InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5317 return;
5318 }
5319 Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: isLValueRef ? VK_LValue
5320 : VK_XValue);
5321 }
5322}
5323
5324/// Attempt character array initialization from a string literal
5325/// (C++ [dcl.init.string], C99 6.7.8).
5326static void TryStringLiteralInitialization(Sema &S,
5327 const InitializedEntity &Entity,
5328 const InitializationKind &Kind,
5329 Expr *Initializer,
5330 InitializationSequence &Sequence) {
5331 Sequence.AddStringInitStep(T: Entity.getType());
5332}
5333
5334/// Attempt value initialization (C++ [dcl.init]p7).
5335static void TryValueInitialization(Sema &S,
5336 const InitializedEntity &Entity,
5337 const InitializationKind &Kind,
5338 InitializationSequence &Sequence,
5339 InitListExpr *InitList) {
5340 assert((!InitList || InitList->getNumInits() == 0) &&
5341 "Shouldn't use value-init for non-empty init lists");
5342
5343 // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5344 //
5345 // To value-initialize an object of type T means:
5346 QualType T = Entity.getType();
5347
5348 // -- if T is an array type, then each element is value-initialized;
5349 T = S.Context.getBaseElementType(QT: T);
5350
5351 if (const RecordType *RT = T->getAs<RecordType>()) {
5352 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) {
5353 bool NeedZeroInitialization = true;
5354 // C++98:
5355 // -- if T is a class type (clause 9) with a user-declared constructor
5356 // (12.1), then the default constructor for T is called (and the
5357 // initialization is ill-formed if T has no accessible default
5358 // constructor);
5359 // C++11:
5360 // -- if T is a class type (clause 9) with either no default constructor
5361 // (12.1 [class.ctor]) or a default constructor that is user-provided
5362 // or deleted, then the object is default-initialized;
5363 //
5364 // Note that the C++11 rule is the same as the C++98 rule if there are no
5365 // defaulted or deleted constructors, so we just use it unconditionally.
5366 CXXConstructorDecl *CD = S.LookupDefaultConstructor(Class: ClassDecl);
5367 if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5368 NeedZeroInitialization = false;
5369
5370 // -- if T is a (possibly cv-qualified) non-union class type without a
5371 // user-provided or deleted default constructor, then the object is
5372 // zero-initialized and, if T has a non-trivial default constructor,
5373 // default-initialized;
5374 // The 'non-union' here was removed by DR1502. The 'non-trivial default
5375 // constructor' part was removed by DR1507.
5376 if (NeedZeroInitialization)
5377 Sequence.AddZeroInitializationStep(T: Entity.getType());
5378
5379 // C++03:
5380 // -- if T is a non-union class type without a user-declared constructor,
5381 // then every non-static data member and base class component of T is
5382 // value-initialized;
5383 // [...] A program that calls for [...] value-initialization of an
5384 // entity of reference type is ill-formed.
5385 //
5386 // C++11 doesn't need this handling, because value-initialization does not
5387 // occur recursively there, and the implicit default constructor is
5388 // defined as deleted in the problematic cases.
5389 if (!S.getLangOpts().CPlusPlus11 &&
5390 ClassDecl->hasUninitializedReferenceMember()) {
5391 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5392 return;
5393 }
5394
5395 // If this is list-value-initialization, pass the empty init list on when
5396 // building the constructor call. This affects the semantics of a few
5397 // things (such as whether an explicit default constructor can be called).
5398 Expr *InitListAsExpr = InitList;
5399 MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5400 bool InitListSyntax = InitList;
5401
5402 // FIXME: Instead of creating a CXXConstructExpr of array type here,
5403 // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5404 return TryConstructorInitialization(
5405 S, Entity, Kind, Args, DestType: T, DestArrayType: Entity.getType(), Sequence, IsListInit: InitListSyntax);
5406 }
5407 }
5408
5409 Sequence.AddZeroInitializationStep(T: Entity.getType());
5410}
5411
5412/// Attempt default initialization (C++ [dcl.init]p6).
5413static void TryDefaultInitialization(Sema &S,
5414 const InitializedEntity &Entity,
5415 const InitializationKind &Kind,
5416 InitializationSequence &Sequence) {
5417 assert(Kind.getKind() == InitializationKind::IK_Default);
5418
5419 // C++ [dcl.init]p6:
5420 // To default-initialize an object of type T means:
5421 // - if T is an array type, each element is default-initialized;
5422 QualType DestType = S.Context.getBaseElementType(QT: Entity.getType());
5423
5424 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
5425 // constructor for T is called (and the initialization is ill-formed if
5426 // T has no accessible default constructor);
5427 if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5428 TryConstructorInitialization(S, Entity, Kind, Args: std::nullopt, DestType,
5429 DestArrayType: Entity.getType(), Sequence);
5430 return;
5431 }
5432
5433 // - otherwise, no initialization is performed.
5434
5435 // If a program calls for the default initialization of an object of
5436 // a const-qualified type T, T shall be a class type with a user-provided
5437 // default constructor.
5438 if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5439 if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5440 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5441 return;
5442 }
5443
5444 // If the destination type has a lifetime property, zero-initialize it.
5445 if (DestType.getQualifiers().hasObjCLifetime()) {
5446 Sequence.AddZeroInitializationStep(T: Entity.getType());
5447 return;
5448 }
5449}
5450
5451static void TryOrBuildParenListInitialization(
5452 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5453 ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5454 ExprResult *Result = nullptr) {
5455 unsigned EntityIndexToProcess = 0;
5456 SmallVector<Expr *, 4> InitExprs;
5457 QualType ResultType;
5458 Expr *ArrayFiller = nullptr;
5459 FieldDecl *InitializedFieldInUnion = nullptr;
5460
5461 auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5462 const InitializationKind &SubKind,
5463 Expr *Arg, Expr **InitExpr = nullptr) {
5464 InitializationSequence IS = InitializationSequence(
5465 S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5466
5467 if (IS.Failed()) {
5468 if (!VerifyOnly) {
5469 IS.Diagnose(S, Entity: SubEntity, Kind: SubKind, Args: Arg ? ArrayRef(Arg) : std::nullopt);
5470 } else {
5471 Sequence.SetFailed(
5472 InitializationSequence::FK_ParenthesizedListInitFailed);
5473 }
5474
5475 return false;
5476 }
5477 if (!VerifyOnly) {
5478 ExprResult ER;
5479 ER = IS.Perform(S, Entity: SubEntity, Kind: SubKind,
5480 Args: Arg ? MultiExprArg(Arg) : std::nullopt);
5481 if (InitExpr)
5482 *InitExpr = ER.get();
5483 else
5484 InitExprs.push_back(Elt: ER.get());
5485 }
5486 return true;
5487 };
5488
5489 if (const ArrayType *AT =
5490 S.getASTContext().getAsArrayType(T: Entity.getType())) {
5491 SmallVector<InitializedEntity, 4> ElementEntities;
5492 uint64_t ArrayLength;
5493 // C++ [dcl.init]p16.5
5494 // if the destination type is an array, the object is initialized as
5495 // follows. Let x1, . . . , xk be the elements of the expression-list. If
5496 // the destination type is an array of unknown bound, it is defined as
5497 // having k elements.
5498 if (const ConstantArrayType *CAT =
5499 S.getASTContext().getAsConstantArrayType(T: Entity.getType())) {
5500 ArrayLength = CAT->getZExtSize();
5501 ResultType = Entity.getType();
5502 } else if (const VariableArrayType *VAT =
5503 S.getASTContext().getAsVariableArrayType(T: Entity.getType())) {
5504 // Braced-initialization of variable array types is not allowed, even if
5505 // the size is greater than or equal to the number of args, so we don't
5506 // allow them to be initialized via parenthesized aggregate initialization
5507 // either.
5508 const Expr *SE = VAT->getSizeExpr();
5509 S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5510 << SE->getSourceRange();
5511 return;
5512 } else {
5513 assert(isa<IncompleteArrayType>(Entity.getType()));
5514 ArrayLength = Args.size();
5515 }
5516 EntityIndexToProcess = ArrayLength;
5517
5518 // ...the ith array element is copy-initialized with xi for each
5519 // 1 <= i <= k
5520 for (Expr *E : Args) {
5521 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5522 Context&: S.getASTContext(), Index: EntityIndexToProcess, Parent: Entity);
5523 InitializationKind SubKind = InitializationKind::CreateForInit(
5524 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
5525 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5526 return;
5527 }
5528 // ...and value-initialized for each k < i <= n;
5529 if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) {
5530 InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5531 Context&: S.getASTContext(), Index: Args.size(), Parent: Entity);
5532 InitializationKind SubKind = InitializationKind::CreateValue(
5533 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true);
5534 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5535 return;
5536 }
5537
5538 if (ResultType.isNull()) {
5539 ResultType = S.Context.getConstantArrayType(
5540 EltTy: AT->getElementType(), ArySize: llvm::APInt(/*numBits=*/32, ArrayLength),
5541 /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5542 }
5543 } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5544 bool IsUnion = RT->isUnionType();
5545 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl());
5546 if (RD->isInvalidDecl()) {
5547 // Exit early to avoid confusion when processing members.
5548 // We do the same for braced list initialization in
5549 // `CheckStructUnionTypes`.
5550 Sequence.SetFailed(
5551 clang::InitializationSequence::FK_ParenthesizedListInitFailed);
5552 return;
5553 }
5554
5555 if (!IsUnion) {
5556 for (const CXXBaseSpecifier &Base : RD->bases()) {
5557 InitializedEntity SubEntity = InitializedEntity::InitializeBase(
5558 Context&: S.getASTContext(), Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity);
5559 if (EntityIndexToProcess < Args.size()) {
5560 // C++ [dcl.init]p16.6.2.2.
5561 // ...the object is initialized is follows. Let e1, ..., en be the
5562 // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5563 // the elements of the expression-list...The element ei is
5564 // copy-initialized with xi for 1 <= i <= k.
5565 Expr *E = Args[EntityIndexToProcess];
5566 InitializationKind SubKind = InitializationKind::CreateForInit(
5567 Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E);
5568 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5569 return;
5570 } else {
5571 // We've processed all of the args, but there are still base classes
5572 // that have to be initialized.
5573 // C++ [dcl.init]p17.6.2.2
5574 // The remaining elements...otherwise are value initialzed
5575 InitializationKind SubKind = InitializationKind::CreateValue(
5576 InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(),
5577 /*IsImplicit=*/isImplicit: true);
5578 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5579 return;
5580 }
5581 EntityIndexToProcess++;
5582 }
5583 }
5584
5585 for (FieldDecl *FD : RD->fields()) {
5586 // Unnamed bitfields should not be initialized at all, either with an arg
5587 // or by default.
5588 if (FD->isUnnamedBitField())
5589 continue;
5590
5591 InitializedEntity SubEntity =
5592 InitializedEntity::InitializeMemberFromParenAggInit(FD);
5593
5594 if (EntityIndexToProcess < Args.size()) {
5595 // ...The element ei is copy-initialized with xi for 1 <= i <= k.
5596 Expr *E = Args[EntityIndexToProcess];
5597
5598 // Incomplete array types indicate flexible array members. Do not allow
5599 // paren list initializations of structs with these members, as GCC
5600 // doesn't either.
5601 if (FD->getType()->isIncompleteArrayType()) {
5602 if (!VerifyOnly) {
5603 S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5604 << SourceRange(E->getBeginLoc(), E->getEndLoc());
5605 S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5606 }
5607 Sequence.SetFailed(
5608 InitializationSequence::FK_ParenthesizedListInitFailed);
5609 return;
5610 }
5611
5612 InitializationKind SubKind = InitializationKind::CreateForInit(
5613 E->getExprLoc(), /*isDirectInit=*/false, E);
5614 if (!HandleInitializedEntity(SubEntity, SubKind, E))
5615 return;
5616
5617 // Unions should have only one initializer expression, so we bail out
5618 // after processing the first field. If there are more initializers then
5619 // it will be caught when we later check whether EntityIndexToProcess is
5620 // less than Args.size();
5621 if (IsUnion) {
5622 InitializedFieldInUnion = FD;
5623 EntityIndexToProcess = 1;
5624 break;
5625 }
5626 } else {
5627 // We've processed all of the args, but there are still members that
5628 // have to be initialized.
5629 if (FD->hasInClassInitializer()) {
5630 if (!VerifyOnly) {
5631 // C++ [dcl.init]p16.6.2.2
5632 // The remaining elements are initialized with their default
5633 // member initializers, if any
5634 ExprResult DIE = S.BuildCXXDefaultInitExpr(
5635 Kind.getParenOrBraceRange().getEnd(), FD);
5636 if (DIE.isInvalid())
5637 return;
5638 S.checkInitializerLifetime(SubEntity, DIE.get());
5639 InitExprs.push_back(DIE.get());
5640 }
5641 } else {
5642 // C++ [dcl.init]p17.6.2.2
5643 // The remaining elements...otherwise are value initialzed
5644 if (FD->getType()->isReferenceType()) {
5645 Sequence.SetFailed(
5646 InitializationSequence::FK_ParenthesizedListInitFailed);
5647 if (!VerifyOnly) {
5648 SourceRange SR = Kind.getParenOrBraceRange();
5649 S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5650 << FD->getType() << SR;
5651 S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5652 }
5653 return;
5654 }
5655 InitializationKind SubKind = InitializationKind::CreateValue(
5656 Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5657 if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5658 return;
5659 }
5660 }
5661 EntityIndexToProcess++;
5662 }
5663 ResultType = Entity.getType();
5664 }
5665
5666 // Not all of the args have been processed, so there must've been more args
5667 // than were required to initialize the element.
5668 if (EntityIndexToProcess < Args.size()) {
5669 Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
5670 if (!VerifyOnly) {
5671 QualType T = Entity.getType();
5672 int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5673 SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5674 Args.back()->getEndLoc());
5675 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5676 << InitKind << ExcessInitSR;
5677 }
5678 return;
5679 }
5680
5681 if (VerifyOnly) {
5682 Sequence.setSequenceKind(InitializationSequence::NormalSequence);
5683 Sequence.AddParenthesizedListInitStep(T: Entity.getType());
5684 } else if (Result) {
5685 SourceRange SR = Kind.getParenOrBraceRange();
5686 auto *CPLIE = CXXParenListInitExpr::Create(
5687 C&: S.getASTContext(), Args: InitExprs, T: ResultType, NumUserSpecifiedExprs: Args.size(),
5688 InitLoc: Kind.getLocation(), LParenLoc: SR.getBegin(), RParenLoc: SR.getEnd());
5689 if (ArrayFiller)
5690 CPLIE->setArrayFiller(ArrayFiller);
5691 if (InitializedFieldInUnion)
5692 CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5693 *Result = CPLIE;
5694 S.Diag(Kind.getLocation(),
5695 diag::warn_cxx17_compat_aggregate_init_paren_list)
5696 << Kind.getLocation() << SR << ResultType;
5697 }
5698}
5699
5700/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5701/// which enumerates all conversion functions and performs overload resolution
5702/// to select the best.
5703static void TryUserDefinedConversion(Sema &S,
5704 QualType DestType,
5705 const InitializationKind &Kind,
5706 Expr *Initializer,
5707 InitializationSequence &Sequence,
5708 bool TopLevelOfInitList) {
5709 assert(!DestType->isReferenceType() && "References are handled elsewhere");
5710 QualType SourceType = Initializer->getType();
5711 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5712 "Must have a class type to perform a user-defined conversion");
5713
5714 // Build the candidate set directly in the initialization sequence
5715 // structure, so that it will persist if we fail.
5716 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5717 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5718 CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5719
5720 // Determine whether we are allowed to call explicit constructors or
5721 // explicit conversion operators.
5722 bool AllowExplicit = Kind.AllowExplicit();
5723
5724 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5725 // The type we're converting to is a class type. Enumerate its constructors
5726 // to see if there is a suitable conversion.
5727 CXXRecordDecl *DestRecordDecl
5728 = cast<CXXRecordDecl>(Val: DestRecordType->getDecl());
5729
5730 // Try to complete the type we're converting to.
5731 if (S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) {
5732 for (NamedDecl *D : S.LookupConstructors(Class: DestRecordDecl)) {
5733 auto Info = getConstructorInfo(ND: D);
5734 if (!Info.Constructor)
5735 continue;
5736
5737 if (!Info.Constructor->isInvalidDecl() &&
5738 Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5739 if (Info.ConstructorTmpl)
5740 S.AddTemplateOverloadCandidate(
5741 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
5742 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet,
5743 /*SuppressUserConversions=*/true,
5744 /*PartialOverloading*/ false, AllowExplicit);
5745 else
5746 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5747 Initializer, CandidateSet,
5748 /*SuppressUserConversions=*/true,
5749 /*PartialOverloading*/ false, AllowExplicit);
5750 }
5751 }
5752 }
5753 }
5754
5755 SourceLocation DeclLoc = Initializer->getBeginLoc();
5756
5757 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5758 // The type we're converting from is a class type, enumerate its conversion
5759 // functions.
5760
5761 // We can only enumerate the conversion functions for a complete type; if
5762 // the type isn't complete, simply skip this step.
5763 if (S.isCompleteType(Loc: DeclLoc, T: SourceType)) {
5764 CXXRecordDecl *SourceRecordDecl
5765 = cast<CXXRecordDecl>(Val: SourceRecordType->getDecl());
5766
5767 const auto &Conversions =
5768 SourceRecordDecl->getVisibleConversionFunctions();
5769 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5770 NamedDecl *D = *I;
5771 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5772 if (isa<UsingShadowDecl>(Val: D))
5773 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5774
5775 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
5776 CXXConversionDecl *Conv;
5777 if (ConvTemplate)
5778 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5779 else
5780 Conv = cast<CXXConversionDecl>(Val: D);
5781
5782 if (ConvTemplate)
5783 S.AddTemplateConversionCandidate(
5784 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType,
5785 CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit);
5786 else
5787 S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer,
5788 ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit,
5789 AllowExplicit);
5790 }
5791 }
5792 }
5793
5794 // Perform overload resolution. If it fails, return the failed result.
5795 OverloadCandidateSet::iterator Best;
5796 if (OverloadingResult Result
5797 = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5798 Sequence.SetOverloadFailure(
5799 Failure: InitializationSequence::FK_UserConversionOverloadFailed, Result);
5800
5801 // [class.copy.elision]p3:
5802 // In some copy-initialization contexts, a two-stage overload resolution
5803 // is performed.
5804 // If the first overload resolution selects a deleted function, we also
5805 // need the initialization sequence to decide whether to perform the second
5806 // overload resolution.
5807 if (!(Result == OR_Deleted &&
5808 Kind.getKind() == InitializationKind::IK_Copy))
5809 return;
5810 }
5811
5812 FunctionDecl *Function = Best->Function;
5813 Function->setReferenced();
5814 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5815
5816 if (isa<CXXConstructorDecl>(Val: Function)) {
5817 // Add the user-defined conversion step. Any cv-qualification conversion is
5818 // subsumed by the initialization. Per DR5, the created temporary is of the
5819 // cv-unqualified type of the destination.
5820 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl,
5821 T: DestType.getUnqualifiedType(),
5822 HadMultipleCandidates);
5823
5824 // C++14 and before:
5825 // - if the function is a constructor, the call initializes a temporary
5826 // of the cv-unqualified version of the destination type. The [...]
5827 // temporary [...] is then used to direct-initialize, according to the
5828 // rules above, the object that is the destination of the
5829 // copy-initialization.
5830 // Note that this just performs a simple object copy from the temporary.
5831 //
5832 // C++17:
5833 // - if the function is a constructor, the call is a prvalue of the
5834 // cv-unqualified version of the destination type whose return object
5835 // is initialized by the constructor. The call is used to
5836 // direct-initialize, according to the rules above, the object that
5837 // is the destination of the copy-initialization.
5838 // Therefore we need to do nothing further.
5839 //
5840 // FIXME: Mark this copy as extraneous.
5841 if (!S.getLangOpts().CPlusPlus17)
5842 Sequence.AddFinalCopy(T: DestType);
5843 else if (DestType.hasQualifiers())
5844 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
5845 return;
5846 }
5847
5848 // Add the user-defined conversion step that calls the conversion function.
5849 QualType ConvType = Function->getCallResultType();
5850 Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: ConvType,
5851 HadMultipleCandidates);
5852
5853 if (ConvType->getAs<RecordType>()) {
5854 // The call is used to direct-initialize [...] the object that is the
5855 // destination of the copy-initialization.
5856 //
5857 // In C++17, this does not call a constructor if we enter /17.6.1:
5858 // - If the initializer expression is a prvalue and the cv-unqualified
5859 // version of the source type is the same as the class of the
5860 // destination [... do not make an extra copy]
5861 //
5862 // FIXME: Mark this copy as extraneous.
5863 if (!S.getLangOpts().CPlusPlus17 ||
5864 Function->getReturnType()->isReferenceType() ||
5865 !S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType))
5866 Sequence.AddFinalCopy(T: DestType);
5867 else if (!S.Context.hasSameType(T1: ConvType, T2: DestType))
5868 Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue);
5869 return;
5870 }
5871
5872 // If the conversion following the call to the conversion function
5873 // is interesting, add it as a separate step.
5874 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5875 Best->FinalConversion.Third) {
5876 ImplicitConversionSequence ICS;
5877 ICS.setStandard();
5878 ICS.Standard = Best->FinalConversion;
5879 Sequence.AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList);
5880 }
5881}
5882
5883/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5884/// a function with a pointer return type contains a 'return false;' statement.
5885/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5886/// code using that header.
5887///
5888/// Work around this by treating 'return false;' as zero-initializing the result
5889/// if it's used in a pointer-returning function in a system header.
5890static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5891 const InitializedEntity &Entity,
5892 const Expr *Init) {
5893 return S.getLangOpts().CPlusPlus11 &&
5894 Entity.getKind() == InitializedEntity::EK_Result &&
5895 Entity.getType()->isPointerType() &&
5896 isa<CXXBoolLiteralExpr>(Val: Init) &&
5897 !cast<CXXBoolLiteralExpr>(Val: Init)->getValue() &&
5898 S.getSourceManager().isInSystemHeader(Loc: Init->getExprLoc());
5899}
5900
5901/// The non-zero enum values here are indexes into diagnostic alternatives.
5902enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5903
5904/// Determines whether this expression is an acceptable ICR source.
5905static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5906 bool isAddressOf, bool &isWeakAccess) {
5907 // Skip parens.
5908 e = e->IgnoreParens();
5909
5910 // Skip address-of nodes.
5911 if (UnaryOperator *op = dyn_cast<UnaryOperator>(Val: e)) {
5912 if (op->getOpcode() == UO_AddrOf)
5913 return isInvalidICRSource(C, e: op->getSubExpr(), /*addressof*/ isAddressOf: true,
5914 isWeakAccess);
5915
5916 // Skip certain casts.
5917 } else if (CastExpr *ce = dyn_cast<CastExpr>(Val: e)) {
5918 switch (ce->getCastKind()) {
5919 case CK_Dependent:
5920 case CK_BitCast:
5921 case CK_LValueBitCast:
5922 case CK_NoOp:
5923 return isInvalidICRSource(C, e: ce->getSubExpr(), isAddressOf, isWeakAccess);
5924
5925 case CK_ArrayToPointerDecay:
5926 return IIK_nonscalar;
5927
5928 case CK_NullToPointer:
5929 return IIK_okay;
5930
5931 default:
5932 break;
5933 }
5934
5935 // If we have a declaration reference, it had better be a local variable.
5936 } else if (isa<DeclRefExpr>(Val: e)) {
5937 // set isWeakAccess to true, to mean that there will be an implicit
5938 // load which requires a cleanup.
5939 if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5940 isWeakAccess = true;
5941
5942 if (!isAddressOf) return IIK_nonlocal;
5943
5944 VarDecl *var = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: e)->getDecl());
5945 if (!var) return IIK_nonlocal;
5946
5947 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5948
5949 // If we have a conditional operator, check both sides.
5950 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(Val: e)) {
5951 if (InvalidICRKind iik = isInvalidICRSource(C, e: cond->getLHS(), isAddressOf,
5952 isWeakAccess))
5953 return iik;
5954
5955 return isInvalidICRSource(C, e: cond->getRHS(), isAddressOf, isWeakAccess);
5956
5957 // These are never scalar.
5958 } else if (isa<ArraySubscriptExpr>(Val: e)) {
5959 return IIK_nonscalar;
5960
5961 // Otherwise, it needs to be a null pointer constant.
5962 } else {
5963 return (e->isNullPointerConstant(Ctx&: C, NPC: Expr::NPC_ValueDependentIsNull)
5964 ? IIK_okay : IIK_nonlocal);
5965 }
5966
5967 return IIK_nonlocal;
5968}
5969
5970/// Check whether the given expression is a valid operand for an
5971/// indirect copy/restore.
5972static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5973 assert(src->isPRValue());
5974 bool isWeakAccess = false;
5975 InvalidICRKind iik = isInvalidICRSource(C&: S.Context, e: src, isAddressOf: false, isWeakAccess);
5976 // If isWeakAccess to true, there will be an implicit
5977 // load which requires a cleanup.
5978 if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5979 S.Cleanup.setExprNeedsCleanups(true);
5980
5981 if (iik == IIK_okay) return;
5982
5983 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5984 << ((unsigned) iik - 1) // shift index into diagnostic explanations
5985 << src->getSourceRange();
5986}
5987
5988/// Determine whether we have compatible array types for the
5989/// purposes of GNU by-copy array initialization.
5990static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5991 const ArrayType *Source) {
5992 // If the source and destination array types are equivalent, we're
5993 // done.
5994 if (Context.hasSameType(T1: QualType(Dest, 0), T2: QualType(Source, 0)))
5995 return true;
5996
5997 // Make sure that the element types are the same.
5998 if (!Context.hasSameType(T1: Dest->getElementType(), T2: Source->getElementType()))
5999 return false;
6000
6001 // The only mismatch we allow is when the destination is an
6002 // incomplete array type and the source is a constant array type.
6003 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
6004}
6005
6006static bool tryObjCWritebackConversion(Sema &S,
6007 InitializationSequence &Sequence,
6008 const InitializedEntity &Entity,
6009 Expr *Initializer) {
6010 bool ArrayDecay = false;
6011 QualType ArgType = Initializer->getType();
6012 QualType ArgPointee;
6013 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(T: ArgType)) {
6014 ArrayDecay = true;
6015 ArgPointee = ArgArrayType->getElementType();
6016 ArgType = S.Context.getPointerType(T: ArgPointee);
6017 }
6018
6019 // Handle write-back conversion.
6020 QualType ConvertedArgType;
6021 if (!S.isObjCWritebackConversion(FromType: ArgType, ToType: Entity.getType(),
6022 ConvertedType&: ConvertedArgType))
6023 return false;
6024
6025 // We should copy unless we're passing to an argument explicitly
6026 // marked 'out'.
6027 bool ShouldCopy = true;
6028 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl()))
6029 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6030
6031 // Do we need an lvalue conversion?
6032 if (ArrayDecay || Initializer->isGLValue()) {
6033 ImplicitConversionSequence ICS;
6034 ICS.setStandard();
6035 ICS.Standard.setAsIdentityConversion();
6036
6037 QualType ResultType;
6038 if (ArrayDecay) {
6039 ICS.Standard.First = ICK_Array_To_Pointer;
6040 ResultType = S.Context.getPointerType(T: ArgPointee);
6041 } else {
6042 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
6043 ResultType = Initializer->getType().getNonLValueExprType(Context: S.Context);
6044 }
6045
6046 Sequence.AddConversionSequenceStep(ICS, T: ResultType);
6047 }
6048
6049 Sequence.AddPassByIndirectCopyRestoreStep(type: Entity.getType(), shouldCopy: ShouldCopy);
6050 return true;
6051}
6052
6053static bool TryOCLSamplerInitialization(Sema &S,
6054 InitializationSequence &Sequence,
6055 QualType DestType,
6056 Expr *Initializer) {
6057 if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6058 (!Initializer->isIntegerConstantExpr(Ctx: S.Context) &&
6059 !Initializer->getType()->isSamplerT()))
6060 return false;
6061
6062 Sequence.AddOCLSamplerInitStep(T: DestType);
6063 return true;
6064}
6065
6066static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
6067 return Initializer->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
6068 (Initializer->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0);
6069}
6070
6071static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
6072 InitializationSequence &Sequence,
6073 QualType DestType,
6074 Expr *Initializer) {
6075 if (!S.getLangOpts().OpenCL)
6076 return false;
6077
6078 //
6079 // OpenCL 1.2 spec, s6.12.10
6080 //
6081 // The event argument can also be used to associate the
6082 // async_work_group_copy with a previous async copy allowing
6083 // an event to be shared by multiple async copies; otherwise
6084 // event should be zero.
6085 //
6086 if (DestType->isEventT() || DestType->isQueueT()) {
6087 if (!IsZeroInitializer(Initializer, S))
6088 return false;
6089
6090 Sequence.AddOCLZeroOpaqueTypeStep(T: DestType);
6091 return true;
6092 }
6093
6094 // We should allow zero initialization for all types defined in the
6095 // cl_intel_device_side_avc_motion_estimation extension, except
6096 // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6097 if (S.getOpenCLOptions().isAvailableOption(
6098 Ext: "cl_intel_device_side_avc_motion_estimation", LO: S.getLangOpts()) &&
6099 DestType->isOCLIntelSubgroupAVCType()) {
6100 if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6101 DestType->isOCLIntelSubgroupAVCMceResultType())
6102 return false;
6103 if (!IsZeroInitializer(Initializer, S))
6104 return false;
6105
6106 Sequence.AddOCLZeroOpaqueTypeStep(T: DestType);
6107 return true;
6108 }
6109
6110 return false;
6111}
6112
6113InitializationSequence::InitializationSequence(
6114 Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6115 MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6116 : FailedOverloadResult(OR_Success),
6117 FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6118 InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6119 TreatUnavailableAsInvalid);
6120}
6121
6122/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6123/// address of that function, this returns true. Otherwise, it returns false.
6124static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6125 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
6126 if (!DRE || !isa<FunctionDecl>(Val: DRE->getDecl()))
6127 return false;
6128
6129 return !S.checkAddressOfFunctionIsAvailable(
6130 Function: cast<FunctionDecl>(Val: DRE->getDecl()));
6131}
6132
6133/// Determine whether we can perform an elementwise array copy for this kind
6134/// of entity.
6135static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6136 switch (Entity.getKind()) {
6137 case InitializedEntity::EK_LambdaCapture:
6138 // C++ [expr.prim.lambda]p24:
6139 // For array members, the array elements are direct-initialized in
6140 // increasing subscript order.
6141 return true;
6142
6143 case InitializedEntity::EK_Variable:
6144 // C++ [dcl.decomp]p1:
6145 // [...] each element is copy-initialized or direct-initialized from the
6146 // corresponding element of the assignment-expression [...]
6147 return isa<DecompositionDecl>(Val: Entity.getDecl());
6148
6149 case InitializedEntity::EK_Member:
6150 // C++ [class.copy.ctor]p14:
6151 // - if the member is an array, each element is direct-initialized with
6152 // the corresponding subobject of x
6153 return Entity.isImplicitMemberInitializer();
6154
6155 case InitializedEntity::EK_ArrayElement:
6156 // All the above cases are intended to apply recursively, even though none
6157 // of them actually say that.
6158 if (auto *E = Entity.getParent())
6159 return canPerformArrayCopy(Entity: *E);
6160 break;
6161
6162 default:
6163 break;
6164 }
6165
6166 return false;
6167}
6168
6169void InitializationSequence::InitializeFrom(Sema &S,
6170 const InitializedEntity &Entity,
6171 const InitializationKind &Kind,
6172 MultiExprArg Args,
6173 bool TopLevelOfInitList,
6174 bool TreatUnavailableAsInvalid) {
6175 ASTContext &Context = S.Context;
6176
6177 // Eliminate non-overload placeholder types in the arguments. We
6178 // need to do this before checking whether types are dependent
6179 // because lowering a pseudo-object expression might well give us
6180 // something of dependent type.
6181 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6182 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6183 // FIXME: should we be doing this here?
6184 ExprResult result = S.CheckPlaceholderExpr(E: Args[I]);
6185 if (result.isInvalid()) {
6186 SetFailed(FK_PlaceholderType);
6187 return;
6188 }
6189 Args[I] = result.get();
6190 }
6191
6192 // C++0x [dcl.init]p16:
6193 // The semantics of initializers are as follows. The destination type is
6194 // the type of the object or reference being initialized and the source
6195 // type is the type of the initializer expression. The source type is not
6196 // defined when the initializer is a braced-init-list or when it is a
6197 // parenthesized list of expressions.
6198 QualType DestType = Entity.getType();
6199
6200 if (DestType->isDependentType() ||
6201 Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
6202 SequenceKind = DependentSequence;
6203 return;
6204 }
6205
6206 // Almost everything is a normal sequence.
6207 setSequenceKind(NormalSequence);
6208
6209 QualType SourceType;
6210 Expr *Initializer = nullptr;
6211 if (Args.size() == 1) {
6212 Initializer = Args[0];
6213 if (S.getLangOpts().ObjC) {
6214 if (S.CheckObjCBridgeRelatedConversions(Loc: Initializer->getBeginLoc(),
6215 DestType, SrcType: Initializer->getType(),
6216 SrcExpr&: Initializer) ||
6217 S.CheckConversionToObjCLiteral(DstType: DestType, SrcExpr&: Initializer))
6218 Args[0] = Initializer;
6219 }
6220 if (!isa<InitListExpr>(Val: Initializer))
6221 SourceType = Initializer->getType();
6222 }
6223
6224 // - If the initializer is a (non-parenthesized) braced-init-list, the
6225 // object is list-initialized (8.5.4).
6226 if (Kind.getKind() != InitializationKind::IK_Direct) {
6227 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Val: Initializer)) {
6228 TryListInitialization(S, Entity, Kind, InitList, Sequence&: *this,
6229 TreatUnavailableAsInvalid);
6230 return;
6231 }
6232 }
6233
6234 // - If the destination type is a reference type, see 8.5.3.
6235 if (DestType->isReferenceType()) {
6236 // C++0x [dcl.init.ref]p1:
6237 // A variable declared to be a T& or T&&, that is, "reference to type T"
6238 // (8.3.2), shall be initialized by an object, or function, of type T or
6239 // by an object that can be converted into a T.
6240 // (Therefore, multiple arguments are not permitted.)
6241 if (Args.size() != 1)
6242 SetFailed(FK_TooManyInitsForReference);
6243 // C++17 [dcl.init.ref]p5:
6244 // A reference [...] is initialized by an expression [...] as follows:
6245 // If the initializer is not an expression, presumably we should reject,
6246 // but the standard fails to actually say so.
6247 else if (isa<InitListExpr>(Val: Args[0]))
6248 SetFailed(FK_ParenthesizedListInitForReference);
6249 else
6250 TryReferenceInitialization(S, Entity, Kind, Initializer: Args[0], Sequence&: *this,
6251 TopLevelOfInitList);
6252 return;
6253 }
6254
6255 // - If the initializer is (), the object is value-initialized.
6256 if (Kind.getKind() == InitializationKind::IK_Value ||
6257 (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6258 TryValueInitialization(S, Entity, Kind, Sequence&: *this);
6259 return;
6260 }
6261
6262 // Handle default initialization.
6263 if (Kind.getKind() == InitializationKind::IK_Default) {
6264 TryDefaultInitialization(S, Entity, Kind, Sequence&: *this);
6265 return;
6266 }
6267
6268 // - If the destination type is an array of characters, an array of
6269 // char16_t, an array of char32_t, or an array of wchar_t, and the
6270 // initializer is a string literal, see 8.5.2.
6271 // - Otherwise, if the destination type is an array, the program is
6272 // ill-formed.
6273 // - Except in HLSL, where non-decaying array parameters behave like
6274 // non-array types for initialization.
6275 if (DestType->isArrayType() && !DestType->isArrayParameterType()) {
6276 const ArrayType *DestAT = Context.getAsArrayType(T: DestType);
6277 if (Initializer && isa<VariableArrayType>(Val: DestAT)) {
6278 SetFailed(FK_VariableLengthArrayHasInitializer);
6279 return;
6280 }
6281
6282 if (Initializer) {
6283 switch (IsStringInit(Init: Initializer, AT: DestAT, Context)) {
6284 case SIF_None:
6285 TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence&: *this);
6286 return;
6287 case SIF_NarrowStringIntoWideChar:
6288 SetFailed(FK_NarrowStringIntoWideCharArray);
6289 return;
6290 case SIF_WideStringIntoChar:
6291 SetFailed(FK_WideStringIntoCharArray);
6292 return;
6293 case SIF_IncompatWideStringIntoWideChar:
6294 SetFailed(FK_IncompatWideStringIntoWideChar);
6295 return;
6296 case SIF_PlainStringIntoUTF8Char:
6297 SetFailed(FK_PlainStringIntoUTF8Char);
6298 return;
6299 case SIF_UTF8StringIntoPlainChar:
6300 SetFailed(FK_UTF8StringIntoPlainChar);
6301 return;
6302 case SIF_Other:
6303 break;
6304 }
6305 }
6306
6307 // Some kinds of initialization permit an array to be initialized from
6308 // another array of the same type, and perform elementwise initialization.
6309 if (Initializer && isa<ConstantArrayType>(Val: DestAT) &&
6310 S.Context.hasSameUnqualifiedType(T1: Initializer->getType(),
6311 T2: Entity.getType()) &&
6312 canPerformArrayCopy(Entity)) {
6313 // If source is a prvalue, use it directly.
6314 if (Initializer->isPRValue()) {
6315 AddArrayInitStep(T: DestType, /*IsGNUExtension*/false);
6316 return;
6317 }
6318
6319 // Emit element-at-a-time copy loop.
6320 InitializedEntity Element =
6321 InitializedEntity::InitializeElement(Context&: S.Context, Index: 0, Parent: Entity);
6322 QualType InitEltT =
6323 Context.getAsArrayType(T: Initializer->getType())->getElementType();
6324 OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6325 Initializer->getValueKind(),
6326 Initializer->getObjectKind());
6327 Expr *OVEAsExpr = &OVE;
6328 InitializeFrom(S, Entity: Element, Kind, Args: OVEAsExpr, TopLevelOfInitList,
6329 TreatUnavailableAsInvalid);
6330 if (!Failed())
6331 AddArrayInitLoopStep(T: Entity.getType(), EltT: InitEltT);
6332 return;
6333 }
6334
6335 // Note: as an GNU C extension, we allow initialization of an
6336 // array from a compound literal that creates an array of the same
6337 // type, so long as the initializer has no side effects.
6338 if (!S.getLangOpts().CPlusPlus && Initializer &&
6339 isa<CompoundLiteralExpr>(Val: Initializer->IgnoreParens()) &&
6340 Initializer->getType()->isArrayType()) {
6341 const ArrayType *SourceAT
6342 = Context.getAsArrayType(T: Initializer->getType());
6343 if (!hasCompatibleArrayTypes(Context&: S.Context, Dest: DestAT, Source: SourceAT))
6344 SetFailed(FK_ArrayTypeMismatch);
6345 else if (Initializer->HasSideEffects(Ctx: S.Context))
6346 SetFailed(FK_NonConstantArrayInit);
6347 else {
6348 AddArrayInitStep(T: DestType, /*IsGNUExtension*/true);
6349 }
6350 }
6351 // Note: as a GNU C++ extension, we allow list-initialization of a
6352 // class member of array type from a parenthesized initializer list.
6353 else if (S.getLangOpts().CPlusPlus &&
6354 Entity.getKind() == InitializedEntity::EK_Member &&
6355 Initializer && isa<InitListExpr>(Val: Initializer)) {
6356 TryListInitialization(S, Entity, Kind, InitList: cast<InitListExpr>(Val: Initializer),
6357 Sequence&: *this, TreatUnavailableAsInvalid);
6358 AddParenthesizedArrayInitStep(T: DestType);
6359 } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6360 Kind.getKind() == InitializationKind::IK_Direct)
6361 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
6362 /*VerifyOnly=*/true);
6363 else if (DestAT->getElementType()->isCharType())
6364 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6365 else if (IsWideCharCompatible(T: DestAT->getElementType(), Context))
6366 SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6367 else
6368 SetFailed(FK_ArrayNeedsInitList);
6369
6370 return;
6371 }
6372
6373 // Determine whether we should consider writeback conversions for
6374 // Objective-C ARC.
6375 bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6376 Entity.isParameterKind();
6377
6378 if (TryOCLSamplerInitialization(S, Sequence&: *this, DestType, Initializer))
6379 return;
6380
6381 // We're at the end of the line for C: it's either a write-back conversion
6382 // or it's a C assignment. There's no need to check anything else.
6383 if (!S.getLangOpts().CPlusPlus) {
6384 assert(Initializer && "Initializer must be non-null");
6385 // If allowed, check whether this is an Objective-C writeback conversion.
6386 if (allowObjCWritebackConversion &&
6387 tryObjCWritebackConversion(S, Sequence&: *this, Entity, Initializer)) {
6388 return;
6389 }
6390
6391 if (TryOCLZeroOpaqueTypeInitialization(S, Sequence&: *this, DestType, Initializer))
6392 return;
6393
6394 // Handle initialization in C
6395 AddCAssignmentStep(T: DestType);
6396 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
6397 return;
6398 }
6399
6400 assert(S.getLangOpts().CPlusPlus);
6401
6402 // - If the destination type is a (possibly cv-qualified) class type:
6403 if (DestType->isRecordType()) {
6404 // - If the initialization is direct-initialization, or if it is
6405 // copy-initialization where the cv-unqualified version of the
6406 // source type is the same class as, or a derived class of, the
6407 // class of the destination, constructors are considered. [...]
6408 if (Kind.getKind() == InitializationKind::IK_Direct ||
6409 (Kind.getKind() == InitializationKind::IK_Copy &&
6410 (Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType) ||
6411 (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6412 SourceType, DestType))))) {
6413 TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestArrayType: DestType,
6414 Sequence&: *this);
6415
6416 // We fall back to the "no matching constructor" path if the
6417 // failed candidate set has functions other than the three default
6418 // constructors. For example, conversion function.
6419 if (const auto *RD =
6420 dyn_cast<CXXRecordDecl>(Val: DestType->getAs<RecordType>()->getDecl());
6421 // In general, we should call isCompleteType for RD to check its
6422 // completeness, we don't call it here as it was already called in the
6423 // above TryConstructorInitialization.
6424 S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6425 RD->isAggregate() && Failed() &&
6426 getFailureKind() == FK_ConstructorOverloadFailed) {
6427 // Do not attempt paren list initialization if overload resolution
6428 // resolves to a deleted function .
6429 //
6430 // We may reach this condition if we have a union wrapping a class with
6431 // a non-trivial copy or move constructor and we call one of those two
6432 // constructors. The union is an aggregate, but the matched constructor
6433 // is implicitly deleted, so we need to prevent aggregate initialization
6434 // (otherwise, it'll attempt aggregate initialization by initializing
6435 // the first element with a reference to the union).
6436 OverloadCandidateSet::iterator Best;
6437 OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
6438 S, Loc: Kind.getLocation(), Best);
6439 if (OR != OverloadingResult::OR_Deleted) {
6440 // C++20 [dcl.init] 17.6.2.2:
6441 // - Otherwise, if no constructor is viable, the destination type is
6442 // an
6443 // aggregate class, and the initializer is a parenthesized
6444 // expression-list.
6445 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
6446 /*VerifyOnly=*/true);
6447 }
6448 }
6449 } else {
6450 // - Otherwise (i.e., for the remaining copy-initialization cases),
6451 // user-defined conversion sequences that can convert from the
6452 // source type to the destination type or (when a conversion
6453 // function is used) to a derived class thereof are enumerated as
6454 // described in 13.3.1.4, and the best one is chosen through
6455 // overload resolution (13.3).
6456 assert(Initializer && "Initializer must be non-null");
6457 TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this,
6458 TopLevelOfInitList);
6459 }
6460 return;
6461 }
6462
6463 assert(Args.size() >= 1 && "Zero-argument case handled above");
6464
6465 // For HLSL ext vector types we allow list initialization behavior for C++
6466 // constructor syntax. This is accomplished by converting initialization
6467 // arguments an InitListExpr late.
6468 if (S.getLangOpts().HLSL && Args.size() > 1 && DestType->isExtVectorType() &&
6469 (SourceType.isNull() ||
6470 !Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType))) {
6471
6472 llvm::SmallVector<Expr *> InitArgs;
6473 for (auto *Arg : Args) {
6474 if (Arg->getType()->isExtVectorType()) {
6475 const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6476 unsigned Elm = VTy->getNumElements();
6477 for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6478 InitArgs.emplace_back(Args: new (Context) ArraySubscriptExpr(
6479 Arg,
6480 IntegerLiteral::Create(
6481 Context, llvm::APInt(Context.getIntWidth(T: Context.IntTy), Idx),
6482 Context.IntTy, SourceLocation()),
6483 VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6484 SourceLocation()));
6485 }
6486 } else
6487 InitArgs.emplace_back(Args&: Arg);
6488 }
6489 InitListExpr *ILE = new (Context) InitListExpr(
6490 S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6491 Args[0] = ILE;
6492 AddListInitializationStep(T: DestType);
6493 return;
6494 }
6495
6496 // The remaining cases all need a source type.
6497 if (Args.size() > 1) {
6498 SetFailed(FK_TooManyInitsForScalar);
6499 return;
6500 } else if (isa<InitListExpr>(Val: Args[0])) {
6501 SetFailed(FK_ParenthesizedListInitForScalar);
6502 return;
6503 }
6504
6505 // - Otherwise, if the source type is a (possibly cv-qualified) class
6506 // type, conversion functions are considered.
6507 if (!SourceType.isNull() && SourceType->isRecordType()) {
6508 assert(Initializer && "Initializer must be non-null");
6509 // For a conversion to _Atomic(T) from either T or a class type derived
6510 // from T, initialize the T object then convert to _Atomic type.
6511 bool NeedAtomicConversion = false;
6512 if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6513 if (Context.hasSameUnqualifiedType(T1: SourceType, T2: Atomic->getValueType()) ||
6514 S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6515 Atomic->getValueType())) {
6516 DestType = Atomic->getValueType();
6517 NeedAtomicConversion = true;
6518 }
6519 }
6520
6521 TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this,
6522 TopLevelOfInitList);
6523 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
6524 if (!Failed() && NeedAtomicConversion)
6525 AddAtomicConversionStep(Ty: Entity.getType());
6526 return;
6527 }
6528
6529 // - Otherwise, if the initialization is direct-initialization, the source
6530 // type is std::nullptr_t, and the destination type is bool, the initial
6531 // value of the object being initialized is false.
6532 if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6533 DestType->isBooleanType() &&
6534 Kind.getKind() == InitializationKind::IK_Direct) {
6535 AddConversionSequenceStep(
6536 ICS: ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
6537 NeedLValToRVal: Initializer->isGLValue()),
6538 T: DestType);
6539 return;
6540 }
6541
6542 // - Otherwise, the initial value of the object being initialized is the
6543 // (possibly converted) value of the initializer expression. Standard
6544 // conversions (Clause 4) will be used, if necessary, to convert the
6545 // initializer expression to the cv-unqualified version of the
6546 // destination type; no user-defined conversions are considered.
6547
6548 ImplicitConversionSequence ICS
6549 = S.TryImplicitConversion(From: Initializer, ToType: DestType,
6550 /*SuppressUserConversions*/true,
6551 AllowExplicit: Sema::AllowedExplicit::None,
6552 /*InOverloadResolution*/ false,
6553 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6554 AllowObjCWritebackConversion: allowObjCWritebackConversion);
6555
6556 if (ICS.isStandard() &&
6557 ICS.Standard.Second == ICK_Writeback_Conversion) {
6558 // Objective-C ARC writeback conversion.
6559
6560 // We should copy unless we're passing to an argument explicitly
6561 // marked 'out'.
6562 bool ShouldCopy = true;
6563 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl()))
6564 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6565
6566 // If there was an lvalue adjustment, add it as a separate conversion.
6567 if (ICS.Standard.First == ICK_Array_To_Pointer ||
6568 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6569 ImplicitConversionSequence LvalueICS;
6570 LvalueICS.setStandard();
6571 LvalueICS.Standard.setAsIdentityConversion();
6572 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(Idx: 0));
6573 LvalueICS.Standard.First = ICS.Standard.First;
6574 AddConversionSequenceStep(ICS: LvalueICS, T: ICS.Standard.getToType(Idx: 0));
6575 }
6576
6577 AddPassByIndirectCopyRestoreStep(type: DestType, shouldCopy: ShouldCopy);
6578 } else if (ICS.isBad()) {
6579 DeclAccessPair dap;
6580 if (isLibstdcxxPointerReturnFalseHack(S, Entity, Init: Initializer)) {
6581 AddZeroInitializationStep(T: Entity.getType());
6582 } else if (Initializer->getType() == Context.OverloadTy &&
6583 !S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, TargetType: DestType,
6584 Complain: false, Found&: dap))
6585 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
6586 else if (Initializer->getType()->isFunctionType() &&
6587 isExprAnUnaddressableFunction(S, E: Initializer))
6588 SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
6589 else
6590 SetFailed(InitializationSequence::FK_ConversionFailed);
6591 } else {
6592 AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList);
6593
6594 MaybeProduceObjCObject(S, Sequence&: *this, Entity);
6595 }
6596}
6597
6598InitializationSequence::~InitializationSequence() {
6599 for (auto &S : Steps)
6600 S.Destroy();
6601}
6602
6603//===----------------------------------------------------------------------===//
6604// Perform initialization
6605//===----------------------------------------------------------------------===//
6606static Sema::AssignmentAction
6607getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6608 switch(Entity.getKind()) {
6609 case InitializedEntity::EK_Variable:
6610 case InitializedEntity::EK_New:
6611 case InitializedEntity::EK_Exception:
6612 case InitializedEntity::EK_Base:
6613 case InitializedEntity::EK_Delegating:
6614 return Sema::AA_Initializing;
6615
6616 case InitializedEntity::EK_Parameter:
6617 if (Entity.getDecl() &&
6618 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6619 return Sema::AA_Sending;
6620
6621 return Sema::AA_Passing;
6622
6623 case InitializedEntity::EK_Parameter_CF_Audited:
6624 if (Entity.getDecl() &&
6625 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6626 return Sema::AA_Sending;
6627
6628 return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6629
6630 case InitializedEntity::EK_Result:
6631 case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6632 return Sema::AA_Returning;
6633
6634 case InitializedEntity::EK_Temporary:
6635 case InitializedEntity::EK_RelatedResult:
6636 // FIXME: Can we tell apart casting vs. converting?
6637 return Sema::AA_Casting;
6638
6639 case InitializedEntity::EK_TemplateParameter:
6640 // This is really initialization, but refer to it as conversion for
6641 // consistency with CheckConvertedConstantExpression.
6642 return Sema::AA_Converting;
6643
6644 case InitializedEntity::EK_Member:
6645 case InitializedEntity::EK_ParenAggInitMember:
6646 case InitializedEntity::EK_Binding:
6647 case InitializedEntity::EK_ArrayElement:
6648 case InitializedEntity::EK_VectorElement:
6649 case InitializedEntity::EK_ComplexElement:
6650 case InitializedEntity::EK_BlockElement:
6651 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6652 case InitializedEntity::EK_LambdaCapture:
6653 case InitializedEntity::EK_CompoundLiteralInit:
6654 return Sema::AA_Initializing;
6655 }
6656
6657 llvm_unreachable("Invalid EntityKind!");
6658}
6659
6660/// Whether we should bind a created object as a temporary when
6661/// initializing the given entity.
6662static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6663 switch (Entity.getKind()) {
6664 case InitializedEntity::EK_ArrayElement:
6665 case InitializedEntity::EK_Member:
6666 case InitializedEntity::EK_ParenAggInitMember:
6667 case InitializedEntity::EK_Result:
6668 case InitializedEntity::EK_StmtExprResult:
6669 case InitializedEntity::EK_New:
6670 case InitializedEntity::EK_Variable:
6671 case InitializedEntity::EK_Base:
6672 case InitializedEntity::EK_Delegating:
6673 case InitializedEntity::EK_VectorElement:
6674 case InitializedEntity::EK_ComplexElement:
6675 case InitializedEntity::EK_Exception:
6676 case InitializedEntity::EK_BlockElement:
6677 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6678 case InitializedEntity::EK_LambdaCapture:
6679 case InitializedEntity::EK_CompoundLiteralInit:
6680 case InitializedEntity::EK_TemplateParameter:
6681 return false;
6682
6683 case InitializedEntity::EK_Parameter:
6684 case InitializedEntity::EK_Parameter_CF_Audited:
6685 case InitializedEntity::EK_Temporary:
6686 case InitializedEntity::EK_RelatedResult:
6687 case InitializedEntity::EK_Binding:
6688 return true;
6689 }
6690
6691 llvm_unreachable("missed an InitializedEntity kind?");
6692}
6693
6694/// Whether the given entity, when initialized with an object
6695/// created for that initialization, requires destruction.
6696static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6697 switch (Entity.getKind()) {
6698 case InitializedEntity::EK_Result:
6699 case InitializedEntity::EK_StmtExprResult:
6700 case InitializedEntity::EK_New:
6701 case InitializedEntity::EK_Base:
6702 case InitializedEntity::EK_Delegating:
6703 case InitializedEntity::EK_VectorElement:
6704 case InitializedEntity::EK_ComplexElement:
6705 case InitializedEntity::EK_BlockElement:
6706 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6707 case InitializedEntity::EK_LambdaCapture:
6708 return false;
6709
6710 case InitializedEntity::EK_Member:
6711 case InitializedEntity::EK_ParenAggInitMember:
6712 case InitializedEntity::EK_Binding:
6713 case InitializedEntity::EK_Variable:
6714 case InitializedEntity::EK_Parameter:
6715 case InitializedEntity::EK_Parameter_CF_Audited:
6716 case InitializedEntity::EK_TemplateParameter:
6717 case InitializedEntity::EK_Temporary:
6718 case InitializedEntity::EK_ArrayElement:
6719 case InitializedEntity::EK_Exception:
6720 case InitializedEntity::EK_CompoundLiteralInit:
6721 case InitializedEntity::EK_RelatedResult:
6722 return true;
6723 }
6724
6725 llvm_unreachable("missed an InitializedEntity kind?");
6726}
6727
6728/// Get the location at which initialization diagnostics should appear.
6729static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
6730 Expr *Initializer) {
6731 switch (Entity.getKind()) {
6732 case InitializedEntity::EK_Result:
6733 case InitializedEntity::EK_StmtExprResult:
6734 return Entity.getReturnLoc();
6735
6736 case InitializedEntity::EK_Exception:
6737 return Entity.getThrowLoc();
6738
6739 case InitializedEntity::EK_Variable:
6740 case InitializedEntity::EK_Binding:
6741 return Entity.getDecl()->getLocation();
6742
6743 case InitializedEntity::EK_LambdaCapture:
6744 return Entity.getCaptureLoc();
6745
6746 case InitializedEntity::EK_ArrayElement:
6747 case InitializedEntity::EK_Member:
6748 case InitializedEntity::EK_ParenAggInitMember:
6749 case InitializedEntity::EK_Parameter:
6750 case InitializedEntity::EK_Parameter_CF_Audited:
6751 case InitializedEntity::EK_TemplateParameter:
6752 case InitializedEntity::EK_Temporary:
6753 case InitializedEntity::EK_New:
6754 case InitializedEntity::EK_Base:
6755 case InitializedEntity::EK_Delegating:
6756 case InitializedEntity::EK_VectorElement:
6757 case InitializedEntity::EK_ComplexElement:
6758 case InitializedEntity::EK_BlockElement:
6759 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6760 case InitializedEntity::EK_CompoundLiteralInit:
6761 case InitializedEntity::EK_RelatedResult:
6762 return Initializer->getBeginLoc();
6763 }
6764 llvm_unreachable("missed an InitializedEntity kind?");
6765}
6766
6767/// Make a (potentially elidable) temporary copy of the object
6768/// provided by the given initializer by calling the appropriate copy
6769/// constructor.
6770///
6771/// \param S The Sema object used for type-checking.
6772///
6773/// \param T The type of the temporary object, which must either be
6774/// the type of the initializer expression or a superclass thereof.
6775///
6776/// \param Entity The entity being initialized.
6777///
6778/// \param CurInit The initializer expression.
6779///
6780/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6781/// is permitted in C++03 (but not C++0x) when binding a reference to
6782/// an rvalue.
6783///
6784/// \returns An expression that copies the initializer expression into
6785/// a temporary object, or an error expression if a copy could not be
6786/// created.
6787static ExprResult CopyObject(Sema &S,
6788 QualType T,
6789 const InitializedEntity &Entity,
6790 ExprResult CurInit,
6791 bool IsExtraneousCopy) {
6792 if (CurInit.isInvalid())
6793 return CurInit;
6794 // Determine which class type we're copying to.
6795 Expr *CurInitExpr = (Expr *)CurInit.get();
6796 CXXRecordDecl *Class = nullptr;
6797 if (const RecordType *Record = T->getAs<RecordType>())
6798 Class = cast<CXXRecordDecl>(Val: Record->getDecl());
6799 if (!Class)
6800 return CurInit;
6801
6802 SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInit.get());
6803
6804 // Make sure that the type we are copying is complete.
6805 if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6806 return CurInit;
6807
6808 // Perform overload resolution using the class's constructors. Per
6809 // C++11 [dcl.init]p16, second bullet for class types, this initialization
6810 // is direct-initialization.
6811 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6812 DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
6813
6814 OverloadCandidateSet::iterator Best;
6815 switch (ResolveConstructorOverload(
6816 S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: T, Ctors, Best,
6817 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6818 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6819 /*RequireActualConstructor=*/false,
6820 /*SecondStepOfCopyInit=*/true)) {
6821 case OR_Success:
6822 break;
6823
6824 case OR_No_Viable_Function:
6825 CandidateSet.NoteCandidates(
6826 PartialDiagnosticAt(
6827 Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6828 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6829 : diag::err_temp_copy_no_viable)
6830 << (int)Entity.getKind() << CurInitExpr->getType()
6831 << CurInitExpr->getSourceRange()),
6832 S, OCD_AllCandidates, CurInitExpr);
6833 if (!IsExtraneousCopy || S.isSFINAEContext())
6834 return ExprError();
6835 return CurInit;
6836
6837 case OR_Ambiguous:
6838 CandidateSet.NoteCandidates(
6839 PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6840 << (int)Entity.getKind()
6841 << CurInitExpr->getType()
6842 << CurInitExpr->getSourceRange()),
6843 S, OCD_AmbiguousCandidates, CurInitExpr);
6844 return ExprError();
6845
6846 case OR_Deleted:
6847 S.Diag(Loc, diag::err_temp_copy_deleted)
6848 << (int)Entity.getKind() << CurInitExpr->getType()
6849 << CurInitExpr->getSourceRange();
6850 S.NoteDeletedFunction(FD: Best->Function);
6851 return ExprError();
6852 }
6853
6854 bool HadMultipleCandidates = CandidateSet.size() > 1;
6855
6856 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
6857 SmallVector<Expr*, 8> ConstructorArgs;
6858 CurInit.get(); // Ownership transferred into MultiExprArg, below.
6859
6860 S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Best->FoundDecl, Entity,
6861 IsCopyBindingRefToTemp: IsExtraneousCopy);
6862
6863 if (IsExtraneousCopy) {
6864 // If this is a totally extraneous copy for C++03 reference
6865 // binding purposes, just return the original initialization
6866 // expression. We don't generate an (elided) copy operation here
6867 // because doing so would require us to pass down a flag to avoid
6868 // infinite recursion, where each step adds another extraneous,
6869 // elidable copy.
6870
6871 // Instantiate the default arguments of any extra parameters in
6872 // the selected copy constructor, as if we were going to create a
6873 // proper call to the copy constructor.
6874 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6875 ParmVarDecl *Parm = Constructor->getParamDecl(I);
6876 if (S.RequireCompleteType(Loc, Parm->getType(),
6877 diag::err_call_incomplete_argument))
6878 break;
6879
6880 // Build the default argument expression; we don't actually care
6881 // if this succeeds or not, because this routine will complain
6882 // if there was a problem.
6883 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6884 }
6885
6886 return CurInitExpr;
6887 }
6888
6889 // Determine the arguments required to actually perform the
6890 // constructor call (we might have derived-to-base conversions, or
6891 // the copy constructor may have default arguments).
6892 if (S.CompleteConstructorCall(Constructor, DeclInitType: T, ArgsPtr: CurInitExpr, Loc,
6893 ConvertedArgs&: ConstructorArgs))
6894 return ExprError();
6895
6896 // C++0x [class.copy]p32:
6897 // When certain criteria are met, an implementation is allowed to
6898 // omit the copy/move construction of a class object, even if the
6899 // copy/move constructor and/or destructor for the object have
6900 // side effects. [...]
6901 // - when a temporary class object that has not been bound to a
6902 // reference (12.2) would be copied/moved to a class object
6903 // with the same cv-unqualified type, the copy/move operation
6904 // can be omitted by constructing the temporary object
6905 // directly into the target of the omitted copy/move
6906 //
6907 // Note that the other three bullets are handled elsewhere. Copy
6908 // elision for return statements and throw expressions are handled as part
6909 // of constructor initialization, while copy elision for exception handlers
6910 // is handled by the run-time.
6911 //
6912 // FIXME: If the function parameter is not the same type as the temporary, we
6913 // should still be able to elide the copy, but we don't have a way to
6914 // represent in the AST how much should be elided in this case.
6915 bool Elidable =
6916 CurInitExpr->isTemporaryObject(Ctx&: S.Context, TempTy: Class) &&
6917 S.Context.hasSameUnqualifiedType(
6918 T1: Best->Function->getParamDecl(i: 0)->getType().getNonReferenceType(),
6919 T2: CurInitExpr->getType());
6920
6921 // Actually perform the constructor call.
6922 CurInit = S.BuildCXXConstructExpr(
6923 ConstructLoc: Loc, DeclInitType: T, FoundDecl: Best->FoundDecl, Constructor, Elidable, Exprs: ConstructorArgs,
6924 HadMultipleCandidates,
6925 /*ListInit*/ IsListInitialization: false,
6926 /*StdInitListInit*/ IsStdInitListInitialization: false,
6927 /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
6928
6929 // If we're supposed to bind temporaries, do so.
6930 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6931 CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>());
6932 return CurInit;
6933}
6934
6935/// Check whether elidable copy construction for binding a reference to
6936/// a temporary would have succeeded if we were building in C++98 mode, for
6937/// -Wc++98-compat.
6938static void CheckCXX98CompatAccessibleCopy(Sema &S,
6939 const InitializedEntity &Entity,
6940 Expr *CurInitExpr) {
6941 assert(S.getLangOpts().CPlusPlus11);
6942
6943 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6944 if (!Record)
6945 return;
6946
6947 SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInitExpr);
6948 if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6949 return;
6950
6951 // Find constructors which would have been considered.
6952 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6953 DeclContext::lookup_result Ctors =
6954 S.LookupConstructors(Class: cast<CXXRecordDecl>(Val: Record->getDecl()));
6955
6956 // Perform overload resolution.
6957 OverloadCandidateSet::iterator Best;
6958 OverloadingResult OR = ResolveConstructorOverload(
6959 S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: CurInitExpr->getType(), Ctors, Best,
6960 /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6961 /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6962 /*RequireActualConstructor=*/false,
6963 /*SecondStepOfCopyInit=*/true);
6964
6965 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6966 << OR << (int)Entity.getKind() << CurInitExpr->getType()
6967 << CurInitExpr->getSourceRange();
6968
6969 switch (OR) {
6970 case OR_Success:
6971 S.CheckConstructorAccess(Loc, D: cast<CXXConstructorDecl>(Val: Best->Function),
6972 FoundDecl: Best->FoundDecl, Entity, PDiag: Diag);
6973 // FIXME: Check default arguments as far as that's possible.
6974 break;
6975
6976 case OR_No_Viable_Function:
6977 CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S,
6978 OCD: OCD_AllCandidates, Args: CurInitExpr);
6979 break;
6980
6981 case OR_Ambiguous:
6982 CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S,
6983 OCD: OCD_AmbiguousCandidates, Args: CurInitExpr);
6984 break;
6985
6986 case OR_Deleted:
6987 S.Diag(Loc, Diag);
6988 S.NoteDeletedFunction(FD: Best->Function);
6989 break;
6990 }
6991}
6992
6993void InitializationSequence::PrintInitLocationNote(Sema &S,
6994 const InitializedEntity &Entity) {
6995 if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6996 if (Entity.getDecl()->getLocation().isInvalid())
6997 return;
6998
6999 if (Entity.getDecl()->getDeclName())
7000 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
7001 << Entity.getDecl()->getDeclName();
7002 else
7003 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
7004 }
7005 else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
7006 Entity.getMethodDecl())
7007 S.Diag(Entity.getMethodDecl()->getLocation(),
7008 diag::note_method_return_type_change)
7009 << Entity.getMethodDecl()->getDeclName();
7010}
7011
7012/// Returns true if the parameters describe a constructor initialization of
7013/// an explicit temporary object, e.g. "Point(x, y)".
7014static bool isExplicitTemporary(const InitializedEntity &Entity,
7015 const InitializationKind &Kind,
7016 unsigned NumArgs) {
7017 switch (Entity.getKind()) {
7018 case InitializedEntity::EK_Temporary:
7019 case InitializedEntity::EK_CompoundLiteralInit:
7020 case InitializedEntity::EK_RelatedResult:
7021 break;
7022 default:
7023 return false;
7024 }
7025
7026 switch (Kind.getKind()) {
7027 case InitializationKind::IK_DirectList:
7028 return true;
7029 // FIXME: Hack to work around cast weirdness.
7030 case InitializationKind::IK_Direct:
7031 case InitializationKind::IK_Value:
7032 return NumArgs != 1;
7033 default:
7034 return false;
7035 }
7036}
7037
7038static ExprResult
7039PerformConstructorInitialization(Sema &S,
7040 const InitializedEntity &Entity,
7041 const InitializationKind &Kind,
7042 MultiExprArg Args,
7043 const InitializationSequence::Step& Step,
7044 bool &ConstructorInitRequiresZeroInit,
7045 bool IsListInitialization,
7046 bool IsStdInitListInitialization,
7047 SourceLocation LBraceLoc,
7048 SourceLocation RBraceLoc) {
7049 unsigned NumArgs = Args.size();
7050 CXXConstructorDecl *Constructor
7051 = cast<CXXConstructorDecl>(Val: Step.Function.Function);
7052 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7053
7054 // Build a call to the selected constructor.
7055 SmallVector<Expr*, 8> ConstructorArgs;
7056 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7057 ? Kind.getEqualLoc()
7058 : Kind.getLocation();
7059
7060 if (Kind.getKind() == InitializationKind::IK_Default) {
7061 // Force even a trivial, implicit default constructor to be
7062 // semantically checked. We do this explicitly because we don't build
7063 // the definition for completely trivial constructors.
7064 assert(Constructor->getParent() && "No parent class for constructor.");
7065 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7066 Constructor->isTrivial() && !Constructor->isUsed(false)) {
7067 S.runWithSufficientStackSpace(Loc, Fn: [&] {
7068 S.DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor);
7069 });
7070 }
7071 }
7072
7073 ExprResult CurInit((Expr *)nullptr);
7074
7075 // C++ [over.match.copy]p1:
7076 // - When initializing a temporary to be bound to the first parameter
7077 // of a constructor that takes a reference to possibly cv-qualified
7078 // T as its first argument, called with a single argument in the
7079 // context of direct-initialization, explicit conversion functions
7080 // are also considered.
7081 bool AllowExplicitConv =
7082 Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7083 hasCopyOrMoveCtorParam(Ctx&: S.Context,
7084 Info: getConstructorInfo(ND: Step.Function.FoundDecl));
7085
7086 // A smart pointer constructed from a nullable pointer is nullable.
7087 if (NumArgs == 1 && !Kind.isExplicitCast())
7088 S.diagnoseNullableToNonnullConversion(
7089 DstType: Entity.getType(), SrcType: Args.front()->getType(), Loc: Kind.getLocation());
7090
7091 // Determine the arguments required to actually perform the constructor
7092 // call.
7093 if (S.CompleteConstructorCall(Constructor, DeclInitType: Step.Type, ArgsPtr: Args, Loc,
7094 ConvertedArgs&: ConstructorArgs, AllowExplicit: AllowExplicitConv,
7095 IsListInitialization))
7096 return ExprError();
7097
7098 if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7099 // An explicitly-constructed temporary, e.g., X(1, 2).
7100 if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc))
7101 return ExprError();
7102
7103 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7104 if (!TSInfo)
7105 TSInfo = S.Context.getTrivialTypeSourceInfo(T: Entity.getType(), Loc);
7106 SourceRange ParenOrBraceRange =
7107 (Kind.getKind() == InitializationKind::IK_DirectList)
7108 ? SourceRange(LBraceLoc, RBraceLoc)
7109 : Kind.getParenOrBraceRange();
7110
7111 CXXConstructorDecl *CalleeDecl = Constructor;
7112 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7113 Val: Step.Function.FoundDecl.getDecl())) {
7114 CalleeDecl = S.findInheritingConstructor(Loc, BaseCtor: Constructor, DerivedShadow: Shadow);
7115 }
7116 S.MarkFunctionReferenced(Loc, CalleeDecl);
7117
7118 CurInit = S.CheckForImmediateInvocation(
7119 CXXTemporaryObjectExpr::Create(
7120 Ctx: S.Context, Cons: CalleeDecl,
7121 Ty: Entity.getType().getNonLValueExprType(Context: S.Context), TSI: TSInfo,
7122 Args: ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7123 ListInitialization: IsListInitialization, StdInitListInitialization: IsStdInitListInitialization,
7124 ZeroInitialization: ConstructorInitRequiresZeroInit),
7125 CalleeDecl);
7126 } else {
7127 CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;
7128
7129 if (Entity.getKind() == InitializedEntity::EK_Base) {
7130 ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7131 ? CXXConstructionKind::VirtualBase
7132 : CXXConstructionKind::NonVirtualBase;
7133 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7134 ConstructKind = CXXConstructionKind::Delegating;
7135 }
7136
7137 // Only get the parenthesis or brace range if it is a list initialization or
7138 // direct construction.
7139 SourceRange ParenOrBraceRange;
7140 if (IsListInitialization)
7141 ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7142 else if (Kind.getKind() == InitializationKind::IK_Direct)
7143 ParenOrBraceRange = Kind.getParenOrBraceRange();
7144
7145 // If the entity allows NRVO, mark the construction as elidable
7146 // unconditionally.
7147 if (Entity.allowsNRVO())
7148 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7149 Step.Function.FoundDecl,
7150 Constructor, /*Elidable=*/true,
7151 ConstructorArgs,
7152 HadMultipleCandidates,
7153 IsListInitialization,
7154 IsStdInitListInitialization,
7155 ConstructorInitRequiresZeroInit,
7156 ConstructKind,
7157 ParenOrBraceRange);
7158 else
7159 CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7160 Step.Function.FoundDecl,
7161 Constructor,
7162 ConstructorArgs,
7163 HadMultipleCandidates,
7164 IsListInitialization,
7165 IsStdInitListInitialization,
7166 ConstructorInitRequiresZeroInit,
7167 ConstructKind,
7168 ParenOrBraceRange);
7169 }
7170 if (CurInit.isInvalid())
7171 return ExprError();
7172
7173 // Only check access if all of that succeeded.
7174 S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Step.Function.FoundDecl, Entity);
7175 if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc))
7176 return ExprError();
7177
7178 if (const ArrayType *AT = S.Context.getAsArrayType(T: Entity.getType()))
7179 if (checkDestructorReference(ElementType: S.Context.getBaseElementType(VAT: AT), Loc, SemaRef&: S))
7180 return ExprError();
7181
7182 if (shouldBindAsTemporary(Entity))
7183 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
7184
7185 return CurInit;
7186}
7187
7188namespace {
7189enum LifetimeKind {
7190 /// The lifetime of a temporary bound to this entity ends at the end of the
7191 /// full-expression, and that's (probably) fine.
7192 LK_FullExpression,
7193
7194 /// The lifetime of a temporary bound to this entity is extended to the
7195 /// lifeitme of the entity itself.
7196 LK_Extended,
7197
7198 /// The lifetime of a temporary bound to this entity probably ends too soon,
7199 /// because the entity is allocated in a new-expression.
7200 LK_New,
7201
7202 /// The lifetime of a temporary bound to this entity ends too soon, because
7203 /// the entity is a return object.
7204 LK_Return,
7205
7206 /// The lifetime of a temporary bound to this entity ends too soon, because
7207 /// the entity is the result of a statement expression.
7208 LK_StmtExprResult,
7209
7210 /// This is a mem-initializer: if it would extend a temporary (other than via
7211 /// a default member initializer), the program is ill-formed.
7212 LK_MemInitializer,
7213};
7214using LifetimeResult =
7215 llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7216}
7217
7218/// Determine the declaration which an initialized entity ultimately refers to,
7219/// for the purpose of lifetime-extending a temporary bound to a reference in
7220/// the initialization of \p Entity.
7221static LifetimeResult getEntityLifetime(
7222 const InitializedEntity *Entity,
7223 const InitializedEntity *InitField = nullptr) {
7224 // C++11 [class.temporary]p5:
7225 switch (Entity->getKind()) {
7226 case InitializedEntity::EK_Variable:
7227 // The temporary [...] persists for the lifetime of the reference
7228 return {Entity, LK_Extended};
7229
7230 case InitializedEntity::EK_Member:
7231 // For subobjects, we look at the complete object.
7232 if (Entity->getParent())
7233 return getEntityLifetime(Entity: Entity->getParent(), InitField: Entity);
7234
7235 // except:
7236 // C++17 [class.base.init]p8:
7237 // A temporary expression bound to a reference member in a
7238 // mem-initializer is ill-formed.
7239 // C++17 [class.base.init]p11:
7240 // A temporary expression bound to a reference member from a
7241 // default member initializer is ill-formed.
7242 //
7243 // The context of p11 and its example suggest that it's only the use of a
7244 // default member initializer from a constructor that makes the program
7245 // ill-formed, not its mere existence, and that it can even be used by
7246 // aggregate initialization.
7247 return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7248 : LK_MemInitializer};
7249
7250 case InitializedEntity::EK_Binding:
7251 // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7252 // type.
7253 return {Entity, LK_Extended};
7254
7255 case InitializedEntity::EK_Parameter:
7256 case InitializedEntity::EK_Parameter_CF_Audited:
7257 // -- A temporary bound to a reference parameter in a function call
7258 // persists until the completion of the full-expression containing
7259 // the call.
7260 return {nullptr, LK_FullExpression};
7261
7262 case InitializedEntity::EK_TemplateParameter:
7263 // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7264 return {nullptr, LK_FullExpression};
7265
7266 case InitializedEntity::EK_Result:
7267 // -- The lifetime of a temporary bound to the returned value in a
7268 // function return statement is not extended; the temporary is
7269 // destroyed at the end of the full-expression in the return statement.
7270 return {nullptr, LK_Return};
7271
7272 case InitializedEntity::EK_StmtExprResult:
7273 // FIXME: Should we lifetime-extend through the result of a statement
7274 // expression?
7275 return {nullptr, LK_StmtExprResult};
7276
7277 case InitializedEntity::EK_New:
7278 // -- A temporary bound to a reference in a new-initializer persists
7279 // until the completion of the full-expression containing the
7280 // new-initializer.
7281 return {nullptr, LK_New};
7282
7283 case InitializedEntity::EK_Temporary:
7284 case InitializedEntity::EK_CompoundLiteralInit:
7285 case InitializedEntity::EK_RelatedResult:
7286 // We don't yet know the storage duration of the surrounding temporary.
7287 // Assume it's got full-expression duration for now, it will patch up our
7288 // storage duration if that's not correct.
7289 return {nullptr, LK_FullExpression};
7290
7291 case InitializedEntity::EK_ArrayElement:
7292 // For subobjects, we look at the complete object.
7293 return getEntityLifetime(Entity: Entity->getParent(), InitField);
7294
7295 case InitializedEntity::EK_Base:
7296 // For subobjects, we look at the complete object.
7297 if (Entity->getParent())
7298 return getEntityLifetime(Entity: Entity->getParent(), InitField);
7299 return {InitField, LK_MemInitializer};
7300
7301 case InitializedEntity::EK_Delegating:
7302 // We can reach this case for aggregate initialization in a constructor:
7303 // struct A { int &&r; };
7304 // struct B : A { B() : A{0} {} };
7305 // In this case, use the outermost field decl as the context.
7306 return {InitField, LK_MemInitializer};
7307
7308 case InitializedEntity::EK_BlockElement:
7309 case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7310 case InitializedEntity::EK_LambdaCapture:
7311 case InitializedEntity::EK_VectorElement:
7312 case InitializedEntity::EK_ComplexElement:
7313 return {nullptr, LK_FullExpression};
7314
7315 case InitializedEntity::EK_Exception:
7316 // FIXME: Can we diagnose lifetime problems with exceptions?
7317 return {nullptr, LK_FullExpression};
7318
7319 case InitializedEntity::EK_ParenAggInitMember:
7320 // -- A temporary object bound to a reference element of an aggregate of
7321 // class type initialized from a parenthesized expression-list
7322 // [dcl.init, 9.3] persists until the completion of the full-expression
7323 // containing the expression-list.
7324 return {nullptr, LK_FullExpression};
7325 }
7326
7327 llvm_unreachable("unknown entity kind");
7328}
7329
7330namespace {
7331enum ReferenceKind {
7332 /// Lifetime would be extended by a reference binding to a temporary.
7333 RK_ReferenceBinding,
7334 /// Lifetime would be extended by a std::initializer_list object binding to
7335 /// its backing array.
7336 RK_StdInitializerList,
7337};
7338
7339/// A temporary or local variable. This will be one of:
7340/// * A MaterializeTemporaryExpr.
7341/// * A DeclRefExpr whose declaration is a local.
7342/// * An AddrLabelExpr.
7343/// * A BlockExpr for a block with captures.
7344using Local = Expr*;
7345
7346/// Expressions we stepped over when looking for the local state. Any steps
7347/// that would inhibit lifetime extension or take us out of subexpressions of
7348/// the initializer are included.
7349struct IndirectLocalPathEntry {
7350 enum EntryKind {
7351 DefaultInit,
7352 AddressOf,
7353 VarInit,
7354 LValToRVal,
7355 LifetimeBoundCall,
7356 TemporaryCopy,
7357 LambdaCaptureInit,
7358 GslReferenceInit,
7359 GslPointerInit
7360 } Kind;
7361 Expr *E;
7362 union {
7363 const Decl *D = nullptr;
7364 const LambdaCapture *Capture;
7365 };
7366 IndirectLocalPathEntry() {}
7367 IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7368 IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7369 : Kind(K), E(E), D(D) {}
7370 IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7371 : Kind(K), E(E), Capture(Capture) {}
7372};
7373
7374using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7375
7376struct RevertToOldSizeRAII {
7377 IndirectLocalPath &Path;
7378 unsigned OldSize = Path.size();
7379 RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7380 ~RevertToOldSizeRAII() { Path.resize(N: OldSize); }
7381};
7382
7383using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7384 ReferenceKind RK)>;
7385}
7386
7387static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7388 for (auto E : Path)
7389 if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7390 return true;
7391 return false;
7392}
7393
7394static bool pathContainsInit(IndirectLocalPath &Path) {
7395 return llvm::any_of(Range&: Path, P: [=](IndirectLocalPathEntry E) {
7396 return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7397 E.Kind == IndirectLocalPathEntry::VarInit;
7398 });
7399}
7400
7401static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7402 Expr *Init, LocalVisitor Visit,
7403 bool RevisitSubinits,
7404 bool EnableLifetimeWarnings);
7405
7406static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7407 Expr *Init, ReferenceKind RK,
7408 LocalVisitor Visit,
7409 bool EnableLifetimeWarnings);
7410
7411template <typename T> static bool isRecordWithAttr(QualType Type) {
7412 if (auto *RD = Type->getAsCXXRecordDecl())
7413 return RD->hasAttr<T>();
7414 return false;
7415}
7416
7417// Decl::isInStdNamespace will return false for iterators in some STL
7418// implementations due to them being defined in a namespace outside of the std
7419// namespace.
7420static bool isInStlNamespace(const Decl *D) {
7421 const DeclContext *DC = D->getDeclContext();
7422 if (!DC)
7423 return false;
7424 if (const auto *ND = dyn_cast<NamespaceDecl>(Val: DC))
7425 if (const IdentifierInfo *II = ND->getIdentifier()) {
7426 StringRef Name = II->getName();
7427 if (Name.size() >= 2 && Name.front() == '_' &&
7428 (Name[1] == '_' || isUppercase(c: Name[1])))
7429 return true;
7430 }
7431
7432 return DC->isStdNamespace();
7433}
7434
7435static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
7436 if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Val: Callee))
7437 if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7438 return true;
7439 if (!isInStlNamespace(Callee->getParent()))
7440 return false;
7441 if (!isRecordWithAttr<PointerAttr>(
7442 Callee->getFunctionObjectParameterType()) &&
7443 !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7444 return false;
7445 if (Callee->getReturnType()->isPointerType() ||
7446 isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7447 if (!Callee->getIdentifier())
7448 return false;
7449 return llvm::StringSwitch<bool>(Callee->getName())
7450 .Cases(S0: "begin", S1: "rbegin", S2: "cbegin", S3: "crbegin", Value: true)
7451 .Cases(S0: "end", S1: "rend", S2: "cend", S3: "crend", Value: true)
7452 .Cases(S0: "c_str", S1: "data", S2: "get", Value: true)
7453 // Map and set types.
7454 .Cases(S0: "find", S1: "equal_range", S2: "lower_bound", S3: "upper_bound", Value: true)
7455 .Default(Value: false);
7456 } else if (Callee->getReturnType()->isReferenceType()) {
7457 if (!Callee->getIdentifier()) {
7458 auto OO = Callee->getOverloadedOperator();
7459 return OO == OverloadedOperatorKind::OO_Subscript ||
7460 OO == OverloadedOperatorKind::OO_Star;
7461 }
7462 return llvm::StringSwitch<bool>(Callee->getName())
7463 .Cases(S0: "front", S1: "back", S2: "at", S3: "top", S4: "value", Value: true)
7464 .Default(Value: false);
7465 }
7466 return false;
7467}
7468
7469static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
7470 if (!FD->getIdentifier() || FD->getNumParams() != 1)
7471 return false;
7472 const auto *RD = FD->getParamDecl(i: 0)->getType()->getPointeeCXXRecordDecl();
7473 if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7474 return false;
7475 if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7476 !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7477 return false;
7478 if (FD->getReturnType()->isPointerType() ||
7479 isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7480 return llvm::StringSwitch<bool>(FD->getName())
7481 .Cases(S0: "begin", S1: "rbegin", S2: "cbegin", S3: "crbegin", Value: true)
7482 .Cases(S0: "end", S1: "rend", S2: "cend", S3: "crend", Value: true)
7483 .Case(S: "data", Value: true)
7484 .Default(Value: false);
7485 } else if (FD->getReturnType()->isReferenceType()) {
7486 return llvm::StringSwitch<bool>(FD->getName())
7487 .Cases(S0: "get", S1: "any_cast", Value: true)
7488 .Default(Value: false);
7489 }
7490 return false;
7491}
7492
7493static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7494 LocalVisitor Visit) {
7495 auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7496 // We are not interested in the temporary base objects of gsl Pointers:
7497 // Temp().ptr; // Here ptr might not dangle.
7498 if (isa<MemberExpr>(Val: Arg->IgnoreImpCasts()))
7499 return;
7500 // Once we initialized a value with a reference, it can no longer dangle.
7501 if (!Value) {
7502 for (const IndirectLocalPathEntry &PE : llvm::reverse(C&: Path)) {
7503 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7504 continue;
7505 if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7506 return;
7507 break;
7508 }
7509 }
7510 Path.push_back(Elt: {Value ? IndirectLocalPathEntry::GslPointerInit
7511 : IndirectLocalPathEntry::GslReferenceInit,
7512 Arg, D});
7513 if (Arg->isGLValue())
7514 visitLocalsRetainedByReferenceBinding(Path, Init: Arg, RK: RK_ReferenceBinding,
7515 Visit,
7516 /*EnableLifetimeWarnings=*/true);
7517 else
7518 visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true,
7519 /*EnableLifetimeWarnings=*/true);
7520 Path.pop_back();
7521 };
7522
7523 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: Call)) {
7524 const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7525 if (MD && shouldTrackImplicitObjectArg(MD))
7526 VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7527 !MD->getReturnType()->isReferenceType());
7528 return;
7529 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: Call)) {
7530 FunctionDecl *Callee = OCE->getDirectCallee();
7531 if (Callee && Callee->isCXXInstanceMember() &&
7532 shouldTrackImplicitObjectArg(Callee: cast<CXXMethodDecl>(Val: Callee)))
7533 VisitPointerArg(Callee, OCE->getArg(0),
7534 !Callee->getReturnType()->isReferenceType());
7535 return;
7536 } else if (auto *CE = dyn_cast<CallExpr>(Val: Call)) {
7537 FunctionDecl *Callee = CE->getDirectCallee();
7538 if (Callee && shouldTrackFirstArgument(FD: Callee))
7539 VisitPointerArg(Callee, CE->getArg(Arg: 0),
7540 !Callee->getReturnType()->isReferenceType());
7541 return;
7542 }
7543
7544 if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Call)) {
7545 const auto *Ctor = CCE->getConstructor();
7546 const CXXRecordDecl *RD = Ctor->getParent();
7547 if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7548 VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7549 }
7550}
7551
7552static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
7553 const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7554 if (!TSI)
7555 return false;
7556 // Don't declare this variable in the second operand of the for-statement;
7557 // GCC miscompiles that by ending its lifetime before evaluating the
7558 // third operand. See gcc.gnu.org/PR86769.
7559 AttributedTypeLoc ATL;
7560 for (TypeLoc TL = TSI->getTypeLoc();
7561 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7562 TL = ATL.getModifiedLoc()) {
7563 if (ATL.getAttrAs<LifetimeBoundAttr>())
7564 return true;
7565 }
7566
7567 // Assume that all assignment operators with a "normal" return type return
7568 // *this, that is, an lvalue reference that is the same type as the implicit
7569 // object parameter (or the LHS for a non-member operator$=).
7570 OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
7571 if (OO == OO_Equal || isCompoundAssignmentOperator(Kind: OO)) {
7572 QualType RetT = FD->getReturnType();
7573 if (RetT->isLValueReferenceType()) {
7574 ASTContext &Ctx = FD->getASTContext();
7575 QualType LHST;
7576 auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7577 if (MD && MD->isCXXInstanceMember())
7578 LHST = Ctx.getLValueReferenceType(T: MD->getFunctionObjectParameterType());
7579 else
7580 LHST = MD->getParamDecl(0)->getType();
7581 if (Ctx.hasSameType(T1: RetT, T2: LHST))
7582 return true;
7583 }
7584 }
7585
7586 return false;
7587}
7588
7589static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7590 LocalVisitor Visit) {
7591 const FunctionDecl *Callee;
7592 ArrayRef<Expr*> Args;
7593
7594 if (auto *CE = dyn_cast<CallExpr>(Val: Call)) {
7595 Callee = CE->getDirectCallee();
7596 Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7597 } else {
7598 auto *CCE = cast<CXXConstructExpr>(Val: Call);
7599 Callee = CCE->getConstructor();
7600 Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7601 }
7602 if (!Callee)
7603 return;
7604
7605 Expr *ObjectArg = nullptr;
7606 if (isa<CXXOperatorCallExpr>(Val: Call) && Callee->isCXXInstanceMember()) {
7607 ObjectArg = Args[0];
7608 Args = Args.slice(N: 1);
7609 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Val: Call)) {
7610 ObjectArg = MCE->getImplicitObjectArgument();
7611 }
7612
7613 auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7614 Path.push_back(Elt: {IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7615 if (Arg->isGLValue())
7616 visitLocalsRetainedByReferenceBinding(Path, Init: Arg, RK: RK_ReferenceBinding,
7617 Visit,
7618 /*EnableLifetimeWarnings=*/false);
7619 else
7620 visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true,
7621 /*EnableLifetimeWarnings=*/false);
7622 Path.pop_back();
7623 };
7624
7625 bool CheckCoroCall = false;
7626 if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7627 CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7628 RD->hasAttr<CoroReturnTypeAttr>() &&
7629 !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
7630 }
7631
7632 if (ObjectArg) {
7633 bool CheckCoroObjArg = CheckCoroCall;
7634 // Coroutine lambda objects with empty capture list are not lifetimebound.
7635 if (auto *LE = dyn_cast<LambdaExpr>(Val: ObjectArg->IgnoreImplicit());
7636 LE && LE->captures().empty())
7637 CheckCoroObjArg = false;
7638 // Allow `get_return_object()` as the object param (__promise) is not
7639 // lifetimebound.
7640 if (Sema::CanBeGetReturnObject(FD: Callee))
7641 CheckCoroObjArg = false;
7642 if (implicitObjectParamIsLifetimeBound(FD: Callee) || CheckCoroObjArg)
7643 VisitLifetimeBoundArg(Callee, ObjectArg);
7644 }
7645
7646 for (unsigned I = 0,
7647 N = std::min<unsigned>(a: Callee->getNumParams(), b: Args.size());
7648 I != N; ++I) {
7649 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7650 VisitLifetimeBoundArg(Callee->getParamDecl(i: I), Args[I]);
7651 }
7652}
7653
7654/// Visit the locals that would be reachable through a reference bound to the
7655/// glvalue expression \c Init.
7656static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7657 Expr *Init, ReferenceKind RK,
7658 LocalVisitor Visit,
7659 bool EnableLifetimeWarnings) {
7660 RevertToOldSizeRAII RAII(Path);
7661
7662 // Walk past any constructs which we can lifetime-extend across.
7663 Expr *Old;
7664 do {
7665 Old = Init;
7666
7667 if (auto *FE = dyn_cast<FullExpr>(Val: Init))
7668 Init = FE->getSubExpr();
7669
7670 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init)) {
7671 // If this is just redundant braces around an initializer, step over it.
7672 if (ILE->isTransparent())
7673 Init = ILE->getInit(Init: 0);
7674 }
7675
7676 // Step over any subobject adjustments; we may have a materialized
7677 // temporary inside them.
7678 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7679
7680 // Per current approach for DR1376, look through casts to reference type
7681 // when performing lifetime extension.
7682 if (CastExpr *CE = dyn_cast<CastExpr>(Val: Init))
7683 if (CE->getSubExpr()->isGLValue())
7684 Init = CE->getSubExpr();
7685
7686 // Per the current approach for DR1299, look through array element access
7687 // on array glvalues when performing lifetime extension.
7688 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: Init)) {
7689 Init = ASE->getBase();
7690 auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Init);
7691 if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7692 Init = ICE->getSubExpr();
7693 else
7694 // We can't lifetime extend through this but we might still find some
7695 // retained temporaries.
7696 return visitLocalsRetainedByInitializer(Path, Init, Visit, RevisitSubinits: true,
7697 EnableLifetimeWarnings);
7698 }
7699
7700 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7701 // constructor inherits one as an implicit mem-initializer.
7702 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Val: Init)) {
7703 Path.push_back(
7704 {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7705 Init = DIE->getExpr();
7706 }
7707 } while (Init != Old);
7708
7709 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Init)) {
7710 if (Visit(Path, Local(MTE), RK))
7711 visitLocalsRetainedByInitializer(Path, Init: MTE->getSubExpr(), Visit, RevisitSubinits: true,
7712 EnableLifetimeWarnings);
7713 }
7714
7715 if (isa<CallExpr>(Val: Init)) {
7716 if (EnableLifetimeWarnings)
7717 handleGslAnnotatedTypes(Path, Call: Init, Visit);
7718 return visitLifetimeBoundArguments(Path, Call: Init, Visit);
7719 }
7720
7721 switch (Init->getStmtClass()) {
7722 case Stmt::DeclRefExprClass: {
7723 // If we find the name of a local non-reference parameter, we could have a
7724 // lifetime problem.
7725 auto *DRE = cast<DeclRefExpr>(Val: Init);
7726 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
7727 if (VD && VD->hasLocalStorage() &&
7728 !DRE->refersToEnclosingVariableOrCapture()) {
7729 if (!VD->getType()->isReferenceType()) {
7730 Visit(Path, Local(DRE), RK);
7731 } else if (isa<ParmVarDecl>(Val: DRE->getDecl())) {
7732 // The lifetime of a reference parameter is unknown; assume it's OK
7733 // for now.
7734 break;
7735 } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7736 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7737 visitLocalsRetainedByReferenceBinding(Path, Init: VD->getInit(),
7738 RK: RK_ReferenceBinding, Visit,
7739 EnableLifetimeWarnings);
7740 }
7741 }
7742 break;
7743 }
7744
7745 case Stmt::UnaryOperatorClass: {
7746 // The only unary operator that make sense to handle here
7747 // is Deref. All others don't resolve to a "name." This includes
7748 // handling all sorts of rvalues passed to a unary operator.
7749 const UnaryOperator *U = cast<UnaryOperator>(Val: Init);
7750 if (U->getOpcode() == UO_Deref)
7751 visitLocalsRetainedByInitializer(Path, Init: U->getSubExpr(), Visit, RevisitSubinits: true,
7752 EnableLifetimeWarnings);
7753 break;
7754 }
7755
7756 case Stmt::OMPArraySectionExprClass: {
7757 visitLocalsRetainedByInitializer(Path,
7758 Init: cast<OMPArraySectionExpr>(Val: Init)->getBase(),
7759 Visit, RevisitSubinits: true, EnableLifetimeWarnings);
7760 break;
7761 }
7762
7763 case Stmt::ConditionalOperatorClass:
7764 case Stmt::BinaryConditionalOperatorClass: {
7765 auto *C = cast<AbstractConditionalOperator>(Val: Init);
7766 if (!C->getTrueExpr()->getType()->isVoidType())
7767 visitLocalsRetainedByReferenceBinding(Path, Init: C->getTrueExpr(), RK, Visit,
7768 EnableLifetimeWarnings);
7769 if (!C->getFalseExpr()->getType()->isVoidType())
7770 visitLocalsRetainedByReferenceBinding(Path, Init: C->getFalseExpr(), RK, Visit,
7771 EnableLifetimeWarnings);
7772 break;
7773 }
7774
7775 case Stmt::CompoundLiteralExprClass: {
7776 if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Init)) {
7777 if (!CLE->isFileScope())
7778 Visit(Path, Local(CLE), RK);
7779 }
7780 break;
7781 }
7782
7783 // FIXME: Visit the left-hand side of an -> or ->*.
7784
7785 default:
7786 break;
7787 }
7788}
7789
7790/// Visit the locals that would be reachable through an object initialized by
7791/// the prvalue expression \c Init.
7792static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7793 Expr *Init, LocalVisitor Visit,
7794 bool RevisitSubinits,
7795 bool EnableLifetimeWarnings) {
7796 RevertToOldSizeRAII RAII(Path);
7797
7798 Expr *Old;
7799 do {
7800 Old = Init;
7801
7802 // Step into CXXDefaultInitExprs so we can diagnose cases where a
7803 // constructor inherits one as an implicit mem-initializer.
7804 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Val: Init)) {
7805 Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7806 Init = DIE->getExpr();
7807 }
7808
7809 if (auto *FE = dyn_cast<FullExpr>(Val: Init))
7810 Init = FE->getSubExpr();
7811
7812 // Dig out the expression which constructs the extended temporary.
7813 Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7814
7815 if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Init))
7816 Init = BTE->getSubExpr();
7817
7818 Init = Init->IgnoreParens();
7819
7820 // Step over value-preserving rvalue casts.
7821 if (auto *CE = dyn_cast<CastExpr>(Val: Init)) {
7822 switch (CE->getCastKind()) {
7823 case CK_LValueToRValue:
7824 // If we can match the lvalue to a const object, we can look at its
7825 // initializer.
7826 Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7827 return visitLocalsRetainedByReferenceBinding(
7828 Path, Init, RK: RK_ReferenceBinding,
7829 Visit: [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7830 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: L)) {
7831 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
7832 if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7833 !isVarOnPath(Path, VD)) {
7834 Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7835 visitLocalsRetainedByInitializer(Path, Init: VD->getInit(), Visit, RevisitSubinits: true,
7836 EnableLifetimeWarnings);
7837 }
7838 } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L)) {
7839 if (MTE->getType().isConstQualified())
7840 visitLocalsRetainedByInitializer(Path, Init: MTE->getSubExpr(), Visit,
7841 RevisitSubinits: true, EnableLifetimeWarnings);
7842 }
7843 return false;
7844 }, EnableLifetimeWarnings);
7845
7846 // We assume that objects can be retained by pointers cast to integers,
7847 // but not if the integer is cast to floating-point type or to _Complex.
7848 // We assume that casts to 'bool' do not preserve enough information to
7849 // retain a local object.
7850 case CK_NoOp:
7851 case CK_BitCast:
7852 case CK_BaseToDerived:
7853 case CK_DerivedToBase:
7854 case CK_UncheckedDerivedToBase:
7855 case CK_Dynamic:
7856 case CK_ToUnion:
7857 case CK_UserDefinedConversion:
7858 case CK_ConstructorConversion:
7859 case CK_IntegralToPointer:
7860 case CK_PointerToIntegral:
7861 case CK_VectorSplat:
7862 case CK_IntegralCast:
7863 case CK_CPointerToObjCPointerCast:
7864 case CK_BlockPointerToObjCPointerCast:
7865 case CK_AnyPointerToBlockPointerCast:
7866 case CK_AddressSpaceConversion:
7867 break;
7868
7869 case CK_ArrayToPointerDecay:
7870 // Model array-to-pointer decay as taking the address of the array
7871 // lvalue.
7872 Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7873 return visitLocalsRetainedByReferenceBinding(Path, Init: CE->getSubExpr(),
7874 RK: RK_ReferenceBinding, Visit,
7875 EnableLifetimeWarnings);
7876
7877 default:
7878 return;
7879 }
7880
7881 Init = CE->getSubExpr();
7882 }
7883 } while (Old != Init);
7884
7885 // C++17 [dcl.init.list]p6:
7886 // initializing an initializer_list object from the array extends the
7887 // lifetime of the array exactly like binding a reference to a temporary.
7888 if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Val: Init))
7889 return visitLocalsRetainedByReferenceBinding(Path, Init: ILE->getSubExpr(),
7890 RK: RK_StdInitializerList, Visit,
7891 EnableLifetimeWarnings);
7892
7893 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: Init)) {
7894 // We already visited the elements of this initializer list while
7895 // performing the initialization. Don't visit them again unless we've
7896 // changed the lifetime of the initialized entity.
7897 if (!RevisitSubinits)
7898 return;
7899
7900 if (ILE->isTransparent())
7901 return visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: 0), Visit,
7902 RevisitSubinits,
7903 EnableLifetimeWarnings);
7904
7905 if (ILE->getType()->isArrayType()) {
7906 for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7907 visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: I), Visit,
7908 RevisitSubinits,
7909 EnableLifetimeWarnings);
7910 return;
7911 }
7912
7913 if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7914 assert(RD->isAggregate() && "aggregate init on non-aggregate");
7915
7916 // If we lifetime-extend a braced initializer which is initializing an
7917 // aggregate, and that aggregate contains reference members which are
7918 // bound to temporaries, those temporaries are also lifetime-extended.
7919 if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7920 ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
7921 visitLocalsRetainedByReferenceBinding(Path, Init: ILE->getInit(Init: 0),
7922 RK: RK_ReferenceBinding, Visit,
7923 EnableLifetimeWarnings);
7924 else {
7925 unsigned Index = 0;
7926 for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7927 visitLocalsRetainedByInitializer(Path, Init: ILE->getInit(Init: Index), Visit,
7928 RevisitSubinits,
7929 EnableLifetimeWarnings);
7930 for (const auto *I : RD->fields()) {
7931 if (Index >= ILE->getNumInits())
7932 break;
7933 if (I->isUnnamedBitField())
7934 continue;
7935 Expr *SubInit = ILE->getInit(Index);
7936 if (I->getType()->isReferenceType())
7937 visitLocalsRetainedByReferenceBinding(Path, SubInit,
7938 RK_ReferenceBinding, Visit,
7939 EnableLifetimeWarnings);
7940 else
7941 // This might be either aggregate-initialization of a member or
7942 // initialization of a std::initializer_list object. Regardless,
7943 // we should recursively lifetime-extend that initializer.
7944 visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7945 RevisitSubinits,
7946 EnableLifetimeWarnings);
7947 ++Index;
7948 }
7949 }
7950 }
7951 return;
7952 }
7953
7954 // The lifetime of an init-capture is that of the closure object constructed
7955 // by a lambda-expression.
7956 if (auto *LE = dyn_cast<LambdaExpr>(Val: Init)) {
7957 LambdaExpr::capture_iterator CapI = LE->capture_begin();
7958 for (Expr *E : LE->capture_inits()) {
7959 assert(CapI != LE->capture_end());
7960 const LambdaCapture &Cap = *CapI++;
7961 if (!E)
7962 continue;
7963 if (Cap.capturesVariable())
7964 Path.push_back(Elt: {IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7965 if (E->isGLValue())
7966 visitLocalsRetainedByReferenceBinding(Path, Init: E, RK: RK_ReferenceBinding,
7967 Visit, EnableLifetimeWarnings);
7968 else
7969 visitLocalsRetainedByInitializer(Path, Init: E, Visit, RevisitSubinits: true,
7970 EnableLifetimeWarnings);
7971 if (Cap.capturesVariable())
7972 Path.pop_back();
7973 }
7974 }
7975
7976 // Assume that a copy or move from a temporary references the same objects
7977 // that the temporary does.
7978 if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Init)) {
7979 if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7980 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: CCE->getArg(Arg: 0))) {
7981 Expr *Arg = MTE->getSubExpr();
7982 Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7983 CCE->getConstructor()});
7984 visitLocalsRetainedByInitializer(Path, Init: Arg, Visit, RevisitSubinits: true,
7985 /*EnableLifetimeWarnings*/false);
7986 Path.pop_back();
7987 }
7988 }
7989 }
7990
7991 if (isa<CallExpr>(Val: Init) || isa<CXXConstructExpr>(Val: Init)) {
7992 if (EnableLifetimeWarnings)
7993 handleGslAnnotatedTypes(Path, Call: Init, Visit);
7994 return visitLifetimeBoundArguments(Path, Call: Init, Visit);
7995 }
7996
7997 switch (Init->getStmtClass()) {
7998 case Stmt::UnaryOperatorClass: {
7999 auto *UO = cast<UnaryOperator>(Val: Init);
8000 // If the initializer is the address of a local, we could have a lifetime
8001 // problem.
8002 if (UO->getOpcode() == UO_AddrOf) {
8003 // If this is &rvalue, then it's ill-formed and we have already diagnosed
8004 // it. Don't produce a redundant warning about the lifetime of the
8005 // temporary.
8006 if (isa<MaterializeTemporaryExpr>(Val: UO->getSubExpr()))
8007 return;
8008
8009 Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
8010 visitLocalsRetainedByReferenceBinding(Path, Init: UO->getSubExpr(),
8011 RK: RK_ReferenceBinding, Visit,
8012 EnableLifetimeWarnings);
8013 }
8014 break;
8015 }
8016
8017 case Stmt::BinaryOperatorClass: {
8018 // Handle pointer arithmetic.
8019 auto *BO = cast<BinaryOperator>(Val: Init);
8020 BinaryOperatorKind BOK = BO->getOpcode();
8021 if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
8022 break;
8023
8024 if (BO->getLHS()->getType()->isPointerType())
8025 visitLocalsRetainedByInitializer(Path, Init: BO->getLHS(), Visit, RevisitSubinits: true,
8026 EnableLifetimeWarnings);
8027 else if (BO->getRHS()->getType()->isPointerType())
8028 visitLocalsRetainedByInitializer(Path, Init: BO->getRHS(), Visit, RevisitSubinits: true,
8029 EnableLifetimeWarnings);
8030 break;
8031 }
8032
8033 case Stmt::ConditionalOperatorClass:
8034 case Stmt::BinaryConditionalOperatorClass: {
8035 auto *C = cast<AbstractConditionalOperator>(Val: Init);
8036 // In C++, we can have a throw-expression operand, which has 'void' type
8037 // and isn't interesting from a lifetime perspective.
8038 if (!C->getTrueExpr()->getType()->isVoidType())
8039 visitLocalsRetainedByInitializer(Path, Init: C->getTrueExpr(), Visit, RevisitSubinits: true,
8040 EnableLifetimeWarnings);
8041 if (!C->getFalseExpr()->getType()->isVoidType())
8042 visitLocalsRetainedByInitializer(Path, Init: C->getFalseExpr(), Visit, RevisitSubinits: true,
8043 EnableLifetimeWarnings);
8044 break;
8045 }
8046
8047 case Stmt::BlockExprClass:
8048 if (cast<BlockExpr>(Val: Init)->getBlockDecl()->hasCaptures()) {
8049 // This is a local block, whose lifetime is that of the function.
8050 Visit(Path, Local(cast<BlockExpr>(Val: Init)), RK_ReferenceBinding);
8051 }
8052 break;
8053
8054 case Stmt::AddrLabelExprClass:
8055 // We want to warn if the address of a label would escape the function.
8056 Visit(Path, Local(cast<AddrLabelExpr>(Val: Init)), RK_ReferenceBinding);
8057 break;
8058
8059 default:
8060 break;
8061 }
8062}
8063
8064/// Whether a path to an object supports lifetime extension.
8065enum PathLifetimeKind {
8066 /// Lifetime-extend along this path.
8067 Extend,
8068 /// We should lifetime-extend, but we don't because (due to technical
8069 /// limitations) we can't. This happens for default member initializers,
8070 /// which we don't clone for every use, so we don't have a unique
8071 /// MaterializeTemporaryExpr to update.
8072 ShouldExtend,
8073 /// Do not lifetime extend along this path.
8074 NoExtend
8075};
8076
8077/// Determine whether this is an indirect path to a temporary that we are
8078/// supposed to lifetime-extend along.
8079static PathLifetimeKind
8080shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8081 PathLifetimeKind Kind = PathLifetimeKind::Extend;
8082 for (auto Elem : Path) {
8083 if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8084 Kind = PathLifetimeKind::ShouldExtend;
8085 else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8086 return PathLifetimeKind::NoExtend;
8087 }
8088 return Kind;
8089}
8090
8091/// Find the range for the first interesting entry in the path at or after I.
8092static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8093 Expr *E) {
8094 for (unsigned N = Path.size(); I != N; ++I) {
8095 switch (Path[I].Kind) {
8096 case IndirectLocalPathEntry::AddressOf:
8097 case IndirectLocalPathEntry::LValToRVal:
8098 case IndirectLocalPathEntry::LifetimeBoundCall:
8099 case IndirectLocalPathEntry::TemporaryCopy:
8100 case IndirectLocalPathEntry::GslReferenceInit:
8101 case IndirectLocalPathEntry::GslPointerInit:
8102 // These exist primarily to mark the path as not permitting or
8103 // supporting lifetime extension.
8104 break;
8105
8106 case IndirectLocalPathEntry::VarInit:
8107 if (cast<VarDecl>(Val: Path[I].D)->isImplicit())
8108 return SourceRange();
8109 [[fallthrough]];
8110 case IndirectLocalPathEntry::DefaultInit:
8111 return Path[I].E->getSourceRange();
8112
8113 case IndirectLocalPathEntry::LambdaCaptureInit:
8114 if (!Path[I].Capture->capturesVariable())
8115 continue;
8116 return Path[I].E->getSourceRange();
8117 }
8118 }
8119 return E->getSourceRange();
8120}
8121
8122static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8123 for (const auto &It : llvm::reverse(C&: Path)) {
8124 if (It.Kind == IndirectLocalPathEntry::VarInit)
8125 continue;
8126 if (It.Kind == IndirectLocalPathEntry::AddressOf)
8127 continue;
8128 if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8129 continue;
8130 return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8131 It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8132 }
8133 return false;
8134}
8135
8136void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
8137 Expr *Init) {
8138 LifetimeResult LR = getEntityLifetime(Entity: &Entity);
8139 LifetimeKind LK = LR.getInt();
8140 const InitializedEntity *ExtendingEntity = LR.getPointer();
8141
8142 // If this entity doesn't have an interesting lifetime, don't bother looking
8143 // for temporaries within its initializer.
8144 if (LK == LK_FullExpression)
8145 return;
8146
8147 auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8148 ReferenceKind RK) -> bool {
8149 SourceRange DiagRange = nextPathEntryRange(Path, I: 0, E: L);
8150 SourceLocation DiagLoc = DiagRange.getBegin();
8151
8152 auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: L);
8153
8154 bool IsGslPtrInitWithGslTempOwner = false;
8155 bool IsLocalGslOwner = false;
8156 if (pathOnlyInitializesGslPointer(Path)) {
8157 if (isa<DeclRefExpr>(Val: L)) {
8158 // We do not want to follow the references when returning a pointer originating
8159 // from a local owner to avoid the following false positive:
8160 // int &p = *localUniquePtr;
8161 // someContainer.add(std::move(localUniquePtr));
8162 // return p;
8163 IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8164 if (pathContainsInit(Path) || !IsLocalGslOwner)
8165 return false;
8166 } else {
8167 IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8168 isRecordWithAttr<OwnerAttr>(MTE->getType());
8169 // Skipping a chain of initializing gsl::Pointer annotated objects.
8170 // We are looking only for the final source to find out if it was
8171 // a local or temporary owner or the address of a local variable/param.
8172 if (!IsGslPtrInitWithGslTempOwner)
8173 return true;
8174 }
8175 }
8176
8177 switch (LK) {
8178 case LK_FullExpression:
8179 llvm_unreachable("already handled this");
8180
8181 case LK_Extended: {
8182 if (!MTE) {
8183 // The initialized entity has lifetime beyond the full-expression,
8184 // and the local entity does too, so don't warn.
8185 //
8186 // FIXME: We should consider warning if a static / thread storage
8187 // duration variable retains an automatic storage duration local.
8188 return false;
8189 }
8190
8191 if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8192 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8193 return false;
8194 }
8195
8196 switch (shouldLifetimeExtendThroughPath(Path)) {
8197 case PathLifetimeKind::Extend:
8198 // Update the storage duration of the materialized temporary.
8199 // FIXME: Rebuild the expression instead of mutating it.
8200 MTE->setExtendingDecl(ExtendedBy: ExtendingEntity->getDecl(),
8201 ManglingNumber: ExtendingEntity->allocateManglingNumber());
8202 // Also visit the temporaries lifetime-extended by this initializer.
8203 return true;
8204
8205 case PathLifetimeKind::ShouldExtend:
8206 // We're supposed to lifetime-extend the temporary along this path (per
8207 // the resolution of DR1815), but we don't support that yet.
8208 //
8209 // FIXME: Properly handle this situation. Perhaps the easiest approach
8210 // would be to clone the initializer expression on each use that would
8211 // lifetime extend its temporaries.
8212 Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8213 << RK << DiagRange;
8214 break;
8215
8216 case PathLifetimeKind::NoExtend:
8217 // If the path goes through the initialization of a variable or field,
8218 // it can't possibly reach a temporary created in this full-expression.
8219 // We will have already diagnosed any problems with the initializer.
8220 if (pathContainsInit(Path))
8221 return false;
8222
8223 Diag(DiagLoc, diag::warn_dangling_variable)
8224 << RK << !Entity.getParent()
8225 << ExtendingEntity->getDecl()->isImplicit()
8226 << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8227 break;
8228 }
8229 break;
8230 }
8231
8232 case LK_MemInitializer: {
8233 if (isa<MaterializeTemporaryExpr>(Val: L)) {
8234 // Under C++ DR1696, if a mem-initializer (or a default member
8235 // initializer used by the absence of one) would lifetime-extend a
8236 // temporary, the program is ill-formed.
8237 if (auto *ExtendingDecl =
8238 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8239 if (IsGslPtrInitWithGslTempOwner) {
8240 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8241 << ExtendingDecl << DiagRange;
8242 Diag(ExtendingDecl->getLocation(),
8243 diag::note_ref_or_ptr_member_declared_here)
8244 << true;
8245 return false;
8246 }
8247 bool IsSubobjectMember = ExtendingEntity != &Entity;
8248 Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8249 PathLifetimeKind::NoExtend
8250 ? diag::err_dangling_member
8251 : diag::warn_dangling_member)
8252 << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8253 // Don't bother adding a note pointing to the field if we're inside
8254 // its default member initializer; our primary diagnostic points to
8255 // the same place in that case.
8256 if (Path.empty() ||
8257 Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8258 Diag(ExtendingDecl->getLocation(),
8259 diag::note_lifetime_extending_member_declared_here)
8260 << RK << IsSubobjectMember;
8261 }
8262 } else {
8263 // We have a mem-initializer but no particular field within it; this
8264 // is either a base class or a delegating initializer directly
8265 // initializing the base-class from something that doesn't live long
8266 // enough.
8267 //
8268 // FIXME: Warn on this.
8269 return false;
8270 }
8271 } else {
8272 // Paths via a default initializer can only occur during error recovery
8273 // (there's no other way that a default initializer can refer to a
8274 // local). Don't produce a bogus warning on those cases.
8275 if (pathContainsInit(Path))
8276 return false;
8277
8278 // Suppress false positives for code like the one below:
8279 // Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8280 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8281 return false;
8282
8283 auto *DRE = dyn_cast<DeclRefExpr>(Val: L);
8284 auto *VD = DRE ? dyn_cast<VarDecl>(Val: DRE->getDecl()) : nullptr;
8285 if (!VD) {
8286 // A member was initialized to a local block.
8287 // FIXME: Warn on this.
8288 return false;
8289 }
8290
8291 if (auto *Member =
8292 ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8293 bool IsPointer = !Member->getType()->isReferenceType();
8294 Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8295 : diag::warn_bind_ref_member_to_parameter)
8296 << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8297 Diag(Member->getLocation(),
8298 diag::note_ref_or_ptr_member_declared_here)
8299 << (unsigned)IsPointer;
8300 }
8301 }
8302 break;
8303 }
8304
8305 case LK_New:
8306 if (isa<MaterializeTemporaryExpr>(Val: L)) {
8307 if (IsGslPtrInitWithGslTempOwner)
8308 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8309 else
8310 Diag(DiagLoc, RK == RK_ReferenceBinding
8311 ? diag::warn_new_dangling_reference
8312 : diag::warn_new_dangling_initializer_list)
8313 << !Entity.getParent() << DiagRange;
8314 } else {
8315 // We can't determine if the allocation outlives the local declaration.
8316 return false;
8317 }
8318 break;
8319
8320 case LK_Return:
8321 case LK_StmtExprResult:
8322 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: L)) {
8323 // We can't determine if the local variable outlives the statement
8324 // expression.
8325 if (LK == LK_StmtExprResult)
8326 return false;
8327 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8328 << Entity.getType()->isReferenceType() << DRE->getDecl()
8329 << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8330 } else if (isa<BlockExpr>(Val: L)) {
8331 Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8332 } else if (isa<AddrLabelExpr>(Val: L)) {
8333 // Don't warn when returning a label from a statement expression.
8334 // Leaving the scope doesn't end its lifetime.
8335 if (LK == LK_StmtExprResult)
8336 return false;
8337 Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8338 } else if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: L)) {
8339 Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8340 << Entity.getType()->isReferenceType() << CLE->getInitializer() << 2
8341 << DiagRange;
8342 } else {
8343 Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8344 << Entity.getType()->isReferenceType() << DiagRange;
8345 }
8346 break;
8347 }
8348
8349 for (unsigned I = 0; I != Path.size(); ++I) {
8350 auto Elem = Path[I];
8351
8352 switch (Elem.Kind) {
8353 case IndirectLocalPathEntry::AddressOf:
8354 case IndirectLocalPathEntry::LValToRVal:
8355 // These exist primarily to mark the path as not permitting or
8356 // supporting lifetime extension.
8357 break;
8358
8359 case IndirectLocalPathEntry::LifetimeBoundCall:
8360 case IndirectLocalPathEntry::TemporaryCopy:
8361 case IndirectLocalPathEntry::GslPointerInit:
8362 case IndirectLocalPathEntry::GslReferenceInit:
8363 // FIXME: Consider adding a note for these.
8364 break;
8365
8366 case IndirectLocalPathEntry::DefaultInit: {
8367 auto *FD = cast<FieldDecl>(Val: Elem.D);
8368 Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8369 << FD << nextPathEntryRange(Path, I + 1, L);
8370 break;
8371 }
8372
8373 case IndirectLocalPathEntry::VarInit: {
8374 const VarDecl *VD = cast<VarDecl>(Val: Elem.D);
8375 Diag(VD->getLocation(), diag::note_local_var_initializer)
8376 << VD->getType()->isReferenceType()
8377 << VD->isImplicit() << VD->getDeclName()
8378 << nextPathEntryRange(Path, I + 1, L);
8379 break;
8380 }
8381
8382 case IndirectLocalPathEntry::LambdaCaptureInit:
8383 if (!Elem.Capture->capturesVariable())
8384 break;
8385 // FIXME: We can't easily tell apart an init-capture from a nested
8386 // capture of an init-capture.
8387 const ValueDecl *VD = Elem.Capture->getCapturedVar();
8388 Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8389 << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8390 << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8391 << nextPathEntryRange(Path, I + 1, L);
8392 break;
8393 }
8394 }
8395
8396 // We didn't lifetime-extend, so don't go any further; we don't need more
8397 // warnings or errors on inner temporaries within this one's initializer.
8398 return false;
8399 };
8400
8401 bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8402 diag::warn_dangling_lifetime_pointer, SourceLocation());
8403 llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
8404 if (Init->isGLValue())
8405 visitLocalsRetainedByReferenceBinding(Path, Init, RK: RK_ReferenceBinding,
8406 Visit: TemporaryVisitor,
8407 EnableLifetimeWarnings);
8408 else
8409 visitLocalsRetainedByInitializer(Path, Init, Visit: TemporaryVisitor, RevisitSubinits: false,
8410 EnableLifetimeWarnings);
8411}
8412
8413static void DiagnoseNarrowingInInitList(Sema &S,
8414 const ImplicitConversionSequence &ICS,
8415 QualType PreNarrowingType,
8416 QualType EntityType,
8417 const Expr *PostInit);
8418
8419static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
8420 QualType ToType, Expr *Init);
8421
8422/// Provide warnings when std::move is used on construction.
8423static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8424 bool IsReturnStmt) {
8425 if (!InitExpr)
8426 return;
8427
8428 if (S.inTemplateInstantiation())
8429 return;
8430
8431 QualType DestType = InitExpr->getType();
8432 if (!DestType->isRecordType())
8433 return;
8434
8435 unsigned DiagID = 0;
8436 if (IsReturnStmt) {
8437 const CXXConstructExpr *CCE =
8438 dyn_cast<CXXConstructExpr>(Val: InitExpr->IgnoreParens());
8439 if (!CCE || CCE->getNumArgs() != 1)
8440 return;
8441
8442 if (!CCE->getConstructor()->isCopyOrMoveConstructor())
8443 return;
8444
8445 InitExpr = CCE->getArg(Arg: 0)->IgnoreImpCasts();
8446 }
8447
8448 // Find the std::move call and get the argument.
8449 const CallExpr *CE = dyn_cast<CallExpr>(Val: InitExpr->IgnoreParens());
8450 if (!CE || !CE->isCallToStdMove())
8451 return;
8452
8453 const Expr *Arg = CE->getArg(Arg: 0)->IgnoreImplicit();
8454
8455 if (IsReturnStmt) {
8456 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts());
8457 if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8458 return;
8459
8460 const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
8461 if (!VD || !VD->hasLocalStorage())
8462 return;
8463
8464 // __block variables are not moved implicitly.
8465 if (VD->hasAttr<BlocksAttr>())
8466 return;
8467
8468 QualType SourceType = VD->getType();
8469 if (!SourceType->isRecordType())
8470 return;
8471
8472 if (!S.Context.hasSameUnqualifiedType(T1: DestType, T2: SourceType)) {
8473 return;
8474 }
8475
8476 // If we're returning a function parameter, copy elision
8477 // is not possible.
8478 if (isa<ParmVarDecl>(VD))
8479 DiagID = diag::warn_redundant_move_on_return;
8480 else
8481 DiagID = diag::warn_pessimizing_move_on_return;
8482 } else {
8483 DiagID = diag::warn_pessimizing_move_on_initialization;
8484 const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8485 if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8486 return;
8487 }
8488
8489 S.Diag(CE->getBeginLoc(), DiagID);
8490
8491 // Get all the locations for a fix-it. Don't emit the fix-it if any location
8492 // is within a macro.
8493 SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8494 if (CallBegin.isMacroID())
8495 return;
8496 SourceLocation RParen = CE->getRParenLoc();
8497 if (RParen.isMacroID())
8498 return;
8499 SourceLocation LParen;
8500 SourceLocation ArgLoc = Arg->getBeginLoc();
8501
8502 // Special testing for the argument location. Since the fix-it needs the
8503 // location right before the argument, the argument location can be in a
8504 // macro only if it is at the beginning of the macro.
8505 while (ArgLoc.isMacroID() &&
8506 S.getSourceManager().isAtStartOfImmediateMacroExpansion(Loc: ArgLoc)) {
8507 ArgLoc = S.getSourceManager().getImmediateExpansionRange(Loc: ArgLoc).getBegin();
8508 }
8509
8510 if (LParen.isMacroID())
8511 return;
8512
8513 LParen = ArgLoc.getLocWithOffset(Offset: -1);
8514
8515 S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8516 << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8517 << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8518}
8519
8520static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8521 // Check to see if we are dereferencing a null pointer. If so, this is
8522 // undefined behavior, so warn about it. This only handles the pattern
8523 // "*null", which is a very syntactic check.
8524 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts()))
8525 if (UO->getOpcode() == UO_Deref &&
8526 UO->getSubExpr()->IgnoreParenCasts()->
8527 isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
8528 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8529 S.PDiag(diag::warn_binding_null_to_reference)
8530 << UO->getSubExpr()->getSourceRange());
8531 }
8532}
8533
8534MaterializeTemporaryExpr *
8535Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
8536 bool BoundToLvalueReference) {
8537 auto MTE = new (Context)
8538 MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8539
8540 // Order an ExprWithCleanups for lifetime marks.
8541 //
8542 // TODO: It'll be good to have a single place to check the access of the
8543 // destructor and generate ExprWithCleanups for various uses. Currently these
8544 // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8545 // but there may be a chance to merge them.
8546 Cleanup.setExprNeedsCleanups(false);
8547 if (isInLifetimeExtendingContext()) {
8548 auto &Record = ExprEvalContexts.back();
8549 Record.ForRangeLifetimeExtendTemps.push_back(Elt: MTE);
8550 }
8551 return MTE;
8552}
8553
8554ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
8555 // In C++98, we don't want to implicitly create an xvalue.
8556 // FIXME: This means that AST consumers need to deal with "prvalues" that
8557 // denote materialized temporaries. Maybe we should add another ValueKind
8558 // for "xvalue pretending to be a prvalue" for C++98 support.
8559 if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8560 return E;
8561
8562 // C++1z [conv.rval]/1: T shall be a complete type.
8563 // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8564 // If so, we should check for a non-abstract class type here too.
8565 QualType T = E->getType();
8566 if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8567 return ExprError();
8568
8569 return CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: false);
8570}
8571
8572ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
8573 ExprValueKind VK,
8574 CheckedConversionKind CCK) {
8575
8576 CastKind CK = CK_NoOp;
8577
8578 if (VK == VK_PRValue) {
8579 auto PointeeTy = Ty->getPointeeType();
8580 auto ExprPointeeTy = E->getType()->getPointeeType();
8581 if (!PointeeTy.isNull() &&
8582 PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8583 CK = CK_AddressSpaceConversion;
8584 } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8585 CK = CK_AddressSpaceConversion;
8586 }
8587
8588 return ImpCastExprToType(E, Type: Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8589}
8590
8591ExprResult InitializationSequence::Perform(Sema &S,
8592 const InitializedEntity &Entity,
8593 const InitializationKind &Kind,
8594 MultiExprArg Args,
8595 QualType *ResultType) {
8596 if (Failed()) {
8597 Diagnose(S, Entity, Kind, Args);
8598 return ExprError();
8599 }
8600 if (!ZeroInitializationFixit.empty()) {
8601 const Decl *D = Entity.getDecl();
8602 const auto *VD = dyn_cast_or_null<VarDecl>(Val: D);
8603 QualType DestType = Entity.getType();
8604
8605 // The initialization would have succeeded with this fixit. Since the fixit
8606 // is on the error, we need to build a valid AST in this case, so this isn't
8607 // handled in the Failed() branch above.
8608 if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8609 // Use a more useful diagnostic for constexpr variables.
8610 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8611 << VD
8612 << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8613 ZeroInitializationFixit);
8614 } else {
8615 unsigned DiagID = diag::err_default_init_const;
8616 if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8617 DiagID = diag::ext_default_init_const;
8618
8619 S.Diag(Kind.getLocation(), DiagID)
8620 << DestType << (bool)DestType->getAs<RecordType>()
8621 << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc,
8622 Code: ZeroInitializationFixit);
8623 }
8624 }
8625
8626 if (getKind() == DependentSequence) {
8627 // If the declaration is a non-dependent, incomplete array type
8628 // that has an initializer, then its type will be completed once
8629 // the initializer is instantiated.
8630 if (ResultType && !Entity.getType()->isDependentType() &&
8631 Args.size() == 1) {
8632 QualType DeclType = Entity.getType();
8633 if (const IncompleteArrayType *ArrayT
8634 = S.Context.getAsIncompleteArrayType(T: DeclType)) {
8635 // FIXME: We don't currently have the ability to accurately
8636 // compute the length of an initializer list without
8637 // performing full type-checking of the initializer list
8638 // (since we have to determine where braces are implicitly
8639 // introduced and such). So, we fall back to making the array
8640 // type a dependently-sized array type with no specified
8641 // bound.
8642 if (isa<InitListExpr>(Val: (Expr *)Args[0])) {
8643 SourceRange Brackets;
8644
8645 // Scavange the location of the brackets from the entity, if we can.
8646 if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Val: Entity.getDecl())) {
8647 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8648 TypeLoc TL = TInfo->getTypeLoc();
8649 if (IncompleteArrayTypeLoc ArrayLoc =
8650 TL.getAs<IncompleteArrayTypeLoc>())
8651 Brackets = ArrayLoc.getBracketsRange();
8652 }
8653 }
8654
8655 *ResultType
8656 = S.Context.getDependentSizedArrayType(EltTy: ArrayT->getElementType(),
8657 /*NumElts=*/nullptr,
8658 ASM: ArrayT->getSizeModifier(),
8659 IndexTypeQuals: ArrayT->getIndexTypeCVRQualifiers(),
8660 Brackets);
8661 }
8662
8663 }
8664 }
8665 if (Kind.getKind() == InitializationKind::IK_Direct &&
8666 !Kind.isExplicitCast()) {
8667 // Rebuild the ParenListExpr.
8668 SourceRange ParenRange = Kind.getParenOrBraceRange();
8669 return S.ActOnParenListExpr(L: ParenRange.getBegin(), R: ParenRange.getEnd(),
8670 Val: Args);
8671 }
8672 assert(Kind.getKind() == InitializationKind::IK_Copy ||
8673 Kind.isExplicitCast() ||
8674 Kind.getKind() == InitializationKind::IK_DirectList);
8675 return ExprResult(Args[0]);
8676 }
8677
8678 // No steps means no initialization.
8679 if (Steps.empty())
8680 return ExprResult((Expr *)nullptr);
8681
8682 if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8683 Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) &&
8684 !Entity.isParamOrTemplateParamKind()) {
8685 // Produce a C++98 compatibility warning if we are initializing a reference
8686 // from an initializer list. For parameters, we produce a better warning
8687 // elsewhere.
8688 Expr *Init = Args[0];
8689 S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8690 << Init->getSourceRange();
8691 }
8692
8693 if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8694 isa<PredefinedExpr>(Val: Args[0]) && Entity.getType()->isArrayType()) {
8695 // Produce a Microsoft compatibility warning when initializing from a
8696 // predefined expression since MSVC treats predefined expressions as string
8697 // literals.
8698 Expr *Init = Args[0];
8699 S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8700 }
8701
8702 // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8703 QualType ETy = Entity.getType();
8704 bool HasGlobalAS = ETy.hasAddressSpace() &&
8705 ETy.getAddressSpace() == LangAS::opencl_global;
8706
8707 if (S.getLangOpts().OpenCLVersion >= 200 &&
8708 ETy->isAtomicType() && !HasGlobalAS &&
8709 Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8710 S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8711 << 1
8712 << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8713 return ExprError();
8714 }
8715
8716 QualType DestType = Entity.getType().getNonReferenceType();
8717 // FIXME: Ugly hack around the fact that Entity.getType() is not
8718 // the same as Entity.getDecl()->getType() in cases involving type merging,
8719 // and we want latter when it makes sense.
8720 if (ResultType)
8721 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8722 Entity.getType();
8723
8724 ExprResult CurInit((Expr *)nullptr);
8725 SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8726
8727 // HLSL allows vector initialization to function like list initialization, but
8728 // use the syntax of a C++-like constructor.
8729 bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8730 isa<InitListExpr>(Val: Args[0]);
8731 (void)IsHLSLVectorInit;
8732
8733 // For initialization steps that start with a single initializer,
8734 // grab the only argument out the Args and place it into the "current"
8735 // initializer.
8736 switch (Steps.front().Kind) {
8737 case SK_ResolveAddressOfOverloadedFunction:
8738 case SK_CastDerivedToBasePRValue:
8739 case SK_CastDerivedToBaseXValue:
8740 case SK_CastDerivedToBaseLValue:
8741 case SK_BindReference:
8742 case SK_BindReferenceToTemporary:
8743 case SK_FinalCopy:
8744 case SK_ExtraneousCopyToTemporary:
8745 case SK_UserConversion:
8746 case SK_QualificationConversionLValue:
8747 case SK_QualificationConversionXValue:
8748 case SK_QualificationConversionPRValue:
8749 case SK_FunctionReferenceConversion:
8750 case SK_AtomicConversion:
8751 case SK_ConversionSequence:
8752 case SK_ConversionSequenceNoNarrowing:
8753 case SK_ListInitialization:
8754 case SK_UnwrapInitList:
8755 case SK_RewrapInitList:
8756 case SK_CAssignment:
8757 case SK_StringInit:
8758 case SK_ObjCObjectConversion:
8759 case SK_ArrayLoopIndex:
8760 case SK_ArrayLoopInit:
8761 case SK_ArrayInit:
8762 case SK_GNUArrayInit:
8763 case SK_ParenthesizedArrayInit:
8764 case SK_PassByIndirectCopyRestore:
8765 case SK_PassByIndirectRestore:
8766 case SK_ProduceObjCObject:
8767 case SK_StdInitializerList:
8768 case SK_OCLSamplerInit:
8769 case SK_OCLZeroOpaqueType: {
8770 assert(Args.size() == 1 || IsHLSLVectorInit);
8771 CurInit = Args[0];
8772 if (!CurInit.get()) return ExprError();
8773 break;
8774 }
8775
8776 case SK_ConstructorInitialization:
8777 case SK_ConstructorInitializationFromList:
8778 case SK_StdInitializerListConstructorCall:
8779 case SK_ZeroInitialization:
8780 case SK_ParenthesizedListInit:
8781 break;
8782 }
8783
8784 // Promote from an unevaluated context to an unevaluated list context in
8785 // C++11 list-initialization; we need to instantiate entities usable in
8786 // constant expressions here in order to perform narrowing checks =(
8787 EnterExpressionEvaluationContext Evaluated(
8788 S, EnterExpressionEvaluationContext::InitList,
8789 CurInit.get() && isa<InitListExpr>(Val: CurInit.get()));
8790
8791 // C++ [class.abstract]p2:
8792 // no objects of an abstract class can be created except as subobjects
8793 // of a class derived from it
8794 auto checkAbstractType = [&](QualType T) -> bool {
8795 if (Entity.getKind() == InitializedEntity::EK_Base ||
8796 Entity.getKind() == InitializedEntity::EK_Delegating)
8797 return false;
8798 return S.RequireNonAbstractType(Kind.getLocation(), T,
8799 diag::err_allocation_of_abstract_type);
8800 };
8801
8802 // Walk through the computed steps for the initialization sequence,
8803 // performing the specified conversions along the way.
8804 bool ConstructorInitRequiresZeroInit = false;
8805 for (step_iterator Step = step_begin(), StepEnd = step_end();
8806 Step != StepEnd; ++Step) {
8807 if (CurInit.isInvalid())
8808 return ExprError();
8809
8810 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8811
8812 switch (Step->Kind) {
8813 case SK_ResolveAddressOfOverloadedFunction:
8814 // Overload resolution determined which function invoke; update the
8815 // initializer to reflect that choice.
8816 S.CheckAddressOfMemberAccess(OvlExpr: CurInit.get(), FoundDecl: Step->Function.FoundDecl);
8817 if (S.DiagnoseUseOfDecl(D: Step->Function.FoundDecl, Locs: Kind.getLocation()))
8818 return ExprError();
8819 CurInit = S.FixOverloadedFunctionReference(CurInit,
8820 FoundDecl: Step->Function.FoundDecl,
8821 Fn: Step->Function.Function);
8822 // We might get back another placeholder expression if we resolved to a
8823 // builtin.
8824 if (!CurInit.isInvalid())
8825 CurInit = S.CheckPlaceholderExpr(E: CurInit.get());
8826 break;
8827
8828 case SK_CastDerivedToBasePRValue:
8829 case SK_CastDerivedToBaseXValue:
8830 case SK_CastDerivedToBaseLValue: {
8831 // We have a derived-to-base cast that produces either an rvalue or an
8832 // lvalue. Perform that cast.
8833
8834 CXXCastPath BasePath;
8835
8836 // Casts to inaccessible base classes are allowed with C-style casts.
8837 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8838 if (S.CheckDerivedToBaseConversion(
8839 SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8840 CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8841 return ExprError();
8842
8843 ExprValueKind VK =
8844 Step->Kind == SK_CastDerivedToBaseLValue
8845 ? VK_LValue
8846 : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8847 : VK_PRValue);
8848 CurInit = ImplicitCastExpr::Create(Context: S.Context, T: Step->Type,
8849 Kind: CK_DerivedToBase, Operand: CurInit.get(),
8850 BasePath: &BasePath, Cat: VK, FPO: FPOptionsOverride());
8851 break;
8852 }
8853
8854 case SK_BindReference:
8855 // Reference binding does not have any corresponding ASTs.
8856
8857 // Check exception specifications
8858 if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType))
8859 return ExprError();
8860
8861 // We don't check for e.g. function pointers here, since address
8862 // availability checks should only occur when the function first decays
8863 // into a pointer or reference.
8864 if (CurInit.get()->getType()->isFunctionProtoType()) {
8865 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CurInit.get()->IgnoreParens())) {
8866 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) {
8867 if (!S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
8868 Loc: DRE->getBeginLoc()))
8869 return ExprError();
8870 }
8871 }
8872 }
8873
8874 CheckForNullPointerDereference(S, E: CurInit.get());
8875 break;
8876
8877 case SK_BindReferenceToTemporary: {
8878 // Make sure the "temporary" is actually an rvalue.
8879 assert(CurInit.get()->isPRValue() && "not a temporary");
8880
8881 // Check exception specifications
8882 if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType))
8883 return ExprError();
8884
8885 QualType MTETy = Step->Type;
8886
8887 // When this is an incomplete array type (such as when this is
8888 // initializing an array of unknown bounds from an init list), use THAT
8889 // type instead so that we propagate the array bounds.
8890 if (MTETy->isIncompleteArrayType() &&
8891 !CurInit.get()->getType()->isIncompleteArrayType() &&
8892 S.Context.hasSameType(
8893 T1: MTETy->getPointeeOrArrayElementType(),
8894 T2: CurInit.get()->getType()->getPointeeOrArrayElementType()))
8895 MTETy = CurInit.get()->getType();
8896
8897 // Materialize the temporary into memory.
8898 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8899 T: MTETy, Temporary: CurInit.get(), BoundToLvalueReference: Entity.getType()->isLValueReferenceType());
8900 CurInit = MTE;
8901
8902 // If we're extending this temporary to automatic storage duration -- we
8903 // need to register its cleanup during the full-expression's cleanups.
8904 if (MTE->getStorageDuration() == SD_Automatic &&
8905 MTE->getType().isDestructedType())
8906 S.Cleanup.setExprNeedsCleanups(true);
8907 break;
8908 }
8909
8910 case SK_FinalCopy:
8911 if (checkAbstractType(Step->Type))
8912 return ExprError();
8913
8914 // If the overall initialization is initializing a temporary, we already
8915 // bound our argument if it was necessary to do so. If not (if we're
8916 // ultimately initializing a non-temporary), our argument needs to be
8917 // bound since it's initializing a function parameter.
8918 // FIXME: This is a mess. Rationalize temporary destruction.
8919 if (!shouldBindAsTemporary(Entity))
8920 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
8921 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8922 /*IsExtraneousCopy=*/false);
8923 break;
8924
8925 case SK_ExtraneousCopyToTemporary:
8926 CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8927 /*IsExtraneousCopy=*/true);
8928 break;
8929
8930 case SK_UserConversion: {
8931 // We have a user-defined conversion that invokes either a constructor
8932 // or a conversion function.
8933 CastKind CastKind;
8934 FunctionDecl *Fn = Step->Function.Function;
8935 DeclAccessPair FoundFn = Step->Function.FoundDecl;
8936 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8937 bool CreatedObject = false;
8938 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
8939 // Build a call to the selected constructor.
8940 SmallVector<Expr*, 8> ConstructorArgs;
8941 SourceLocation Loc = CurInit.get()->getBeginLoc();
8942
8943 // Determine the arguments required to actually perform the constructor
8944 // call.
8945 Expr *Arg = CurInit.get();
8946 if (S.CompleteConstructorCall(Constructor, DeclInitType: Step->Type,
8947 ArgsPtr: MultiExprArg(&Arg, 1), Loc,
8948 ConvertedArgs&: ConstructorArgs))
8949 return ExprError();
8950
8951 // Build an expression that constructs a temporary.
8952 CurInit = S.BuildCXXConstructExpr(
8953 Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8954 HadMultipleCandidates,
8955 /*ListInit*/ false,
8956 /*StdInitListInit*/ false,
8957 /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8958 if (CurInit.isInvalid())
8959 return ExprError();
8960
8961 S.CheckConstructorAccess(Loc: Kind.getLocation(), D: Constructor, FoundDecl: FoundFn,
8962 Entity);
8963 if (S.DiagnoseUseOfDecl(D: FoundFn, Locs: Kind.getLocation()))
8964 return ExprError();
8965
8966 CastKind = CK_ConstructorConversion;
8967 CreatedObject = true;
8968 } else {
8969 // Build a call to the conversion function.
8970 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Val: Fn);
8971 S.CheckMemberOperatorAccess(Loc: Kind.getLocation(), ObjectExpr: CurInit.get(), ArgExpr: nullptr,
8972 FoundDecl: FoundFn);
8973 if (S.DiagnoseUseOfDecl(D: FoundFn, Locs: Kind.getLocation()))
8974 return ExprError();
8975
8976 CurInit = S.BuildCXXMemberCallExpr(Exp: CurInit.get(), FoundDecl: FoundFn, Method: Conversion,
8977 HadMultipleCandidates);
8978 if (CurInit.isInvalid())
8979 return ExprError();
8980
8981 CastKind = CK_UserDefinedConversion;
8982 CreatedObject = Conversion->getReturnType()->isRecordType();
8983 }
8984
8985 if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8986 return ExprError();
8987
8988 CurInit = ImplicitCastExpr::Create(
8989 Context: S.Context, T: CurInit.get()->getType(), Kind: CastKind, Operand: CurInit.get(), BasePath: nullptr,
8990 Cat: CurInit.get()->getValueKind(), FPO: S.CurFPFeatureOverrides());
8991
8992 if (shouldBindAsTemporary(Entity))
8993 // The overall entity is temporary, so this expression should be
8994 // destroyed at the end of its full-expression.
8995 CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>());
8996 else if (CreatedObject && shouldDestroyEntity(Entity)) {
8997 // The object outlasts the full-expression, but we need to prepare for
8998 // a destructor being run on it.
8999 // FIXME: It makes no sense to do this here. This should happen
9000 // regardless of how we initialized the entity.
9001 QualType T = CurInit.get()->getType();
9002 if (const RecordType *Record = T->getAs<RecordType>()) {
9003 CXXDestructorDecl *Destructor
9004 = S.LookupDestructor(Class: cast<CXXRecordDecl>(Val: Record->getDecl()));
9005 S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
9006 S.PDiag(diag::err_access_dtor_temp) << T);
9007 S.MarkFunctionReferenced(Loc: CurInit.get()->getBeginLoc(), Func: Destructor);
9008 if (S.DiagnoseUseOfDecl(D: Destructor, Locs: CurInit.get()->getBeginLoc()))
9009 return ExprError();
9010 }
9011 }
9012 break;
9013 }
9014
9015 case SK_QualificationConversionLValue:
9016 case SK_QualificationConversionXValue:
9017 case SK_QualificationConversionPRValue: {
9018 // Perform a qualification conversion; these can never go wrong.
9019 ExprValueKind VK =
9020 Step->Kind == SK_QualificationConversionLValue
9021 ? VK_LValue
9022 : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
9023 : VK_PRValue);
9024 CurInit = S.PerformQualificationConversion(E: CurInit.get(), Ty: Step->Type, VK);
9025 break;
9026 }
9027
9028 case SK_FunctionReferenceConversion:
9029 assert(CurInit.get()->isLValue() &&
9030 "function reference should be lvalue");
9031 CurInit =
9032 S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, CK: CK_NoOp, VK: VK_LValue);
9033 break;
9034
9035 case SK_AtomicConversion: {
9036 assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
9037 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
9038 CK: CK_NonAtomicToAtomic, VK: VK_PRValue);
9039 break;
9040 }
9041
9042 case SK_ConversionSequence:
9043 case SK_ConversionSequenceNoNarrowing: {
9044 if (const auto *FromPtrType =
9045 CurInit.get()->getType()->getAs<PointerType>()) {
9046 if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
9047 if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9048 !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9049 // Do not check static casts here because they are checked earlier
9050 // in Sema::ActOnCXXNamedCast()
9051 if (!Kind.isStaticCast()) {
9052 S.Diag(CurInit.get()->getExprLoc(),
9053 diag::warn_noderef_to_dereferenceable_pointer)
9054 << CurInit.get()->getSourceRange();
9055 }
9056 }
9057 }
9058 }
9059
9060 CheckedConversionKind CCK =
9061 Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast
9062 : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast
9063 : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast
9064 : CheckedConversionKind::Implicit;
9065 ExprResult CurInitExprRes =
9066 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
9067 getAssignmentAction(Entity), CCK);
9068 if (CurInitExprRes.isInvalid())
9069 return ExprError();
9070
9071 S.DiscardMisalignedMemberAddress(T: Step->Type.getTypePtr(), E: CurInit.get());
9072
9073 CurInit = CurInitExprRes;
9074
9075 if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
9076 S.getLangOpts().CPlusPlus)
9077 DiagnoseNarrowingInInitList(S, ICS: *Step->ICS, PreNarrowingType: SourceType, EntityType: Entity.getType(),
9078 PostInit: CurInit.get());
9079
9080 break;
9081 }
9082
9083 case SK_ListInitialization: {
9084 if (checkAbstractType(Step->Type))
9085 return ExprError();
9086
9087 InitListExpr *InitList = cast<InitListExpr>(Val: CurInit.get());
9088 // If we're not initializing the top-level entity, we need to create an
9089 // InitializeTemporary entity for our target type.
9090 QualType Ty = Step->Type;
9091 bool IsTemporary = !S.Context.hasSameType(T1: Entity.getType(), T2: Ty);
9092 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Type: Ty);
9093 InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9094 InitListChecker PerformInitList(S, InitEntity,
9095 InitList, Ty, /*VerifyOnly=*/false,
9096 /*TreatUnavailableAsInvalid=*/false);
9097 if (PerformInitList.HadError())
9098 return ExprError();
9099
9100 // Hack: We must update *ResultType if available in order to set the
9101 // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9102 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9103 if (ResultType &&
9104 ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9105 if ((*ResultType)->isRValueReferenceType())
9106 Ty = S.Context.getRValueReferenceType(T: Ty);
9107 else if ((*ResultType)->isLValueReferenceType())
9108 Ty = S.Context.getLValueReferenceType(T: Ty,
9109 SpelledAsLValue: (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9110 *ResultType = Ty;
9111 }
9112
9113 InitListExpr *StructuredInitList =
9114 PerformInitList.getFullyStructuredList();
9115 CurInit.get();
9116 CurInit = shouldBindAsTemporary(Entity: InitEntity)
9117 ? S.MaybeBindToTemporary(StructuredInitList)
9118 : StructuredInitList;
9119 break;
9120 }
9121
9122 case SK_ConstructorInitializationFromList: {
9123 if (checkAbstractType(Step->Type))
9124 return ExprError();
9125
9126 // When an initializer list is passed for a parameter of type "reference
9127 // to object", we don't get an EK_Temporary entity, but instead an
9128 // EK_Parameter entity with reference type.
9129 // FIXME: This is a hack. What we really should do is create a user
9130 // conversion step for this case, but this makes it considerably more
9131 // complicated. For now, this will do.
9132 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9133 Type: Entity.getType().getNonReferenceType());
9134 bool UseTemporary = Entity.getType()->isReferenceType();
9135 assert(Args.size() == 1 && "expected a single argument for list init");
9136 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9137 S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9138 << InitList->getSourceRange();
9139 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9140 CurInit = PerformConstructorInitialization(S, Entity: UseTemporary ? TempEntity :
9141 Entity,
9142 Kind, Args: Arg, Step: *Step,
9143 ConstructorInitRequiresZeroInit,
9144 /*IsListInitialization*/true,
9145 /*IsStdInitListInit*/IsStdInitListInitialization: false,
9146 LBraceLoc: InitList->getLBraceLoc(),
9147 RBraceLoc: InitList->getRBraceLoc());
9148 break;
9149 }
9150
9151 case SK_UnwrapInitList:
9152 CurInit = cast<InitListExpr>(Val: CurInit.get())->getInit(Init: 0);
9153 break;
9154
9155 case SK_RewrapInitList: {
9156 Expr *E = CurInit.get();
9157 InitListExpr *Syntactic = Step->WrappingSyntacticList;
9158 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9159 Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9160 ILE->setSyntacticForm(Syntactic);
9161 ILE->setType(E->getType());
9162 ILE->setValueKind(E->getValueKind());
9163 CurInit = ILE;
9164 break;
9165 }
9166
9167 case SK_ConstructorInitialization:
9168 case SK_StdInitializerListConstructorCall: {
9169 if (checkAbstractType(Step->Type))
9170 return ExprError();
9171
9172 // When an initializer list is passed for a parameter of type "reference
9173 // to object", we don't get an EK_Temporary entity, but instead an
9174 // EK_Parameter entity with reference type.
9175 // FIXME: This is a hack. What we really should do is create a user
9176 // conversion step for this case, but this makes it considerably more
9177 // complicated. For now, this will do.
9178 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9179 Type: Entity.getType().getNonReferenceType());
9180 bool UseTemporary = Entity.getType()->isReferenceType();
9181 bool IsStdInitListInit =
9182 Step->Kind == SK_StdInitializerListConstructorCall;
9183 Expr *Source = CurInit.get();
9184 SourceRange Range = Kind.hasParenOrBraceRange()
9185 ? Kind.getParenOrBraceRange()
9186 : SourceRange();
9187 CurInit = PerformConstructorInitialization(
9188 S, Entity: UseTemporary ? TempEntity : Entity, Kind,
9189 Args: Source ? MultiExprArg(Source) : Args, Step: *Step,
9190 ConstructorInitRequiresZeroInit,
9191 /*IsListInitialization*/ IsStdInitListInit,
9192 /*IsStdInitListInitialization*/ IsStdInitListInit,
9193 /*LBraceLoc*/ Range.getBegin(),
9194 /*RBraceLoc*/ Range.getEnd());
9195 break;
9196 }
9197
9198 case SK_ZeroInitialization: {
9199 step_iterator NextStep = Step;
9200 ++NextStep;
9201 if (NextStep != StepEnd &&
9202 (NextStep->Kind == SK_ConstructorInitialization ||
9203 NextStep->Kind == SK_ConstructorInitializationFromList)) {
9204 // The need for zero-initialization is recorded directly into
9205 // the call to the object's constructor within the next step.
9206 ConstructorInitRequiresZeroInit = true;
9207 } else if (Kind.getKind() == InitializationKind::IK_Value &&
9208 S.getLangOpts().CPlusPlus &&
9209 !Kind.isImplicitValueInit()) {
9210 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9211 if (!TSInfo)
9212 TSInfo = S.Context.getTrivialTypeSourceInfo(T: Step->Type,
9213 Loc: Kind.getRange().getBegin());
9214
9215 CurInit = new (S.Context) CXXScalarValueInitExpr(
9216 Entity.getType().getNonLValueExprType(Context: S.Context), TSInfo,
9217 Kind.getRange().getEnd());
9218 } else {
9219 CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9220 }
9221 break;
9222 }
9223
9224 case SK_CAssignment: {
9225 QualType SourceType = CurInit.get()->getType();
9226
9227 // Save off the initial CurInit in case we need to emit a diagnostic
9228 ExprResult InitialCurInit = CurInit;
9229 ExprResult Result = CurInit;
9230 Sema::AssignConvertType ConvTy =
9231 S.CheckSingleAssignmentConstraints(LHSType: Step->Type, RHS&: Result, Diagnose: true,
9232 DiagnoseCFAudited: Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
9233 if (Result.isInvalid())
9234 return ExprError();
9235 CurInit = Result;
9236
9237 // If this is a call, allow conversion to a transparent union.
9238 ExprResult CurInitExprRes = CurInit;
9239 if (ConvTy != Sema::Compatible &&
9240 Entity.isParameterKind() &&
9241 S.CheckTransparentUnionArgumentConstraints(ArgType: Step->Type, RHS&: CurInitExprRes)
9242 == Sema::Compatible)
9243 ConvTy = Sema::Compatible;
9244 if (CurInitExprRes.isInvalid())
9245 return ExprError();
9246 CurInit = CurInitExprRes;
9247
9248 if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) {
9249 CheckC23ConstexprInitConversion(S, FromType: SourceType, ToType: Entity.getType(),
9250 Init: CurInit.get());
9251
9252 // C23 6.7.1p6: If an object or subobject declared with storage-class
9253 // specifier constexpr has pointer, integer, or arithmetic type, any
9254 // explicit initializer value for it shall be null, an integer
9255 // constant expression, or an arithmetic constant expression,
9256 // respectively.
9257 Expr::EvalResult ER;
9258 if (Entity.getType()->getAs<PointerType>() &&
9259 CurInit.get()->EvaluateAsRValue(Result&: ER, Ctx: S.Context) &&
9260 !ER.Val.isNullPointer()) {
9261 S.Diag(Kind.getLocation(), diag::err_c23_constexpr_pointer_not_null);
9262 }
9263 }
9264
9265 bool Complained;
9266 if (S.DiagnoseAssignmentResult(ConvTy, Loc: Kind.getLocation(),
9267 DstType: Step->Type, SrcType: SourceType,
9268 SrcExpr: InitialCurInit.get(),
9269 Action: getAssignmentAction(Entity, Diagnose: true),
9270 Complained: &Complained)) {
9271 PrintInitLocationNote(S, Entity);
9272 return ExprError();
9273 } else if (Complained)
9274 PrintInitLocationNote(S, Entity);
9275 break;
9276 }
9277
9278 case SK_StringInit: {
9279 QualType Ty = Step->Type;
9280 bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9281 CheckStringInit(Str: CurInit.get(), DeclT&: UpdateType ? *ResultType : Ty,
9282 AT: S.Context.getAsArrayType(T: Ty), S,
9283 CheckC23ConstexprInit: S.getLangOpts().C23 &&
9284 initializingConstexprVariable(Entity));
9285 break;
9286 }
9287
9288 case SK_ObjCObjectConversion:
9289 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
9290 CK: CK_ObjCObjectLValueCast,
9291 VK: CurInit.get()->getValueKind());
9292 break;
9293
9294 case SK_ArrayLoopIndex: {
9295 Expr *Cur = CurInit.get();
9296 Expr *BaseExpr = new (S.Context)
9297 OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9298 Cur->getValueKind(), Cur->getObjectKind(), Cur);
9299 Expr *IndexExpr =
9300 new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
9301 CurInit = S.CreateBuiltinArraySubscriptExpr(
9302 Base: BaseExpr, LLoc: Kind.getLocation(), Idx: IndexExpr, RLoc: Kind.getLocation());
9303 ArrayLoopCommonExprs.push_back(Elt: BaseExpr);
9304 break;
9305 }
9306
9307 case SK_ArrayLoopInit: {
9308 assert(!ArrayLoopCommonExprs.empty() &&
9309 "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9310 Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9311 CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9312 CurInit.get());
9313 break;
9314 }
9315
9316 case SK_GNUArrayInit:
9317 // Okay: we checked everything before creating this step. Note that
9318 // this is a GNU extension.
9319 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9320 << Step->Type << CurInit.get()->getType()
9321 << CurInit.get()->getSourceRange();
9322 updateGNUCompoundLiteralRValue(E: CurInit.get());
9323 [[fallthrough]];
9324 case SK_ArrayInit:
9325 // If the destination type is an incomplete array type, update the
9326 // type accordingly.
9327 if (ResultType) {
9328 if (const IncompleteArrayType *IncompleteDest
9329 = S.Context.getAsIncompleteArrayType(T: Step->Type)) {
9330 if (const ConstantArrayType *ConstantSource
9331 = S.Context.getAsConstantArrayType(T: CurInit.get()->getType())) {
9332 *ResultType = S.Context.getConstantArrayType(
9333 EltTy: IncompleteDest->getElementType(), ArySize: ConstantSource->getSize(),
9334 SizeExpr: ConstantSource->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
9335 }
9336 }
9337 }
9338 break;
9339
9340 case SK_ParenthesizedArrayInit:
9341 // Okay: we checked everything before creating this step. Note that
9342 // this is a GNU extension.
9343 S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9344 << CurInit.get()->getSourceRange();
9345 break;
9346
9347 case SK_PassByIndirectCopyRestore:
9348 case SK_PassByIndirectRestore:
9349 checkIndirectCopyRestoreSource(S, src: CurInit.get());
9350 CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9351 CurInit.get(), Step->Type,
9352 Step->Kind == SK_PassByIndirectCopyRestore);
9353 break;
9354
9355 case SK_ProduceObjCObject:
9356 CurInit = ImplicitCastExpr::Create(
9357 Context: S.Context, T: Step->Type, Kind: CK_ARCProduceObject, Operand: CurInit.get(), BasePath: nullptr,
9358 Cat: VK_PRValue, FPO: FPOptionsOverride());
9359 break;
9360
9361 case SK_StdInitializerList: {
9362 S.Diag(CurInit.get()->getExprLoc(),
9363 diag::warn_cxx98_compat_initializer_list_init)
9364 << CurInit.get()->getSourceRange();
9365
9366 // Materialize the temporary into memory.
9367 MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
9368 T: CurInit.get()->getType(), Temporary: CurInit.get(),
9369 /*BoundToLvalueReference=*/false);
9370
9371 // Wrap it in a construction of a std::initializer_list<T>.
9372 CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9373
9374 // Bind the result, in case the library has given initializer_list a
9375 // non-trivial destructor.
9376 if (shouldBindAsTemporary(Entity))
9377 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
9378 break;
9379 }
9380
9381 case SK_OCLSamplerInit: {
9382 // Sampler initialization have 5 cases:
9383 // 1. function argument passing
9384 // 1a. argument is a file-scope variable
9385 // 1b. argument is a function-scope variable
9386 // 1c. argument is one of caller function's parameters
9387 // 2. variable initialization
9388 // 2a. initializing a file-scope variable
9389 // 2b. initializing a function-scope variable
9390 //
9391 // For file-scope variables, since they cannot be initialized by function
9392 // call of __translate_sampler_initializer in LLVM IR, their references
9393 // need to be replaced by a cast from their literal initializers to
9394 // sampler type. Since sampler variables can only be used in function
9395 // calls as arguments, we only need to replace them when handling the
9396 // argument passing.
9397 assert(Step->Type->isSamplerT() &&
9398 "Sampler initialization on non-sampler type.");
9399 Expr *Init = CurInit.get()->IgnoreParens();
9400 QualType SourceType = Init->getType();
9401 // Case 1
9402 if (Entity.isParameterKind()) {
9403 if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9404 S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9405 << SourceType;
9406 break;
9407 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Init)) {
9408 auto Var = cast<VarDecl>(Val: DRE->getDecl());
9409 // Case 1b and 1c
9410 // No cast from integer to sampler is needed.
9411 if (!Var->hasGlobalStorage()) {
9412 CurInit = ImplicitCastExpr::Create(
9413 Context: S.Context, T: Step->Type, Kind: CK_LValueToRValue, Operand: Init,
9414 /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
9415 break;
9416 }
9417 // Case 1a
9418 // For function call with a file-scope sampler variable as argument,
9419 // get the integer literal.
9420 // Do not diagnose if the file-scope variable does not have initializer
9421 // since this has already been diagnosed when parsing the variable
9422 // declaration.
9423 if (!Var->getInit() || !isa<ImplicitCastExpr>(Val: Var->getInit()))
9424 break;
9425 Init = cast<ImplicitCastExpr>(Val: const_cast<Expr*>(
9426 Var->getInit()))->getSubExpr();
9427 SourceType = Init->getType();
9428 }
9429 } else {
9430 // Case 2
9431 // Check initializer is 32 bit integer constant.
9432 // If the initializer is taken from global variable, do not diagnose since
9433 // this has already been done when parsing the variable declaration.
9434 if (!Init->isConstantInitializer(Ctx&: S.Context, ForRef: false))
9435 break;
9436
9437 if (!SourceType->isIntegerType() ||
9438 32 != S.Context.getIntWidth(T: SourceType)) {
9439 S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9440 << SourceType;
9441 break;
9442 }
9443
9444 Expr::EvalResult EVResult;
9445 Init->EvaluateAsInt(Result&: EVResult, Ctx: S.Context);
9446 llvm::APSInt Result = EVResult.Val.getInt();
9447 const uint64_t SamplerValue = Result.getLimitedValue();
9448 // 32-bit value of sampler's initializer is interpreted as
9449 // bit-field with the following structure:
9450 // |unspecified|Filter|Addressing Mode| Normalized Coords|
9451 // |31 6|5 4|3 1| 0|
9452 // This structure corresponds to enum values of sampler properties
9453 // defined in SPIR spec v1.2 and also opencl-c.h
9454 unsigned AddressingMode = (0x0E & SamplerValue) >> 1;
9455 unsigned FilterMode = (0x30 & SamplerValue) >> 4;
9456 if (FilterMode != 1 && FilterMode != 2 &&
9457 !S.getOpenCLOptions().isAvailableOption(
9458 "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9459 S.Diag(Kind.getLocation(),
9460 diag::warn_sampler_initializer_invalid_bits)
9461 << "Filter Mode";
9462 if (AddressingMode > 4)
9463 S.Diag(Kind.getLocation(),
9464 diag::warn_sampler_initializer_invalid_bits)
9465 << "Addressing Mode";
9466 }
9467
9468 // Cases 1a, 2a and 2b
9469 // Insert cast from integer to sampler.
9470 CurInit = S.ImpCastExprToType(E: Init, Type: S.Context.OCLSamplerTy,
9471 CK: CK_IntToOCLSampler);
9472 break;
9473 }
9474 case SK_OCLZeroOpaqueType: {
9475 assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9476 Step->Type->isOCLIntelSubgroupAVCType()) &&
9477 "Wrong type for initialization of OpenCL opaque type.");
9478
9479 CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type,
9480 CK: CK_ZeroToOCLOpaqueType,
9481 VK: CurInit.get()->getValueKind());
9482 break;
9483 }
9484 case SK_ParenthesizedListInit: {
9485 CurInit = nullptr;
9486 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
9487 /*VerifyOnly=*/false, Result: &CurInit);
9488 if (CurInit.get() && ResultType)
9489 *ResultType = CurInit.get()->getType();
9490 if (shouldBindAsTemporary(Entity))
9491 CurInit = S.MaybeBindToTemporary(E: CurInit.get());
9492 break;
9493 }
9494 }
9495 }
9496
9497 Expr *Init = CurInit.get();
9498 if (!Init)
9499 return ExprError();
9500
9501 // Check whether the initializer has a shorter lifetime than the initialized
9502 // entity, and if not, either lifetime-extend or warn as appropriate.
9503 S.checkInitializerLifetime(Entity, Init);
9504
9505 // Diagnose non-fatal problems with the completed initialization.
9506 if (InitializedEntity::EntityKind EK = Entity.getKind();
9507 (EK == InitializedEntity::EK_Member ||
9508 EK == InitializedEntity::EK_ParenAggInitMember) &&
9509 cast<FieldDecl>(Val: Entity.getDecl())->isBitField())
9510 S.CheckBitFieldInitialization(InitLoc: Kind.getLocation(),
9511 Field: cast<FieldDecl>(Val: Entity.getDecl()), Init);
9512
9513 // Check for std::move on construction.
9514 CheckMoveOnConstruction(S, InitExpr: Init,
9515 IsReturnStmt: Entity.getKind() == InitializedEntity::EK_Result);
9516
9517 return Init;
9518}
9519
9520/// Somewhere within T there is an uninitialized reference subobject.
9521/// Dig it out and diagnose it.
9522static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
9523 QualType T) {
9524 if (T->isReferenceType()) {
9525 S.Diag(Loc, diag::err_reference_without_init)
9526 << T.getNonReferenceType();
9527 return true;
9528 }
9529
9530 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
9531 if (!RD || !RD->hasUninitializedReferenceMember())
9532 return false;
9533
9534 for (const auto *FI : RD->fields()) {
9535 if (FI->isUnnamedBitField())
9536 continue;
9537
9538 if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9539 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9540 return true;
9541 }
9542 }
9543
9544 for (const auto &BI : RD->bases()) {
9545 if (DiagnoseUninitializedReference(S, Loc: BI.getBeginLoc(), T: BI.getType())) {
9546 S.Diag(Loc, diag::note_value_initialization_here) << RD;
9547 return true;
9548 }
9549 }
9550
9551 return false;
9552}
9553
9554
9555//===----------------------------------------------------------------------===//
9556// Diagnose initialization failures
9557//===----------------------------------------------------------------------===//
9558
9559/// Emit notes associated with an initialization that failed due to a
9560/// "simple" conversion failure.
9561static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9562 Expr *op) {
9563 QualType destType = entity.getType();
9564 if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9565 op->getType()->isObjCObjectPointerType()) {
9566
9567 // Emit a possible note about the conversion failing because the
9568 // operand is a message send with a related result type.
9569 S.EmitRelatedResultTypeNote(E: op);
9570
9571 // Emit a possible note about a return failing because we're
9572 // expecting a related result type.
9573 if (entity.getKind() == InitializedEntity::EK_Result)
9574 S.EmitRelatedResultTypeNoteForReturn(destType);
9575 }
9576 QualType fromType = op->getType();
9577 QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9578 QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9579 auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9580 auto *destDecl = destType->getPointeeCXXRecordDecl();
9581 if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9582 destDecl->getDeclKind() == Decl::CXXRecord &&
9583 !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9584 !fromDecl->hasDefinition() &&
9585 destPointeeType.getQualifiers().compatiblyIncludes(
9586 fromPointeeType.getQualifiers()))
9587 S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9588 << S.getASTContext().getTagDeclType(fromDecl)
9589 << S.getASTContext().getTagDeclType(destDecl);
9590}
9591
9592static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9593 InitListExpr *InitList) {
9594 QualType DestType = Entity.getType();
9595
9596 QualType E;
9597 if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(Ty: DestType, Element: &E)) {
9598 QualType ArrayType = S.Context.getConstantArrayType(
9599 EltTy: E.withConst(),
9600 ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()),
9601 InitList->getNumInits()),
9602 SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0);
9603 InitializedEntity HiddenArray =
9604 InitializedEntity::InitializeTemporary(Type: ArrayType);
9605 return diagnoseListInit(S, Entity: HiddenArray, InitList);
9606 }
9607
9608 if (DestType->isReferenceType()) {
9609 // A list-initialization failure for a reference means that we tried to
9610 // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9611 // inner initialization failed.
9612 QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9613 diagnoseListInit(S, Entity: InitializedEntity::InitializeTemporary(Type: T), InitList);
9614 SourceLocation Loc = InitList->getBeginLoc();
9615 if (auto *D = Entity.getDecl())
9616 Loc = D->getLocation();
9617 S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9618 return;
9619 }
9620
9621 InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9622 /*VerifyOnly=*/false,
9623 /*TreatUnavailableAsInvalid=*/false);
9624 assert(DiagnoseInitList.HadError() &&
9625 "Inconsistent init list check result.");
9626}
9627
9628bool InitializationSequence::Diagnose(Sema &S,
9629 const InitializedEntity &Entity,
9630 const InitializationKind &Kind,
9631 ArrayRef<Expr *> Args) {
9632 if (!Failed())
9633 return false;
9634
9635 // When we want to diagnose only one element of a braced-init-list,
9636 // we need to factor it out.
9637 Expr *OnlyArg;
9638 if (Args.size() == 1) {
9639 auto *List = dyn_cast<InitListExpr>(Val: Args[0]);
9640 if (List && List->getNumInits() == 1)
9641 OnlyArg = List->getInit(Init: 0);
9642 else
9643 OnlyArg = Args[0];
9644 }
9645 else
9646 OnlyArg = nullptr;
9647
9648 QualType DestType = Entity.getType();
9649 switch (Failure) {
9650 case FK_TooManyInitsForReference:
9651 // FIXME: Customize for the initialized entity?
9652 if (Args.empty()) {
9653 // Dig out the reference subobject which is uninitialized and diagnose it.
9654 // If this is value-initialization, this could be nested some way within
9655 // the target type.
9656 assert(Kind.getKind() == InitializationKind::IK_Value ||
9657 DestType->isReferenceType());
9658 bool Diagnosed =
9659 DiagnoseUninitializedReference(S, Loc: Kind.getLocation(), T: DestType);
9660 assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9661 (void)Diagnosed;
9662 } else // FIXME: diagnostic below could be better!
9663 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9664 << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9665 break;
9666 case FK_ParenthesizedListInitForReference:
9667 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9668 << 1 << Entity.getType() << Args[0]->getSourceRange();
9669 break;
9670
9671 case FK_ArrayNeedsInitList:
9672 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9673 break;
9674 case FK_ArrayNeedsInitListOrStringLiteral:
9675 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9676 break;
9677 case FK_ArrayNeedsInitListOrWideStringLiteral:
9678 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9679 break;
9680 case FK_NarrowStringIntoWideCharArray:
9681 S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9682 break;
9683 case FK_WideStringIntoCharArray:
9684 S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9685 break;
9686 case FK_IncompatWideStringIntoWideChar:
9687 S.Diag(Kind.getLocation(),
9688 diag::err_array_init_incompat_wide_string_into_wchar);
9689 break;
9690 case FK_PlainStringIntoUTF8Char:
9691 S.Diag(Kind.getLocation(),
9692 diag::err_array_init_plain_string_into_char8_t);
9693 S.Diag(Args.front()->getBeginLoc(),
9694 diag::note_array_init_plain_string_into_char8_t)
9695 << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9696 break;
9697 case FK_UTF8StringIntoPlainChar:
9698 S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9699 << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9700 break;
9701 case FK_ArrayTypeMismatch:
9702 case FK_NonConstantArrayInit:
9703 S.Diag(Kind.getLocation(),
9704 (Failure == FK_ArrayTypeMismatch
9705 ? diag::err_array_init_different_type
9706 : diag::err_array_init_non_constant_array))
9707 << DestType.getNonReferenceType()
9708 << OnlyArg->getType()
9709 << Args[0]->getSourceRange();
9710 break;
9711
9712 case FK_VariableLengthArrayHasInitializer:
9713 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9714 << Args[0]->getSourceRange();
9715 break;
9716
9717 case FK_AddressOfOverloadFailed: {
9718 DeclAccessPair Found;
9719 S.ResolveAddressOfOverloadedFunction(AddressOfExpr: OnlyArg,
9720 TargetType: DestType.getNonReferenceType(),
9721 Complain: true,
9722 Found);
9723 break;
9724 }
9725
9726 case FK_AddressOfUnaddressableFunction: {
9727 auto *FD = cast<FunctionDecl>(Val: cast<DeclRefExpr>(Val: OnlyArg)->getDecl());
9728 S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
9729 Loc: OnlyArg->getBeginLoc());
9730 break;
9731 }
9732
9733 case FK_ReferenceInitOverloadFailed:
9734 case FK_UserConversionOverloadFailed:
9735 switch (FailedOverloadResult) {
9736 case OR_Ambiguous:
9737
9738 FailedCandidateSet.NoteCandidates(
9739 PartialDiagnosticAt(
9740 Kind.getLocation(),
9741 Failure == FK_UserConversionOverloadFailed
9742 ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9743 << OnlyArg->getType() << DestType
9744 << Args[0]->getSourceRange())
9745 : (S.PDiag(diag::err_ref_init_ambiguous)
9746 << DestType << OnlyArg->getType()
9747 << Args[0]->getSourceRange())),
9748 S, OCD_AmbiguousCandidates, Args);
9749 break;
9750
9751 case OR_No_Viable_Function: {
9752 auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args);
9753 if (!S.RequireCompleteType(Kind.getLocation(),
9754 DestType.getNonReferenceType(),
9755 diag::err_typecheck_nonviable_condition_incomplete,
9756 OnlyArg->getType(), Args[0]->getSourceRange()))
9757 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9758 << (Entity.getKind() == InitializedEntity::EK_Result)
9759 << OnlyArg->getType() << Args[0]->getSourceRange()
9760 << DestType.getNonReferenceType();
9761
9762 FailedCandidateSet.NoteCandidates(S, Args, Cands);
9763 break;
9764 }
9765 case OR_Deleted: {
9766 OverloadCandidateSet::iterator Best;
9767 OverloadingResult Ovl
9768 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
9769
9770 StringLiteral *Msg = Best->Function->getDeletedMessage();
9771 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9772 << OnlyArg->getType() << DestType.getNonReferenceType()
9773 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
9774 << Args[0]->getSourceRange();
9775 if (Ovl == OR_Deleted) {
9776 S.NoteDeletedFunction(FD: Best->Function);
9777 } else {
9778 llvm_unreachable("Inconsistent overload resolution?");
9779 }
9780 break;
9781 }
9782
9783 case OR_Success:
9784 llvm_unreachable("Conversion did not fail!");
9785 }
9786 break;
9787
9788 case FK_NonConstLValueReferenceBindingToTemporary:
9789 if (isa<InitListExpr>(Val: Args[0])) {
9790 S.Diag(Kind.getLocation(),
9791 diag::err_lvalue_reference_bind_to_initlist)
9792 << DestType.getNonReferenceType().isVolatileQualified()
9793 << DestType.getNonReferenceType()
9794 << Args[0]->getSourceRange();
9795 break;
9796 }
9797 [[fallthrough]];
9798
9799 case FK_NonConstLValueReferenceBindingToUnrelated:
9800 S.Diag(Kind.getLocation(),
9801 Failure == FK_NonConstLValueReferenceBindingToTemporary
9802 ? diag::err_lvalue_reference_bind_to_temporary
9803 : diag::err_lvalue_reference_bind_to_unrelated)
9804 << DestType.getNonReferenceType().isVolatileQualified()
9805 << DestType.getNonReferenceType()
9806 << OnlyArg->getType()
9807 << Args[0]->getSourceRange();
9808 break;
9809
9810 case FK_NonConstLValueReferenceBindingToBitfield: {
9811 // We don't necessarily have an unambiguous source bit-field.
9812 FieldDecl *BitField = Args[0]->getSourceBitField();
9813 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9814 << DestType.isVolatileQualified()
9815 << (BitField ? BitField->getDeclName() : DeclarationName())
9816 << (BitField != nullptr)
9817 << Args[0]->getSourceRange();
9818 if (BitField)
9819 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9820 break;
9821 }
9822
9823 case FK_NonConstLValueReferenceBindingToVectorElement:
9824 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9825 << DestType.isVolatileQualified()
9826 << Args[0]->getSourceRange();
9827 break;
9828
9829 case FK_NonConstLValueReferenceBindingToMatrixElement:
9830 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9831 << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9832 break;
9833
9834 case FK_RValueReferenceBindingToLValue:
9835 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9836 << DestType.getNonReferenceType() << OnlyArg->getType()
9837 << Args[0]->getSourceRange();
9838 break;
9839
9840 case FK_ReferenceAddrspaceMismatchTemporary:
9841 S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9842 << DestType << Args[0]->getSourceRange();
9843 break;
9844
9845 case FK_ReferenceInitDropsQualifiers: {
9846 QualType SourceType = OnlyArg->getType();
9847 QualType NonRefType = DestType.getNonReferenceType();
9848 Qualifiers DroppedQualifiers =
9849 SourceType.getQualifiers() - NonRefType.getQualifiers();
9850
9851 if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9852 SourceType.getQualifiers()))
9853 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9854 << NonRefType << SourceType << 1 /*addr space*/
9855 << Args[0]->getSourceRange();
9856 else if (DroppedQualifiers.hasQualifiers())
9857 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9858 << NonRefType << SourceType << 0 /*cv quals*/
9859 << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9860 << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9861 else
9862 // FIXME: Consider decomposing the type and explaining which qualifiers
9863 // were dropped where, or on which level a 'const' is missing, etc.
9864 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9865 << NonRefType << SourceType << 2 /*incompatible quals*/
9866 << Args[0]->getSourceRange();
9867 break;
9868 }
9869
9870 case FK_ReferenceInitFailed:
9871 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9872 << DestType.getNonReferenceType()
9873 << DestType.getNonReferenceType()->isIncompleteType()
9874 << OnlyArg->isLValue()
9875 << OnlyArg->getType()
9876 << Args[0]->getSourceRange();
9877 emitBadConversionNotes(S, entity: Entity, op: Args[0]);
9878 break;
9879
9880 case FK_ConversionFailed: {
9881 QualType FromType = OnlyArg->getType();
9882 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9883 << (int)Entity.getKind()
9884 << DestType
9885 << OnlyArg->isLValue()
9886 << FromType
9887 << Args[0]->getSourceRange();
9888 S.HandleFunctionTypeMismatch(PDiag, FromType, ToType: DestType);
9889 S.Diag(Kind.getLocation(), PDiag);
9890 emitBadConversionNotes(S, entity: Entity, op: Args[0]);
9891 break;
9892 }
9893
9894 case FK_ConversionFromPropertyFailed:
9895 // No-op. This error has already been reported.
9896 break;
9897
9898 case FK_TooManyInitsForScalar: {
9899 SourceRange R;
9900
9901 auto *InitList = dyn_cast<InitListExpr>(Val: Args[0]);
9902 if (InitList && InitList->getNumInits() >= 1) {
9903 R = SourceRange(InitList->getInit(Init: 0)->getEndLoc(), InitList->getEndLoc());
9904 } else {
9905 assert(Args.size() > 1 && "Expected multiple initializers!");
9906 R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9907 }
9908
9909 R.setBegin(S.getLocForEndOfToken(Loc: R.getBegin()));
9910 if (Kind.isCStyleOrFunctionalCast())
9911 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9912 << R;
9913 else
9914 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9915 << /*scalar=*/2 << R;
9916 break;
9917 }
9918
9919 case FK_ParenthesizedListInitForScalar:
9920 S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9921 << 0 << Entity.getType() << Args[0]->getSourceRange();
9922 break;
9923
9924 case FK_ReferenceBindingToInitList:
9925 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9926 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9927 break;
9928
9929 case FK_InitListBadDestinationType:
9930 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9931 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9932 break;
9933
9934 case FK_ListConstructorOverloadFailed:
9935 case FK_ConstructorOverloadFailed: {
9936 SourceRange ArgsRange;
9937 if (Args.size())
9938 ArgsRange =
9939 SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9940
9941 if (Failure == FK_ListConstructorOverloadFailed) {
9942 assert(Args.size() == 1 &&
9943 "List construction from other than 1 argument.");
9944 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
9945 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9946 }
9947
9948 // FIXME: Using "DestType" for the entity we're printing is probably
9949 // bad.
9950 switch (FailedOverloadResult) {
9951 case OR_Ambiguous:
9952 FailedCandidateSet.NoteCandidates(
9953 PartialDiagnosticAt(Kind.getLocation(),
9954 S.PDiag(diag::err_ovl_ambiguous_init)
9955 << DestType << ArgsRange),
9956 S, OCD_AmbiguousCandidates, Args);
9957 break;
9958
9959 case OR_No_Viable_Function:
9960 if (Kind.getKind() == InitializationKind::IK_Default &&
9961 (Entity.getKind() == InitializedEntity::EK_Base ||
9962 Entity.getKind() == InitializedEntity::EK_Member ||
9963 Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9964 isa<CXXConstructorDecl>(Val: S.CurContext)) {
9965 // This is implicit default initialization of a member or
9966 // base within a constructor. If no viable function was
9967 // found, notify the user that they need to explicitly
9968 // initialize this base/member.
9969 CXXConstructorDecl *Constructor
9970 = cast<CXXConstructorDecl>(Val: S.CurContext);
9971 const CXXRecordDecl *InheritedFrom = nullptr;
9972 if (auto Inherited = Constructor->getInheritedConstructor())
9973 InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9974 if (Entity.getKind() == InitializedEntity::EK_Base) {
9975 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9976 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9977 << S.Context.getTypeDeclType(Constructor->getParent())
9978 << /*base=*/0
9979 << Entity.getType()
9980 << InheritedFrom;
9981
9982 RecordDecl *BaseDecl
9983 = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9984 ->getDecl();
9985 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9986 << S.Context.getTagDeclType(BaseDecl);
9987 } else {
9988 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9989 << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9990 << S.Context.getTypeDeclType(Constructor->getParent())
9991 << /*member=*/1
9992 << Entity.getName()
9993 << InheritedFrom;
9994 S.Diag(Entity.getDecl()->getLocation(),
9995 diag::note_member_declared_at);
9996
9997 if (const RecordType *Record
9998 = Entity.getType()->getAs<RecordType>())
9999 S.Diag(Record->getDecl()->getLocation(),
10000 diag::note_previous_decl)
10001 << S.Context.getTagDeclType(Record->getDecl());
10002 }
10003 break;
10004 }
10005
10006 FailedCandidateSet.NoteCandidates(
10007 PartialDiagnosticAt(
10008 Kind.getLocation(),
10009 S.PDiag(diag::err_ovl_no_viable_function_in_init)
10010 << DestType << ArgsRange),
10011 S, OCD_AllCandidates, Args);
10012 break;
10013
10014 case OR_Deleted: {
10015 OverloadCandidateSet::iterator Best;
10016 OverloadingResult Ovl
10017 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
10018 if (Ovl != OR_Deleted) {
10019 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10020 << DestType << ArgsRange;
10021 llvm_unreachable("Inconsistent overload resolution?");
10022 break;
10023 }
10024
10025 // If this is a defaulted or implicitly-declared function, then
10026 // it was implicitly deleted. Make it clear that the deletion was
10027 // implicit.
10028 if (S.isImplicitlyDeleted(FD: Best->Function))
10029 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
10030 << llvm::to_underlying(
10031 S.getSpecialMember(cast<CXXMethodDecl>(Best->Function)))
10032 << DestType << ArgsRange;
10033 else {
10034 StringLiteral *Msg = Best->Function->getDeletedMessage();
10035 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
10036 << DestType << (Msg != nullptr)
10037 << (Msg ? Msg->getString() : StringRef()) << ArgsRange;
10038 }
10039
10040 S.NoteDeletedFunction(FD: Best->Function);
10041 break;
10042 }
10043
10044 case OR_Success:
10045 llvm_unreachable("Conversion did not fail!");
10046 }
10047 }
10048 break;
10049
10050 case FK_DefaultInitOfConst:
10051 if (Entity.getKind() == InitializedEntity::EK_Member &&
10052 isa<CXXConstructorDecl>(Val: S.CurContext)) {
10053 // This is implicit default-initialization of a const member in
10054 // a constructor. Complain that it needs to be explicitly
10055 // initialized.
10056 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: S.CurContext);
10057 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
10058 << (Constructor->getInheritedConstructor() ? 2 :
10059 Constructor->isImplicit() ? 1 : 0)
10060 << S.Context.getTypeDeclType(Constructor->getParent())
10061 << /*const=*/1
10062 << Entity.getName();
10063 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
10064 << Entity.getName();
10065 } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: Entity.getDecl());
10066 VD && VD->isConstexpr()) {
10067 S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
10068 << VD;
10069 } else {
10070 S.Diag(Kind.getLocation(), diag::err_default_init_const)
10071 << DestType << (bool)DestType->getAs<RecordType>();
10072 }
10073 break;
10074
10075 case FK_Incomplete:
10076 S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
10077 diag::err_init_incomplete_type);
10078 break;
10079
10080 case FK_ListInitializationFailed: {
10081 // Run the init list checker again to emit diagnostics.
10082 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
10083 diagnoseListInit(S, Entity, InitList);
10084 break;
10085 }
10086
10087 case FK_PlaceholderType: {
10088 // FIXME: Already diagnosed!
10089 break;
10090 }
10091
10092 case FK_ExplicitConstructor: {
10093 S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
10094 << Args[0]->getSourceRange();
10095 OverloadCandidateSet::iterator Best;
10096 OverloadingResult Ovl
10097 = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best);
10098 (void)Ovl;
10099 assert(Ovl == OR_Success && "Inconsistent overload resolution");
10100 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function);
10101 S.Diag(CtorDecl->getLocation(),
10102 diag::note_explicit_ctor_deduction_guide_here) << false;
10103 break;
10104 }
10105
10106 case FK_ParenthesizedListInitFailed:
10107 TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this,
10108 /*VerifyOnly=*/false);
10109 break;
10110
10111 case FK_DesignatedInitForNonAggregate:
10112 InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]);
10113 S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10114 << Entity.getType() << InitList->getSourceRange();
10115 break;
10116 }
10117
10118 PrintInitLocationNote(S, Entity);
10119 return true;
10120}
10121
10122void InitializationSequence::dump(raw_ostream &OS) const {
10123 switch (SequenceKind) {
10124 case FailedSequence: {
10125 OS << "Failed sequence: ";
10126 switch (Failure) {
10127 case FK_TooManyInitsForReference:
10128 OS << "too many initializers for reference";
10129 break;
10130
10131 case FK_ParenthesizedListInitForReference:
10132 OS << "parenthesized list init for reference";
10133 break;
10134
10135 case FK_ArrayNeedsInitList:
10136 OS << "array requires initializer list";
10137 break;
10138
10139 case FK_AddressOfUnaddressableFunction:
10140 OS << "address of unaddressable function was taken";
10141 break;
10142
10143 case FK_ArrayNeedsInitListOrStringLiteral:
10144 OS << "array requires initializer list or string literal";
10145 break;
10146
10147 case FK_ArrayNeedsInitListOrWideStringLiteral:
10148 OS << "array requires initializer list or wide string literal";
10149 break;
10150
10151 case FK_NarrowStringIntoWideCharArray:
10152 OS << "narrow string into wide char array";
10153 break;
10154
10155 case FK_WideStringIntoCharArray:
10156 OS << "wide string into char array";
10157 break;
10158
10159 case FK_IncompatWideStringIntoWideChar:
10160 OS << "incompatible wide string into wide char array";
10161 break;
10162
10163 case FK_PlainStringIntoUTF8Char:
10164 OS << "plain string literal into char8_t array";
10165 break;
10166
10167 case FK_UTF8StringIntoPlainChar:
10168 OS << "u8 string literal into char array";
10169 break;
10170
10171 case FK_ArrayTypeMismatch:
10172 OS << "array type mismatch";
10173 break;
10174
10175 case FK_NonConstantArrayInit:
10176 OS << "non-constant array initializer";
10177 break;
10178
10179 case FK_AddressOfOverloadFailed:
10180 OS << "address of overloaded function failed";
10181 break;
10182
10183 case FK_ReferenceInitOverloadFailed:
10184 OS << "overload resolution for reference initialization failed";
10185 break;
10186
10187 case FK_NonConstLValueReferenceBindingToTemporary:
10188 OS << "non-const lvalue reference bound to temporary";
10189 break;
10190
10191 case FK_NonConstLValueReferenceBindingToBitfield:
10192 OS << "non-const lvalue reference bound to bit-field";
10193 break;
10194
10195 case FK_NonConstLValueReferenceBindingToVectorElement:
10196 OS << "non-const lvalue reference bound to vector element";
10197 break;
10198
10199 case FK_NonConstLValueReferenceBindingToMatrixElement:
10200 OS << "non-const lvalue reference bound to matrix element";
10201 break;
10202
10203 case FK_NonConstLValueReferenceBindingToUnrelated:
10204 OS << "non-const lvalue reference bound to unrelated type";
10205 break;
10206
10207 case FK_RValueReferenceBindingToLValue:
10208 OS << "rvalue reference bound to an lvalue";
10209 break;
10210
10211 case FK_ReferenceInitDropsQualifiers:
10212 OS << "reference initialization drops qualifiers";
10213 break;
10214
10215 case FK_ReferenceAddrspaceMismatchTemporary:
10216 OS << "reference with mismatching address space bound to temporary";
10217 break;
10218
10219 case FK_ReferenceInitFailed:
10220 OS << "reference initialization failed";
10221 break;
10222
10223 case FK_ConversionFailed:
10224 OS << "conversion failed";
10225 break;
10226
10227 case FK_ConversionFromPropertyFailed:
10228 OS << "conversion from property failed";
10229 break;
10230
10231 case FK_TooManyInitsForScalar:
10232 OS << "too many initializers for scalar";
10233 break;
10234
10235 case FK_ParenthesizedListInitForScalar:
10236 OS << "parenthesized list init for reference";
10237 break;
10238
10239 case FK_ReferenceBindingToInitList:
10240 OS << "referencing binding to initializer list";
10241 break;
10242
10243 case FK_InitListBadDestinationType:
10244 OS << "initializer list for non-aggregate, non-scalar type";
10245 break;
10246
10247 case FK_UserConversionOverloadFailed:
10248 OS << "overloading failed for user-defined conversion";
10249 break;
10250
10251 case FK_ConstructorOverloadFailed:
10252 OS << "constructor overloading failed";
10253 break;
10254
10255 case FK_DefaultInitOfConst:
10256 OS << "default initialization of a const variable";
10257 break;
10258
10259 case FK_Incomplete:
10260 OS << "initialization of incomplete type";
10261 break;
10262
10263 case FK_ListInitializationFailed:
10264 OS << "list initialization checker failure";
10265 break;
10266
10267 case FK_VariableLengthArrayHasInitializer:
10268 OS << "variable length array has an initializer";
10269 break;
10270
10271 case FK_PlaceholderType:
10272 OS << "initializer expression isn't contextually valid";
10273 break;
10274
10275 case FK_ListConstructorOverloadFailed:
10276 OS << "list constructor overloading failed";
10277 break;
10278
10279 case FK_ExplicitConstructor:
10280 OS << "list copy initialization chose explicit constructor";
10281 break;
10282
10283 case FK_ParenthesizedListInitFailed:
10284 OS << "parenthesized list initialization failed";
10285 break;
10286
10287 case FK_DesignatedInitForNonAggregate:
10288 OS << "designated initializer for non-aggregate type";
10289 break;
10290 }
10291 OS << '\n';
10292 return;
10293 }
10294
10295 case DependentSequence:
10296 OS << "Dependent sequence\n";
10297 return;
10298
10299 case NormalSequence:
10300 OS << "Normal sequence: ";
10301 break;
10302 }
10303
10304 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10305 if (S != step_begin()) {
10306 OS << " -> ";
10307 }
10308
10309 switch (S->Kind) {
10310 case SK_ResolveAddressOfOverloadedFunction:
10311 OS << "resolve address of overloaded function";
10312 break;
10313
10314 case SK_CastDerivedToBasePRValue:
10315 OS << "derived-to-base (prvalue)";
10316 break;
10317
10318 case SK_CastDerivedToBaseXValue:
10319 OS << "derived-to-base (xvalue)";
10320 break;
10321
10322 case SK_CastDerivedToBaseLValue:
10323 OS << "derived-to-base (lvalue)";
10324 break;
10325
10326 case SK_BindReference:
10327 OS << "bind reference to lvalue";
10328 break;
10329
10330 case SK_BindReferenceToTemporary:
10331 OS << "bind reference to a temporary";
10332 break;
10333
10334 case SK_FinalCopy:
10335 OS << "final copy in class direct-initialization";
10336 break;
10337
10338 case SK_ExtraneousCopyToTemporary:
10339 OS << "extraneous C++03 copy to temporary";
10340 break;
10341
10342 case SK_UserConversion:
10343 OS << "user-defined conversion via " << *S->Function.Function;
10344 break;
10345
10346 case SK_QualificationConversionPRValue:
10347 OS << "qualification conversion (prvalue)";
10348 break;
10349
10350 case SK_QualificationConversionXValue:
10351 OS << "qualification conversion (xvalue)";
10352 break;
10353
10354 case SK_QualificationConversionLValue:
10355 OS << "qualification conversion (lvalue)";
10356 break;
10357
10358 case SK_FunctionReferenceConversion:
10359 OS << "function reference conversion";
10360 break;
10361
10362 case SK_AtomicConversion:
10363 OS << "non-atomic-to-atomic conversion";
10364 break;
10365
10366 case SK_ConversionSequence:
10367 OS << "implicit conversion sequence (";
10368 S->ICS->dump(); // FIXME: use OS
10369 OS << ")";
10370 break;
10371
10372 case SK_ConversionSequenceNoNarrowing:
10373 OS << "implicit conversion sequence with narrowing prohibited (";
10374 S->ICS->dump(); // FIXME: use OS
10375 OS << ")";
10376 break;
10377
10378 case SK_ListInitialization:
10379 OS << "list aggregate initialization";
10380 break;
10381
10382 case SK_UnwrapInitList:
10383 OS << "unwrap reference initializer list";
10384 break;
10385
10386 case SK_RewrapInitList:
10387 OS << "rewrap reference initializer list";
10388 break;
10389
10390 case SK_ConstructorInitialization:
10391 OS << "constructor initialization";
10392 break;
10393
10394 case SK_ConstructorInitializationFromList:
10395 OS << "list initialization via constructor";
10396 break;
10397
10398 case SK_ZeroInitialization:
10399 OS << "zero initialization";
10400 break;
10401
10402 case SK_CAssignment:
10403 OS << "C assignment";
10404 break;
10405
10406 case SK_StringInit:
10407 OS << "string initialization";
10408 break;
10409
10410 case SK_ObjCObjectConversion:
10411 OS << "Objective-C object conversion";
10412 break;
10413
10414 case SK_ArrayLoopIndex:
10415 OS << "indexing for array initialization loop";
10416 break;
10417
10418 case SK_ArrayLoopInit:
10419 OS << "array initialization loop";
10420 break;
10421
10422 case SK_ArrayInit:
10423 OS << "array initialization";
10424 break;
10425
10426 case SK_GNUArrayInit:
10427 OS << "array initialization (GNU extension)";
10428 break;
10429
10430 case SK_ParenthesizedArrayInit:
10431 OS << "parenthesized array initialization";
10432 break;
10433
10434 case SK_PassByIndirectCopyRestore:
10435 OS << "pass by indirect copy and restore";
10436 break;
10437
10438 case SK_PassByIndirectRestore:
10439 OS << "pass by indirect restore";
10440 break;
10441
10442 case SK_ProduceObjCObject:
10443 OS << "Objective-C object retension";
10444 break;
10445
10446 case SK_StdInitializerList:
10447 OS << "std::initializer_list from initializer list";
10448 break;
10449
10450 case SK_StdInitializerListConstructorCall:
10451 OS << "list initialization from std::initializer_list";
10452 break;
10453
10454 case SK_OCLSamplerInit:
10455 OS << "OpenCL sampler_t from integer constant";
10456 break;
10457
10458 case SK_OCLZeroOpaqueType:
10459 OS << "OpenCL opaque type from zero";
10460 break;
10461 case SK_ParenthesizedListInit:
10462 OS << "initialization from a parenthesized list of values";
10463 break;
10464 }
10465
10466 OS << " [" << S->Type << ']';
10467 }
10468
10469 OS << '\n';
10470}
10471
10472void InitializationSequence::dump() const {
10473 dump(OS&: llvm::errs());
10474}
10475
10476static void DiagnoseNarrowingInInitList(Sema &S,
10477 const ImplicitConversionSequence &ICS,
10478 QualType PreNarrowingType,
10479 QualType EntityType,
10480 const Expr *PostInit) {
10481 const StandardConversionSequence *SCS = nullptr;
10482 switch (ICS.getKind()) {
10483 case ImplicitConversionSequence::StandardConversion:
10484 SCS = &ICS.Standard;
10485 break;
10486 case ImplicitConversionSequence::UserDefinedConversion:
10487 SCS = &ICS.UserDefined.After;
10488 break;
10489 case ImplicitConversionSequence::AmbiguousConversion:
10490 case ImplicitConversionSequence::StaticObjectArgumentConversion:
10491 case ImplicitConversionSequence::EllipsisConversion:
10492 case ImplicitConversionSequence::BadConversion:
10493 return;
10494 }
10495
10496 auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
10497 unsigned ConstRefDiagID, unsigned WarnDiagID) {
10498 unsigned DiagID;
10499 auto &L = S.getLangOpts();
10500 if (L.CPlusPlus11 &&
10501 (!L.MicrosoftExt || L.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)))
10502 DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
10503 else
10504 DiagID = WarnDiagID;
10505 return S.Diag(PostInit->getBeginLoc(), DiagID)
10506 << PostInit->getSourceRange();
10507 };
10508
10509 // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10510 APValue ConstantValue;
10511 QualType ConstantType;
10512 switch (SCS->getNarrowingKind(Context&: S.Context, Converted: PostInit, ConstantValue,
10513 ConstantType)) {
10514 case NK_Not_Narrowing:
10515 case NK_Dependent_Narrowing:
10516 // No narrowing occurred.
10517 return;
10518
10519 case NK_Type_Narrowing: {
10520 // This was a floating-to-integer conversion, which is always considered a
10521 // narrowing conversion even if the value is a constant and can be
10522 // represented exactly as an integer.
10523 QualType T = EntityType.getNonReferenceType();
10524 MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10525 diag::ext_init_list_type_narrowing_const_reference,
10526 diag::warn_init_list_type_narrowing)
10527 << PreNarrowingType.getLocalUnqualifiedType()
10528 << T.getLocalUnqualifiedType();
10529 break;
10530 }
10531
10532 case NK_Constant_Narrowing: {
10533 // A constant value was narrowed.
10534 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10535 diag::ext_init_list_constant_narrowing,
10536 diag::ext_init_list_constant_narrowing_const_reference,
10537 diag::warn_init_list_constant_narrowing)
10538 << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10539 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10540 break;
10541 }
10542
10543 case NK_Variable_Narrowing: {
10544 // A variable's value may have been narrowed.
10545 MakeDiag(EntityType.getNonReferenceType() != EntityType,
10546 diag::ext_init_list_variable_narrowing,
10547 diag::ext_init_list_variable_narrowing_const_reference,
10548 diag::warn_init_list_variable_narrowing)
10549 << PreNarrowingType.getLocalUnqualifiedType()
10550 << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10551 break;
10552 }
10553 }
10554
10555 SmallString<128> StaticCast;
10556 llvm::raw_svector_ostream OS(StaticCast);
10557 OS << "static_cast<";
10558 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10559 // It's important to use the typedef's name if there is one so that the
10560 // fixit doesn't break code using types like int64_t.
10561 //
10562 // FIXME: This will break if the typedef requires qualification. But
10563 // getQualifiedNameAsString() includes non-machine-parsable components.
10564 OS << *TT->getDecl();
10565 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10566 OS << BT->getName(Policy: S.getLangOpts());
10567 else {
10568 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
10569 // with a broken cast.
10570 return;
10571 }
10572 OS << ">(";
10573 S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10574 << PostInit->getSourceRange()
10575 << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10576 << FixItHint::CreateInsertion(
10577 S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10578}
10579
10580static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType,
10581 QualType ToType, Expr *Init) {
10582 assert(S.getLangOpts().C23);
10583 ImplicitConversionSequence ICS = S.TryImplicitConversion(
10584 From: Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false,
10585 AllowExplicit: Sema::AllowedExplicit::None,
10586 /*InOverloadResolution*/ false,
10587 /*CStyle*/ false,
10588 /*AllowObjCWritebackConversion=*/false);
10589
10590 if (!ICS.isStandard())
10591 return;
10592
10593 APValue Value;
10594 QualType PreNarrowingType;
10595 // Reuse C++ narrowing check.
10596 switch (ICS.Standard.getNarrowingKind(
10597 Context&: S.Context, Converted: Init, ConstantValue&: Value, ConstantType&: PreNarrowingType,
10598 /*IgnoreFloatToIntegralConversion*/ false)) {
10599 // The value doesn't fit.
10600 case NK_Constant_Narrowing:
10601 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_not_representable)
10602 << Value.getAsString(S.Context, PreNarrowingType) << ToType;
10603 return;
10604
10605 // Conversion to a narrower type.
10606 case NK_Type_Narrowing:
10607 S.Diag(Init->getBeginLoc(), diag::err_c23_constexpr_init_type_mismatch)
10608 << ToType << FromType;
10609 return;
10610
10611 // Since we only reuse narrowing check for C23 constexpr variables here, we're
10612 // not really interested in these cases.
10613 case NK_Dependent_Narrowing:
10614 case NK_Variable_Narrowing:
10615 case NK_Not_Narrowing:
10616 return;
10617 }
10618 llvm_unreachable("unhandled case in switch");
10619}
10620
10621static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE,
10622 Sema &SemaRef, QualType &TT) {
10623 assert(SemaRef.getLangOpts().C23);
10624 // character that string literal contains fits into TT - target type.
10625 const ArrayType *AT = SemaRef.Context.getAsArrayType(T: TT);
10626 QualType CharType = AT->getElementType();
10627 uint32_t BitWidth = SemaRef.Context.getTypeSize(T: CharType);
10628 bool isUnsigned = CharType->isUnsignedIntegerType();
10629 llvm::APSInt Value(BitWidth, isUnsigned);
10630 for (unsigned I = 0, N = SE->getLength(); I != N; ++I) {
10631 int64_t C = SE->getCodeUnitS(I, BitWidth: SemaRef.Context.getCharWidth());
10632 Value = C;
10633 if (Value != C) {
10634 SemaRef.Diag(SemaRef.getLocationOfStringLiteralByte(SE, I),
10635 diag::err_c23_constexpr_init_not_representable)
10636 << C << CharType;
10637 return;
10638 }
10639 }
10640 return;
10641}
10642
10643//===----------------------------------------------------------------------===//
10644// Initialization helper functions
10645//===----------------------------------------------------------------------===//
10646bool
10647Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10648 ExprResult Init) {
10649 if (Init.isInvalid())
10650 return false;
10651
10652 Expr *InitE = Init.get();
10653 assert(InitE && "No initialization expression");
10654
10655 InitializationKind Kind =
10656 InitializationKind::CreateCopy(InitLoc: InitE->getBeginLoc(), EqualLoc: SourceLocation());
10657 InitializationSequence Seq(*this, Entity, Kind, InitE);
10658 return !Seq.Failed();
10659}
10660
10661ExprResult
10662Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10663 SourceLocation EqualLoc,
10664 ExprResult Init,
10665 bool TopLevelOfInitList,
10666 bool AllowExplicit) {
10667 if (Init.isInvalid())
10668 return ExprError();
10669
10670 Expr *InitE = Init.get();
10671 assert(InitE && "No initialization expression?");
10672
10673 if (EqualLoc.isInvalid())
10674 EqualLoc = InitE->getBeginLoc();
10675
10676 InitializationKind Kind = InitializationKind::CreateCopy(
10677 InitLoc: InitE->getBeginLoc(), EqualLoc, AllowExplicitConvs: AllowExplicit);
10678 InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10679
10680 // Prevent infinite recursion when performing parameter copy-initialization.
10681 const bool ShouldTrackCopy =
10682 Entity.isParameterKind() && Seq.isConstructorInitialization();
10683 if (ShouldTrackCopy) {
10684 if (llvm::is_contained(Range&: CurrentParameterCopyTypes, Element: Entity.getType())) {
10685 Seq.SetOverloadFailure(
10686 Failure: InitializationSequence::FK_ConstructorOverloadFailed,
10687 Result: OR_No_Viable_Function);
10688
10689 // Try to give a meaningful diagnostic note for the problematic
10690 // constructor.
10691 const auto LastStep = Seq.step_end() - 1;
10692 assert(LastStep->Kind ==
10693 InitializationSequence::SK_ConstructorInitialization);
10694 const FunctionDecl *Function = LastStep->Function.Function;
10695 auto Candidate =
10696 llvm::find_if(Range&: Seq.getFailedCandidateSet(),
10697 P: [Function](const OverloadCandidate &Candidate) -> bool {
10698 return Candidate.Viable &&
10699 Candidate.Function == Function &&
10700 Candidate.Conversions.size() > 0;
10701 });
10702 if (Candidate != Seq.getFailedCandidateSet().end() &&
10703 Function->getNumParams() > 0) {
10704 Candidate->Viable = false;
10705 Candidate->FailureKind = ovl_fail_bad_conversion;
10706 Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
10707 InitE,
10708 Function->getParamDecl(i: 0)->getType());
10709 }
10710 }
10711 CurrentParameterCopyTypes.push_back(Elt: Entity.getType());
10712 }
10713
10714 ExprResult Result = Seq.Perform(S&: *this, Entity, Kind, Args: InitE);
10715
10716 if (ShouldTrackCopy)
10717 CurrentParameterCopyTypes.pop_back();
10718
10719 return Result;
10720}
10721
10722/// Determine whether RD is, or is derived from, a specialization of CTD.
10723static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10724 ClassTemplateDecl *CTD) {
10725 auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10726 auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Candidate);
10727 return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10728 };
10729 return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10730}
10731
10732QualType Sema::DeduceTemplateSpecializationFromInitializer(
10733 TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10734 const InitializationKind &Kind, MultiExprArg Inits) {
10735 auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10736 TSInfo->getType()->getContainedDeducedType());
10737 assert(DeducedTST && "not a deduced template specialization type");
10738
10739 auto TemplateName = DeducedTST->getTemplateName();
10740 if (TemplateName.isDependent())
10741 return SubstAutoTypeDependent(TypeWithAuto: TSInfo->getType());
10742
10743 // We can only perform deduction for class templates or alias templates.
10744 auto *Template =
10745 dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10746 TemplateDecl *LookupTemplateDecl = Template;
10747 if (!Template) {
10748 if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>(
10749 TemplateName.getAsTemplateDecl())) {
10750 Diag(Kind.getLocation(),
10751 diag::warn_cxx17_compat_ctad_for_alias_templates);
10752 LookupTemplateDecl = AliasTemplate;
10753 auto UnderlyingType = AliasTemplate->getTemplatedDecl()
10754 ->getUnderlyingType()
10755 .getCanonicalType();
10756 // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be
10757 // of the form
10758 // [typename] [nested-name-specifier] [template] simple-template-id
10759 if (const auto *TST =
10760 UnderlyingType->getAs<TemplateSpecializationType>()) {
10761 Template = dyn_cast_or_null<ClassTemplateDecl>(
10762 TST->getTemplateName().getAsTemplateDecl());
10763 } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) {
10764 // Cases where template arguments in the RHS of the alias are not
10765 // dependent. e.g.
10766 // using AliasFoo = Foo<bool>;
10767 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
10768 RT->getAsCXXRecordDecl()))
10769 Template = CTSD->getSpecializedTemplate();
10770 }
10771 }
10772 }
10773 if (!Template) {
10774 Diag(Kind.getLocation(),
10775 diag::err_deduced_non_class_or_alias_template_specialization_type)
10776 << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10777 if (auto *TD = TemplateName.getAsTemplateDecl())
10778 NoteTemplateLocation(Decl: *TD);
10779 return QualType();
10780 }
10781
10782 // Can't deduce from dependent arguments.
10783 if (Expr::hasAnyTypeDependentArguments(Exprs: Inits)) {
10784 Diag(TSInfo->getTypeLoc().getBeginLoc(),
10785 diag::warn_cxx14_compat_class_template_argument_deduction)
10786 << TSInfo->getTypeLoc().getSourceRange() << 0;
10787 return SubstAutoTypeDependent(TypeWithAuto: TSInfo->getType());
10788 }
10789
10790 // FIXME: Perform "exact type" matching first, per CWG discussion?
10791 // Or implement this via an implied 'T(T) -> T' deduction guide?
10792
10793 // FIXME: Do we need/want a std::initializer_list<T> special case?
10794
10795 // Look up deduction guides, including those synthesized from constructors.
10796 //
10797 // C++1z [over.match.class.deduct]p1:
10798 // A set of functions and function templates is formed comprising:
10799 // - For each constructor of the class template designated by the
10800 // template-name, a function template [...]
10801 // - For each deduction-guide, a function or function template [...]
10802 DeclarationNameInfo NameInfo(
10803 Context.DeclarationNames.getCXXDeductionGuideName(TD: LookupTemplateDecl),
10804 TSInfo->getTypeLoc().getEndLoc());
10805 LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10806 LookupQualifiedName(Guides, LookupTemplateDecl->getDeclContext());
10807
10808 // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10809 // clear on this, but they're not found by name so access does not apply.
10810 Guides.suppressDiagnostics();
10811
10812 // Figure out if this is list-initialization.
10813 InitListExpr *ListInit =
10814 (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10815 ? dyn_cast<InitListExpr>(Val: Inits[0])
10816 : nullptr;
10817
10818 // C++1z [over.match.class.deduct]p1:
10819 // Initialization and overload resolution are performed as described in
10820 // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10821 // (as appropriate for the type of initialization performed) for an object
10822 // of a hypothetical class type, where the selected functions and function
10823 // templates are considered to be the constructors of that class type
10824 //
10825 // Since we know we're initializing a class type of a type unrelated to that
10826 // of the initializer, this reduces to something fairly reasonable.
10827 OverloadCandidateSet Candidates(Kind.getLocation(),
10828 OverloadCandidateSet::CSK_Normal);
10829 OverloadCandidateSet::iterator Best;
10830
10831 bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10832
10833 // Return true if the candidate is added successfully, false otherwise.
10834 auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10835 CXXDeductionGuideDecl *GD,
10836 DeclAccessPair FoundDecl,
10837 bool OnlyListConstructors,
10838 bool AllowAggregateDeductionCandidate) {
10839 // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10840 // For copy-initialization, the candidate functions are all the
10841 // converting constructors (12.3.1) of that class.
10842 // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10843 // The converting constructors of T are candidate functions.
10844 if (!AllowExplicit) {
10845 // Overload resolution checks whether the deduction guide is declared
10846 // explicit for us.
10847
10848 // When looking for a converting constructor, deduction guides that
10849 // could never be called with one argument are not interesting to
10850 // check or note.
10851 if (GD->getMinRequiredArguments() > 1 ||
10852 (GD->getNumParams() == 0 && !GD->isVariadic()))
10853 return;
10854 }
10855
10856 // C++ [over.match.list]p1.1: (first phase list initialization)
10857 // Initially, the candidate functions are the initializer-list
10858 // constructors of the class T
10859 if (OnlyListConstructors && !isInitListConstructor(GD))
10860 return;
10861
10862 if (!AllowAggregateDeductionCandidate &&
10863 GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10864 return;
10865
10866 // C++ [over.match.list]p1.2: (second phase list initialization)
10867 // the candidate functions are all the constructors of the class T
10868 // C++ [over.match.ctor]p1: (all other cases)
10869 // the candidate functions are all the constructors of the class of
10870 // the object being initialized
10871
10872 // C++ [over.best.ics]p4:
10873 // When [...] the constructor [...] is a candidate by
10874 // - [over.match.copy] (in all cases)
10875 // FIXME: The "second phase of [over.match.list] case can also
10876 // theoretically happen here, but it's not clear whether we can
10877 // ever have a parameter of the right type.
10878 bool SuppressUserConversions = Kind.isCopyInit();
10879
10880 if (TD) {
10881 SmallVector<Expr *, 8> TmpInits;
10882 for (Expr *E : Inits)
10883 if (auto *DI = dyn_cast<DesignatedInitExpr>(Val: E))
10884 TmpInits.push_back(Elt: DI->getInit());
10885 else
10886 TmpInits.push_back(Elt: E);
10887 AddTemplateOverloadCandidate(
10888 FunctionTemplate: TD, FoundDecl, /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, Args: TmpInits, CandidateSet&: Candidates,
10889 SuppressUserConversions,
10890 /*PartialOverloading=*/false, AllowExplicit, IsADLCandidate: ADLCallKind::NotADL,
10891 /*PO=*/{}, AggregateCandidateDeduction: AllowAggregateDeductionCandidate);
10892 } else {
10893 AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10894 SuppressUserConversions,
10895 /*PartialOverloading=*/false, AllowExplicit);
10896 }
10897 };
10898
10899 bool FoundDeductionGuide = false;
10900
10901 auto TryToResolveOverload =
10902 [&](bool OnlyListConstructors) -> OverloadingResult {
10903 Candidates.clear(CSK: OverloadCandidateSet::CSK_Normal);
10904 bool HasAnyDeductionGuide = false;
10905
10906 auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10907 auto *Pattern = Template;
10908 while (Pattern->getInstantiatedFromMemberTemplate()) {
10909 if (Pattern->isMemberSpecialization())
10910 break;
10911 Pattern = Pattern->getInstantiatedFromMemberTemplate();
10912 }
10913
10914 auto *RD = cast<CXXRecordDecl>(Pattern->getTemplatedDecl());
10915 if (!(RD->getDefinition() && RD->isAggregate()))
10916 return;
10917 QualType Ty = Context.getRecordType(Decl: RD);
10918 SmallVector<QualType, 8> ElementTypes;
10919
10920 InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10921 if (!CheckInitList.HadError()) {
10922 // C++ [over.match.class.deduct]p1.8:
10923 // if e_i is of array type and x_i is a braced-init-list, T_i is an
10924 // rvalue reference to the declared type of e_i and
10925 // C++ [over.match.class.deduct]p1.9:
10926 // if e_i is of array type and x_i is a bstring-literal, T_i is an
10927 // lvalue reference to the const-qualified declared type of e_i and
10928 // C++ [over.match.class.deduct]p1.10:
10929 // otherwise, T_i is the declared type of e_i
10930 for (int I = 0, E = ListInit->getNumInits();
10931 I < E && !isa<PackExpansionType>(Val: ElementTypes[I]); ++I)
10932 if (ElementTypes[I]->isArrayType()) {
10933 if (isa<InitListExpr>(Val: ListInit->getInit(Init: I)))
10934 ElementTypes[I] = Context.getRValueReferenceType(T: ElementTypes[I]);
10935 else if (isa<StringLiteral>(
10936 Val: ListInit->getInit(Init: I)->IgnoreParenImpCasts()))
10937 ElementTypes[I] =
10938 Context.getLValueReferenceType(T: ElementTypes[I].withConst());
10939 }
10940
10941 if (FunctionTemplateDecl *TD =
10942 DeclareAggregateDeductionGuideFromInitList(
10943 Template: LookupTemplateDecl, ParamTypes: ElementTypes,
10944 Loc: TSInfo->getTypeLoc().getEndLoc())) {
10945 auto *GD = cast<CXXDeductionGuideDecl>(Val: TD->getTemplatedDecl());
10946 addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10947 OnlyListConstructors,
10948 /*AllowAggregateDeductionCandidate=*/true);
10949 HasAnyDeductionGuide = true;
10950 }
10951 }
10952 };
10953
10954 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10955 NamedDecl *D = (*I)->getUnderlyingDecl();
10956 if (D->isInvalidDecl())
10957 continue;
10958
10959 auto *TD = dyn_cast<FunctionTemplateDecl>(Val: D);
10960 auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10961 TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(Val: D));
10962 if (!GD)
10963 continue;
10964
10965 if (!GD->isImplicit())
10966 HasAnyDeductionGuide = true;
10967
10968 addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10969 /*AllowAggregateDeductionCandidate=*/false);
10970 }
10971
10972 // C++ [over.match.class.deduct]p1.4:
10973 // if C is defined and its definition satisfies the conditions for an
10974 // aggregate class ([dcl.init.aggr]) with the assumption that any
10975 // dependent base class has no virtual functions and no virtual base
10976 // classes, and the initializer is a non-empty braced-init-list or
10977 // parenthesized expression-list, and there are no deduction-guides for
10978 // C, the set contains an additional function template, called the
10979 // aggregate deduction candidate, defined as follows.
10980 if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10981 if (ListInit && ListInit->getNumInits()) {
10982 SynthesizeAggrGuide(ListInit);
10983 } else if (Inits.size()) { // parenthesized expression-list
10984 // Inits are expressions inside the parentheses. We don't have
10985 // the parentheses source locations, use the begin/end of Inits as the
10986 // best heuristic.
10987 InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10988 Inits, Inits.back()->getEndLoc());
10989 SynthesizeAggrGuide(&TempListInit);
10990 }
10991 }
10992
10993 FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10994
10995 return Candidates.BestViableFunction(S&: *this, Loc: Kind.getLocation(), Best);
10996 };
10997
10998 OverloadingResult Result = OR_No_Viable_Function;
10999
11000 // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
11001 // try initializer-list constructors.
11002 if (ListInit) {
11003 bool TryListConstructors = true;
11004
11005 // Try list constructors unless the list is empty and the class has one or
11006 // more default constructors, in which case those constructors win.
11007 if (!ListInit->getNumInits()) {
11008 for (NamedDecl *D : Guides) {
11009 auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
11010 if (FD && FD->getMinRequiredArguments() == 0) {
11011 TryListConstructors = false;
11012 break;
11013 }
11014 }
11015 } else if (ListInit->getNumInits() == 1) {
11016 // C++ [over.match.class.deduct]:
11017 // As an exception, the first phase in [over.match.list] (considering
11018 // initializer-list constructors) is omitted if the initializer list
11019 // consists of a single expression of type cv U, where U is a
11020 // specialization of C or a class derived from a specialization of C.
11021 Expr *E = ListInit->getInit(Init: 0);
11022 auto *RD = E->getType()->getAsCXXRecordDecl();
11023 if (!isa<InitListExpr>(Val: E) && RD &&
11024 isCompleteType(Loc: Kind.getLocation(), T: E->getType()) &&
11025 isOrIsDerivedFromSpecializationOf(RD, Template))
11026 TryListConstructors = false;
11027 }
11028
11029 if (TryListConstructors)
11030 Result = TryToResolveOverload(/*OnlyListConstructor*/true);
11031 // Then unwrap the initializer list and try again considering all
11032 // constructors.
11033 Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
11034 }
11035
11036 // If list-initialization fails, or if we're doing any other kind of
11037 // initialization, we (eventually) consider constructors.
11038 if (Result == OR_No_Viable_Function)
11039 Result = TryToResolveOverload(/*OnlyListConstructor*/false);
11040
11041 switch (Result) {
11042 case OR_Ambiguous:
11043 // FIXME: For list-initialization candidates, it'd usually be better to
11044 // list why they were not viable when given the initializer list itself as
11045 // an argument.
11046 Candidates.NoteCandidates(
11047 PartialDiagnosticAt(
11048 Kind.getLocation(),
11049 PDiag(diag::err_deduced_class_template_ctor_ambiguous)
11050 << TemplateName),
11051 *this, OCD_AmbiguousCandidates, Inits);
11052 return QualType();
11053
11054 case OR_No_Viable_Function: {
11055 CXXRecordDecl *Primary =
11056 cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
11057 bool Complete =
11058 isCompleteType(Loc: Kind.getLocation(), T: Context.getTypeDeclType(Primary));
11059 Candidates.NoteCandidates(
11060 PartialDiagnosticAt(
11061 Kind.getLocation(),
11062 PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
11063 : diag::err_deduced_class_template_incomplete)
11064 << TemplateName << !Guides.empty()),
11065 *this, OCD_AllCandidates, Inits);
11066 return QualType();
11067 }
11068
11069 case OR_Deleted: {
11070 // FIXME: There are no tests for this diagnostic, and it doesn't seem
11071 // like we ever get here; attempts to trigger this seem to yield a
11072 // generic c'all to deleted function' diagnostic instead.
11073 Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
11074 << TemplateName;
11075 NoteDeletedFunction(FD: Best->Function);
11076 return QualType();
11077 }
11078
11079 case OR_Success:
11080 // C++ [over.match.list]p1:
11081 // In copy-list-initialization, if an explicit constructor is chosen, the
11082 // initialization is ill-formed.
11083 if (Kind.isCopyInit() && ListInit &&
11084 cast<CXXDeductionGuideDecl>(Val: Best->Function)->isExplicit()) {
11085 bool IsDeductionGuide = !Best->Function->isImplicit();
11086 Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
11087 << TemplateName << IsDeductionGuide;
11088 Diag(Best->Function->getLocation(),
11089 diag::note_explicit_ctor_deduction_guide_here)
11090 << IsDeductionGuide;
11091 return QualType();
11092 }
11093
11094 // Make sure we didn't select an unusable deduction guide, and mark it
11095 // as referenced.
11096 DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: Kind.getLocation());
11097 MarkFunctionReferenced(Loc: Kind.getLocation(), Func: Best->Function);
11098 break;
11099 }
11100
11101 // C++ [dcl.type.class.deduct]p1:
11102 // The placeholder is replaced by the return type of the function selected
11103 // by overload resolution for class template deduction.
11104 QualType DeducedType =
11105 SubstAutoType(TypeWithAuto: TSInfo->getType(), Replacement: Best->Function->getReturnType());
11106 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11107 diag::warn_cxx14_compat_class_template_argument_deduction)
11108 << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
11109
11110 // Warn if CTAD was used on a type that does not have any user-defined
11111 // deduction guides.
11112 if (!FoundDeductionGuide) {
11113 Diag(TSInfo->getTypeLoc().getBeginLoc(),
11114 diag::warn_ctad_maybe_unsupported)
11115 << TemplateName;
11116 Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
11117 }
11118
11119 return DeducedType;
11120}
11121

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